【发布时间】:2017-08-28 15:28:37
【问题描述】:
我有一个 PBE 生成的密钥,我使用算法“PBEWithHmacSHA256AndAES_128”加密了一个字符串,但是我无法解密所述字符串。
密钥生成:
private final static byte[] SALT = { (byte) 0xc9, (byte) 0x36, (byte) 0x78, (byte) 0x99, (byte) 0x52, (byte) 0x3e, (byte) 0xea,
(byte) 0xf2 };
PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray(), SALT, 20 , 128);
try {
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
PRIVATE_KEY = kf.generateSecret(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
加密字符串:
private static String cipherString(String string) {
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(SALT, 100);
Cipher cipher;
try {
cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
cipher.init(Cipher.ENCRYPT_MODE, PRIVATE_KEY, pbeParameterSpec);
byte[] input = string.getBytes();
byte[] encryptedp = cipher.doFinal(input);
return encryptedp.toString();
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
解密字符串:
private static String decipherString(String string) {
Cipher c;
try {
c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
c.init(Cipher.DECRYPT_MODE, PRIVATE_KEY);
byte[] input = string.getBytes();
byte[] encryptedp = c.doFinal(input);
return encryptedp.toString();
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
【问题讨论】:
-
然后会发生什么?如果有错误,包括它。如果结果不是您所期望的,请描述您得到的结果及其有何不同。
-
encryptedp.toString()不返回加密字符串。在处理加密字节时,你应该只操作字节数组 -
另外,请参阅Java: Syntax and meaning behind “[B@1ef9157”? Binary/Address? 您需要使用 Base64 或类似的方法来传输您的密文。
标签: java encryption cryptography passwords aes