我必须在Android设备上加密和解密文本。我找到了一些解决方案,但是当我再次加密文本时,结果却不同了。谁能告诉我为什么?
这是我的代码:
public class AESDemo {
private static final String password = "test";
private static String salt;
private static int pswdIterations = 65536;
private static int keySize = 256;
private byte[] ivBytes;
public String encrypt(String plainText) throws Exception {
//get salt
salt = generateSalt();
byte[] saltBytes = salt.getBytes("UTF-8");
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(
password.toCharArray(),
saltBytes,
//null,
pswdIterations,
keySize
);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//encrypt the message
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
//return new Base64().encodeAsString(encryptedTextBytes);
return Base64.encodeToString(encryptedTextBytes, Base64.DEFAULT);
}
@SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {
byte[] saltBytes = salt.getBytes("UTF-8");
//byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);
byte[] encryptedTextBytes= Base64.decode(encryptedText, Base64.DEFAULT);
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(
password.toCharArray(),
saltBytes,
pswdIterations,
keySize
);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
// Decrypt the message
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public String generateSalt() {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
String ss = "";
random.nextBytes(bytes);
String s = new String(bytes);
return "sare";
}
}
我已经将盐硬编码为相同,但结果每次都不同。谁能告诉我为什么?
答案 0 :(得分:0)
你的IV处理困扰我。你调用getIV()但你在哪里实际设置加密的IV?在我看来,你使用随机IV,这可能解释了为什么你每次都得到不同的加密数据。
我建议尝试创建一个动态的IvParameterSpec类,并用预设的IV填充它。