1

I have a legacy code in ruby that does the encryption using OpenSSL
However, I would like to translate this in Java and I am lost. so far my biggest blocker is figuring out how to generate the IV based on this code. Any help would be greatly appreciated

    def func_enc(data, key)
        cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
        cipher.encrypt
        cipher.pkcs5_keyivgen(key)
        cipher.update(data)
        encrypted_data << cipher.final
        return encryptedData
    end

EDIT
Just to clarify, I would like to use Java Crypto for this. This is the code I came up with so far:

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithMD5And256AES-CBC");
    KeySpec spec = new PBEKeySpec("Password".toCharArray(), null, 2048, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();

but "PBKDF2WithMD5And256AES-CBC" does not have any provider and I get NoSuchAlgorithm exception.

    java.security.NoSuchAlgorithmException: PBKDF2WithMD5And256AES-CBC SecretKeyFactory not available

Also the salt that pkcs5_keyivgen uses by default is null!! I am not sure if Java lets me use a null salt.

How can I generate the correct IV ?

  • Give a look to this: http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption – Aguardientico Jun 26 '13 at 04:39
  • Is there some reason you can't take advantage of an existing encryption library? It's much better reuse existing and well-tested wheels. – the Tin Man Jun 26 '13 at 05:18
  • Read the documentation: http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory – rossum Jun 26 '13 at 11:54
  • I have read the documentation but non provide "PBKDF2WithMD5And256AES-CBC" (Maybe I have the name wrong?, should it be PBEWithMD5AndAES?). Also , when ruby code encrypts the data, the only thing the is returned is the cipher text. When I do the decryption how do I retrieve the IV from the key? – Emad Koling Jun 26 '13 at 14:22
  • anyone can help me with this? I am really stuck ! – Emad Koling Jun 27 '13 at 14:46

1 Answers1

0

The warning on this documentation page suggests that the deprecated pkcs5_keyivgen method does something non-standard when used together with AES. First of all, it uses PBKDF1, not PBKDF2.

It might be difficult to replicate what it does, and implementing cryptographic algorithms is generally inadvisable unless you know exactly what you're doing – even experts often get it wrong.

ntoskrnl
  • 5,714
  • 2
  • 27
  • 31