tags:

views:

63

answers:

1
+1  Q: 

Ruby Equivalent

I am in the process of implementing a Java library in Ruby. I have come across the following road block. Is it possible to implement the following code in ruby? Are there any ruby equivalents for byte[], IvParameterSpec, SecretKeySpec ?

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  A: 

You'll probably have to implement both IvParameterSpec and SecretKeySpec on Ruby if you want the algorithm to behave exactly like it does in Java. byte[] is of course just a byte array. You'll probably want to at the docs for them (links above) and also hopefully you understand block cipher operation modes work.

If you don't, SecretKey refers to the symmetric key (eg: the passphrase), and IV is the initialization vector, a cryptographic nonce used to make different encryptions of the same plaintext generate different ciphertext. IV's are needed for all operation modes except ECB. See this wikipedia page for more details.

NullUserException
If you're using `byte` in Java, you probably want to use a string in Ruby, and all the string/array packing and unpacking functions
banister