Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 :
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;
–
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 :
openssl_encrypt(data, "aes-256-cbc", key, OPENSSL_RAW_DATA, iv);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.