Kashkain
Kashkain

Reputation: 523

openssl_encrypt 256 CBC raw_data in java

I try to do a PHP openssl_encrypt aes-256-cbc with OPENSSL_RAW_DATA in java 6 without success. I found some topic about this, but I'ved successful only to do it in aes-128-cbc without raw_data. The best topic I founded about this it's : AES-256 CBC encrypt in php and decrypt in Java or vice-versa But the raw_data doesn't work and the 256 bits key is randomly generated. In fact the Php version is :

<?php>
    openssl(
        "hello",
        "aes-256-cbc",
        "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
        OPENSSL_RAW_DATA,
        "aaaaaaaaaaaaaaaa"
    )
?>

And I actually have this :

public static void main(String[] args) {
    try {
        // 128 bits key
        openssl_encrypt("hello", "bbbbbbbbbbbbbbbb", "aaaaaaaaaaaaaaaa");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
    Base64 base64 = new Base64();
    Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
    IvParameterSpec iv = new IvParameterSpec(strIv.getBytes("UTF-8"), 0, ciper.getBlockSize());

    // Encrypt
    ciper.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encryptedCiperBytes = base64.encode((ciper.doFinal(data.getBytes())));

    String s = new String(encryptedCiperBytes);
    System.out.println("Ciper : " + s);
    return s;
}

Upvotes: 0

Views: 7234

Answers (1)

Kashkain
Kashkain

Reputation: 523

After few modification and some testing I found it :

private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
    Base64 base64 = new Base64();
    Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
    IvParameterSpec iv = new IvParameterSpec(strIv.getBytes(), 0, ciper.getBlockSize());

    // Encrypt
    ciper.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encryptedCiperBytes = ciper.doFinal(data.getBytes());

    String s = new String(encryptedCiperBytes);
    System.out.println("Ciper : " + s);
    return s;
}

openssl_encrypt in PHP don't convert his result in base64, and I also use getBytes() without param cause, for some keys, I had an error about the key's lentgh.

So this method do the same thing than :

<?php>
    openssl_encrypt(data, "aes-256-cbc", key, OPENSSL_RAW_DATA, iv);
?>

Upvotes: 6

Related Questions