對於128位
下面的方法是加密的字符串(valueEnc
)與AES加密的答案:
private static final String ALGORITHM = "AES";
public String encrypt(final String valueEnc, final String secKey) {
String encryptedVal = null;
try {
final Key key = generateKeyFromString(secKey);
final Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
final byte[] encValue = c.doFinal(valueEnc.getBytes());
encryptedVal = new BASE64Encoder().encode(encValue);
} catch(Exception ex) {
System.out.println("The Exception is=" + ex);
}
return encryptedVal;
}
下一個方法將解密的AES加密字符串(encryptedVal
) :
public String decrypt(final String encryptedValue, final String secretKey) {
String decryptedValue = null;
try {
final Key key = generateKeyFromString(secretKey);
final Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
final byte[] decorVal = new BASE64Decoder().decodeBuffer(encryptedValue);
final byte[] decValue = c.doFinal(decorVal);
decryptedValue = new String(decValue);
} catch(Exception ex) {
System.out.println("The Exception is=" + ex);
}
return decryptedValue;
}
The secKey
是一個128位密鑰,編碼在BASE64Encoder
中。在以下方法BASE64Decoder
生成一個合適的128位密鑰
private Key generateKeyFromString(final String secKey) throws Exception {
final byte[] keyVal = new BASE64Decoder().decodeBuffer(secKey);
final Key key = new SecretKeySpec(keyVal, ALGORITHM);
return key;
}
我真的不知道,但我認爲使用一個256字節的密鑰將完成這項工作。 –
實際上只有16個字節(128位)的密鑰在我的代碼中工作。 – Bhuban
更大的按鍵是什麼「不工作」?你有例外嗎?哪一個?它的消息和堆棧跟蹤是什麼? –