【发布时间】:2015-06-16 22:46:42
【问题描述】:
我曾尝试在 Nexus 5 中运行以下 AES/ CBC/ PKCS5Padding 加密和解密代码,并使用 SHA-1 作为密钥生成。它运行良好到目前为止。
不过,我唯一关心的是,AES/CBC/PKCS5Padding 加密解密算法和 SHA-1 哈希算法是否适用于所有类型的 Android 设备?
以下代码是否有可能无法在某些 Android 设备上运行?如果有,有没有后备计划?
AES/CBC/PKCS5Padding
// http://stackoverflow.com/questions/3451670/java-aes-and-using-my-own-key
public static byte[] generateKey(String key) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] binary = key.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
binary = sha.digest(binary);
// Use only first 128 bit.
binary = Arrays.copyOf(binary, 16);
return binary;
}
// http://stackoverflow.com/questions/17322002/what-causes-the-error-java-security-invalidkeyexception-parameters-missing
public static String encrypt(byte[] key, String value) throws GeneralSecurityException {
// Argument validation.
if (key.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
// Setup AES tool.
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
// Do the job with AES tool.
byte[] original = value.getBytes(Charset.forName("UTF-8"));
byte[] binary = cipher.doFinal(original);
return Base64.encodeToString(binary, Base64.DEFAULT);
}
// // http://stackoverflow.com/questions/17322002/what-causes-the-error-java-security-invalidkeyexception-parameters-missing
public static String decrypt(byte[] key, String encrypted) throws GeneralSecurityException {
// Argument validation.
if (key.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
// Setup AES tool.
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
// Do the job with AES tool.
byte[] binary = Base64.decode(encrypted, Base64.DEFAULT);
byte[] original = cipher.doFinal(binary);
return new String(original, Charset.forName("UTF-8"));
}
用法
byte[] key = generateKey("my secret key");
String ciphertext = encrypt(key, "my plain content");
String plainContent = decrypt(key, ciphertext);
【问题讨论】:
-
在所有可用的模拟器图像中尝试一下,但我认为没有理由不应该在任何地方实施。如果您仍然不想自己尝试,则默认使用 BouncyCastle/SpongyCastle 提供程序。
-
@OlegEstekhin 它认为关于这个问题有点过头了。这意味着提问者仍然需要在所有模拟器上进行测试,这可能只是您在设计应用程序后才想做的事情。
标签: android encryption cryptography