java.security.InvalidKeyException:不支持的密钥。从数据库中获取KEY时

时间:2015-01-03 06:37:02

标签: java encryption

我已经存储了数据库中的密钥并获取了加密密钥, 我得到例外

异常

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

程序

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(); 

我在这段代码中出错了

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

并且在byte [] encodedKey = keyskey.getBytes();输出为[B @ 117e4ff

请帮我解决问题。

1 个答案:

答案 0 :(得分:1)

我们通常以HEX或Base64 String格式存储密钥,如果我们需要它们是人类可读的。假设您将HEX格式的密钥存储到数据库中,您不应该使用keyskey.getBytes()获取String的字节数,而是使用以下算法获取它们(取自here,其工作速度相当快到HEX到字节的其他解决方案):

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;
}

如果使用Base64格式,请执行与上述类似的操作,请参阅here