Android 如何在多次加密相同的明文时获得相同的密文
我不太了解加密/解密。使用下面的代码进行加密Android 如何在多次加密相同的明文时获得相同的密文,android,encryption,Android,Encryption,我不太了解加密/解密。使用下面的代码进行加密 class EncryptExample { private static int KEY_LENGTH = 256; private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private static String DELIMITER = "]"; public static String encrypt(String
class EncryptExample {
private static int KEY_LENGTH = 256;
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static String DELIMITER = "]";
public static String encrypt(String plaintext, SecretKey key, byte[] salt) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] iv = generateIv(cipher.getBlockSize());
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
if (salt != null) {
return String.format("%s%s%s%s%s", toBase64(salt), DELIMITER, toBase64(iv), DELIMITER, toBase64(cipherText));
}
return String.format("%s%s%s", toBase64(iv), DELIMITER, toBase64(cipherText));
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static byte[] generateIv(int length) {
byte[] b = new byte[length];
new SecureRandom().nextBytes(b);
return b;
}
public static String toBase64(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static byte[] fromBase64(String base64) {
return Base64.decode(base64, Base64.NO_WRAP);
}
}
它可以很好地用于加密,但当我得到加密值时,对于相同的文本总是不同的。您能告诉我,如果我能为同一明文获得相同的加密值,该怎么办?“您能告诉我,如果我能为同一明文获得相同的加密值,该怎么办?”这是一个安全属性。你应该留着它。你为什么不想要那份财产?即使IV和密文每次都不同,也不会降低你解密密文的能力。我完全同意@ArtjomB。但问题是,我们再次使用加密值作为保存功能状态(功能打开/关闭)的密钥。我们优先保存的那把钥匙。这个密钥实际上是用户名,所以我们可以根据用户跟踪功能的状态。您当然可以简单地使用静态IV,但我相信在您的情况下会有更合适的解决方案。你们有并没有想过在你们的数据库中添加一个额外的令牌,或者在加密之前对明文进行散列?我知道你们的第一个建议。让我试试。但很抱歉,我没听清楚你的第二种方法?你是说不用加密值作为密钥,我必须用一个可分离的散列值作为密钥?我仍然不确定你想做什么。也许你可以问一个问题来描述你的情况,最好的方法是什么。我几乎不认为使用密文作为查找键是可行的。