简体   繁体   English

java AES / CFB / NoPadding:加密相似数据时,结果也相似

[英]java AES/CFB/NoPadding :when encrypting similar data the results are similar too

package com.game;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
public class MainTest5 {
    public static byte[] encrypt(String content, String key) {
        try {
            Cipher aesECB = Cipher.getInstance("AES/CFB/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
            aesECB.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] result = aesECB.doFinal(content.getBytes());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(new String(encrypt("1234567890123456", "1234567890123456"), "ISO_8859_1"));
        System.out.println(new String(encrypt("1234567890123457", "1234567890123456"), "ISO_8859_1"));
    }
}

I just want to encrypt some similar data and hope that the result is not similar, but the length must be the same. 我只想加密一些相似的数据,并希望结果不相似,但是长度必须相同。 What can I do? 我能做什么?

Your IV should not just re-use the key bytes. 您的IV不应仅重用密钥字节。 The whole point of the IV is to act as a 'seed' to ensure the ciphertext does not remain constant. IV的全部目的是充当“种子”,以确保密文不保持恒定。

See wikipedia for more information. 有关更多信息,请参见Wikipedia

If you want semantic security (that is what you're talking about here when you say you want vastly different ciphertexts for similar/same plaintexts), you need to use a random IV. 如果您需要语义安全性(当您说要为相似/相同的明文要求截然不同的密文时,这就是您在这里所说的),则需要使用随机IV。 The IV is not supposed to be secret, it only needs to be random to achieve this property. IV不应被认为是秘密的,它只需要是随机的即可达到该特性。

SecureRandom r = new SecureRandom();
byte[] ivBytes = new byte[16];
r.nextBytes(ivBytes);

For the decryption to work, you need to provide the same IV again. 为了使解密正常工作,您需要再次提供相同的IV。 Since it's not supposed to be secret you can send it along with the ciphertext. 由于它不是秘密的,您可以将其与密文一起发送。 A common way is to prepend it to the ciphertext, since the IV is always 16 bytes long for AES. 一种常见的方式是将其放在密文之前,因为IV对于AES而言总是16字节长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM