【发布时间】:2014-05-27 09:04:59
【问题描述】:
我使用以下简单的加密和解密函数只是为了在使用更复杂的安全功能(如填充和散列)之前查看它是否有效。由于某种原因,返回的明文与原始消息不相似。代码如下:
public static byte[] encrypt(SecretKey secret, byte[] buffer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Encrypt the message. */
cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] ciphertext = cipher.doFinal(buffer);
return ciphertext;
}
public static byte[] decrypt(SecretKey secret, byte[] buffer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Decrypt the message. - use cipher instance created at encrypt */
cipher.init(Cipher.DECRYPT_MODE, secret);
byte[] clear = cipher.doFinal(buffer);
return clear;
}
和调用代码:
SecretKey secret1 = null;
byte[] ciphertext = null;
byte[] message = "Hello, World!".getBytes();
byte[] clear = null;
try {
// aSecret is a shared secret generated with ECDH
secret1 = Crypto.createAESKey(aSecret);
ciphertext = Crypto.encrypt(secret1, message);
clear = Crypto.decrypt(secret1, ciphertext);
String s = new String(clear);//clear.toString();
keyAText.setText(new String(message));
keyBText.setText(s);
return;
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
【问题讨论】:
-
在字节数组上调用
toString并没有按照您的想法进行。看看String构造函数。 -
Henry - 即使字符串没有正确构建,我也希望两个字节数组生成相同的“字符串”。
-
@Simon 不,因为它不是同一个实例。默认的
toString方法将对象的哈希码显示为字符串的一部分。 -
您确定要使用 AES 计数器模式吗?如果是,则必须使用相同的IV值进行加密和解密。
标签: android security encryption aes