0

I am implementing aes encryption in mysql and same thing I am doing using my java code. Below is my mysql script to encrypt the data. This AES_ENCRYPT function takes column_name as 1st parameter, encryption_key as 2nd and ivparam as 3rd parameter. It doesn't take any salt bytes.

SET session block_encryption_mode = 'aes-128-cbc';
SET @key_str = LEFT(UNHEX(SHA2('My secret passphrase',256)),16);
AES_ENCRYPT(COLUMN_NAME,@key_str,LEFT(UNHEX(SHA2(IV,256)),16)) 

When I try to do same thing via java code, PBEKeySpec constructor has mandatory saltbytes parameter, which results in different cipher text from mysql and java. I am trying to generate same cipher using mysql and java

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 2, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
        
Muddassir Rahman
  • 976
  • 1
  • 9
  • 20
  • 1
    **I want to** is not a question. Where are you stuck? What have you researched? What have you tried? To be clear, we'll help you at stackoverflow but we're not a free do-my-thinking service See [how to ask](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) – RiggsFolly Sep 05 '22 at 08:02
  • 1
    Can you pass an empty parameter to saltbytes? If not, then you need to find another java library that implements AES algorithm without salting. Even then you will have to work with character sets in mysql and java to be able to generate the same output. I would also mention that I don't think there is much point in using a symmetric encryption algorithm on database columns as you will struggle to keep the key secure and encrypted data in databases can slow down or even prevent searching of data. – Shadow Sep 05 '22 at 08:03
  • 2
    You are using PBKDF2 in the Java code for key derivation, which is why a salt is needed. In the mysql code key and IV are derived via SHA256. You have to do the same in the Java code with [`MessageDigest`](https://stackoverflow.com/a/5531479/9014097). Note, that for security reasons PBKDF2 is preferable as key derivation to a digest like SHA256. – Topaco Sep 05 '22 at 08:33
  • @Shadow empty salt throws exception – Muddassir Rahman Sep 05 '22 at 11:12
  • @Topaco `MessageDigest` link is talking about one way hash but I have to decrypt as well – Muddassir Rahman Sep 05 '22 at 11:12
  • You misunderstand me. I mean, you have to use SHA256 instead of PBKDF2/HMAC-SHA1, of course only for the key derivation. The encryption/decryption still uses AES. – Topaco Sep 05 '22 at 12:04

0 Answers0