如何在多次加密相同的明文时获得相同的密文

时间:2017-02-26 06:50:26

标签: 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 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);
    }
}

它的加密工作正常,但是当我获得加密值时,对于相同的文本它总是不同的。如果我能为同一个plaint文本获得相同的加密值,请告诉我怎么办?

0 个答案:

没有答案