2010-08-27 80 views
1

我正在使用Ruby實現Java庫。我遇到了以下路障。是否有可能在ruby中實現下面的代碼?有沒有任何紅寶石等價物的字節[],IvParameterSpec,SecretKeySpec?Ruby等效

private String decrypt(String token) 
{  
//parse token into its IV and token components 
byte[] ivAndToken = Base64.decodeBase64(token); 
byte[] iv = new byte[ivLength]; 
System.arraycopy(ivAndToken, 0, iv, 0, ivLength); 

int length = ivAndToken.length - ivLength; 
byte[] tokenBytes = new byte[length]; 
System.arraycopy(ivAndToken, ivLength, tokenBytes, 0, length); 

//prepare initialization vector specification 
IvParameterSpec spec = new IvParameterSpec(iv); 

//create cipher instance based on transformer params 
Cipher cipher = Cipher.getInstance(algorithm + mode + padding, CRYPTO_PROVIDER); 

//convert key bytes into valid key format 
Key key = new SecretKeySpec(Base64.decodeBase64(symkey), algorithm); 

//initialize cipher for decryption 
cipher.init(Cipher.DECRYPT_MODE, key, spec); 

//decrypt the payload 
String plaintext = new String(cipher.doFinal(tokenBytes)); 

return plaintext; 

} 
+1

如果你使用jruby,你可以包裝你的java代碼...... – rogerdpack 2010-08-28 17:05:19

回答

1

你可能必須執行關於Ruby都IvParameterSpecSecretKeySpec如果希望算法表現得完全像它在Java中。 byte[]當然只是一個字節數組。你可能想在他們的文檔(上面的鏈接),也希望你瞭解塊密碼操作模式的工作。

如果不這樣做,SecretKey指的是對稱密鑰(例如:密碼短語),IV是initialization vector,用於對同一明文的不同加密生成不同的密文的密碼nonce。除ECB外,所有操作模式都需要IV。有關更多詳細信息,請參閱此wikipedia page

+0

如果你在Java中使用'byte',你可能想在Ruby中使用一個字符串,並且所有的字符串/數組打包和解包功能 – horseyguy 2010-08-28 01:42:20