MySql and Java interoperability in AES 256 encryption/decryption
P粉937769356
P粉937769356 2024-03-27 21:26:09
0
1
392

The following encryption and decryption work normally in mysql (aes-256-cbc) mode

SET block_encryption_mode = 'aes-256-cbc';

select
cast(
aes_decrypt(
from_base64('StThdNXA+CWvlg+of/heJQ=='),
sha2(concat('ssshhhhhhhhhhh!!','ENCRYPTION_KEY$&'),256),
'ssshhhhhhhhhhh!!'
)
as char);

select to_base64(aes_encrypt(
'test_value',
sha2(concat('ssshhhhhhhhhhh!!','ENCRYPTION_KEY$&'),256),
'ssshhhhhhhhhhh!!'
));

I'm trying to decrypt a value encrypted in mysql without success.

The following is the key in my mysql query sha256 (salt key)

select sha2(concat('ssshhhhhhhhhhh!!','ENCRYPTION_KEY$&'),256);

Same value as I was able to get in java:

Hashing.sha256().hashString("ssshhhhhhhhhhh!!ENCRYPTION_KEY$&", StandardCharsets.UTF_8).toString();

Is there a custom way to make bouncy castle/other APIs use the same key for decryption?

P粉937769356
P粉937769356

reply all(1)
P粉239089443

MySQL uses the OpenSSL algorithm internally, using EVP_BytesToKey as the derivation function. Look at this URL

MySQL encryption and decryption example:

SET block_encryption_mode = 'aes-128-cbc';
SET block_encryption_mode = 'aes-256-cbc';
select 
cast(
    aes_decrypt(
        from_base64('MKicK+vAcZkq/g3wpTKxVg=='),
        'ENCRYPTION_KEY$&',
        'ssshhhhhhhhhhh!!'
    )
as char);


select to_base64(aes_encrypt(
'test_value',
'ENCRYPTION_KEY$&',
'ssshhhhhhhhhhh!!'
));

There is a JAR that supports this EVP_BytesToKey key derivation function.

JAR : not-going-to-be-commons-ssl-0.3.19
byte[] key = "ENCRYPTION_KEY$&".getBytes(StandardCharsets.UTF_8);
byte[] iv = "ssshhhhhhhhhhh!!".getBytes(StandardCharsets.UTF_8);

String cipher = "AES-128-CBC";

@Test
public void testEncrypt() throws Exception {
    byte[] data = "test_message".getBytes(StandardCharsets.UTF_8);
    byte[] encrypted = OpenSSL.encrypt(cipher, key, iv, data, true);
    System.out.println(new String(encrypted));
}

@Test
public void testDecrypt() throws GeneralSecurityException, IOException {
    byte[] encrypted = "rQ8Y0ClNu5d4ODZQ3XcQtw==".getBytes(StandardCharsets.UTF_8);
    byte[] decrypted = OpenSSL.decrypt(cipher, key, iv, encrypted);
    System.out.println(new String(decrypted));
}

}

This finally achieves interoperability! Hope this helps someone trying to do the same thing.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template