简体   繁体   中英

Trying to store encrypted AES data into mySQL database using Java

I'm trying to store a byte array into mySQL which contains encrypted 'password'. I've tried both using both Blob and varbinary datatype, but when I extract the encrypted data, it doesn't seem to decrypted correctly as the stored byte array is not the same as the one I started with.

The code below for the encrypt/decryption

   public byte[] encrypt(String password){
    byte[] encrypted = null;
    try {
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        encrypted = cipher.doFinal(password.getBytes());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return encrypted;
}

public String decrypt(byte[] encrypted){
    String decrypted = null;
    try {
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        decrypted = new String(cipher.doFinal(encrypted));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return decrypted;
}

I've printed out the byte array to see if there was the difference, as you can see during the transition into the database it does change and I'm not sure how to overcome this problem

Output of byte array (Top is original byte array, bottom is from the database)

84-48-4282-15-60-21-38-41944477106182
916664495599545657505332

Just to clarify, if I try to decrypt using database byte array I recieve this error:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decryption with padded cipher

Also as mentioned in the comments section, I've tried converted it into a string and and storing it in DB then decrypt it but I get the same error.

I've even tried using Hashing with SHA-256 and it's the same thing the byte array that I'm retrieving is completely different to what it was originally

variables I'm using

byte[] pa = p.hashPass("Hello World");
byte[] dbp = null;

This is the statement I'm using to store/get the data

Statement stmt = conn.createStatement();
stmt.execute("INSERT INTO staffaccounts(`ID`, `UserName`, `Password`, `Salt`) VALUES (NULL, 'admin', '"+pa+"', '')");
ResultSet rs = stmt.executeQuery("SELECT * FROM staffaccounts");
rs.next();
dbp = rs.getBytes("password");

The problem here is that you are inserting the value returned by byte[].toString() , which is not the content of the byte array.

You should be doing this via positional parameters in a PreparedStatement. Never concatenate values into an SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM