0

I have Stored the key in the database and fetching the key for encryption, I get exception

Exception

java.security.InvalidKeyException: Unsupported key  Note: Key is not in encrypted format.
Fetched Key from DB de.flexiprovider.core.rijndael.RijndaelKey@c4ef71c9
invalid Key  javax.crypto.spec.SecretKeySpec@97d5a10e  // we can see here key is changed

Program

StringBuffer sbselect1=new StringBuffer();
sbselect1.append("SELECT Keyforkey FROM ");
sbselect1.append(UserConstants.USER_DETAILS_TABLE_NAME2);
sbselect1.append(" where ID=2");
ps1=conn.prepareStatement(sbselect1.toString());
ResultSet rs =ps1.executeQuery();
 rs.next();
String keyskey = rs.getString("KeyforKey");
System.out.println("Fetched Key from DB "+keyskey);
Security.addProvider(new FlexiCoreProvider());
Cipher cipher2 = Cipher.getInstance("AES128_CBC", "FlexiCore");
//  byte[] encodedKey =keyskey.getBytes();
SecretKey key2 = new SecretKeySpec(keyskey.getBytes(), 0,  keyskey.length(), "AES");
System.out.println("invalid Key  "+ key2);
rs.close(); 

I have gone wrong at this piece of code

SecretKey key2 = new SecretKeySpec(keyskey.getBytes(), 0,  keyskey.length(), "AES");

And also at byte[] encodedKey =keyskey.getBytes();output is [B@117e4ff

Please help me to troubleshoot the problem.

swaroop k
  • 89
  • 1
  • 1
  • 13

1 Answers1

1

We usually store keys in HEX or Base64 String format if we need them to be human readable. Assuming you store your keys in HEX format to your database, you shouldn't get get the bytes of your String with keyskey.getBytes(), but get them using the following algorithm (taken from here which works pretty fast compared to other solutions for HEX to bytes):

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

do something analogous to the above if you use Base64 format see here.

Community
  • 1
  • 1
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24
  • With security - especially with keys - you don't need fast, you need precise. I've got a solution that beats that one 10-100 times over, but I don't use it :) That said, it looks like it works and bugs out on errors, so +1. – Maarten Bodewes Jan 04 '15 at 15:03