java - 使用 DES 加密数据 - JAVA

标签 java encryption des

给出以下示例:

String f="A000000000000000";
FileInputStream fis = new FileInputStream("C:\\Users\\original.txt");
byte[] bytes = DatatypeConverter.parseHexBinary(f);
SecretKey key = new SecretKeySpec(bytes, 0, bytes.length, "DES");

String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();

    try{

    Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE,key);

            //read from file and transform to String
            try{
            builder = new StringBuilder();
            int ch;
            while((ch = fis.read()) != -1){
            builder.append((char)ch);
            }
            }catch (IOException e){

            }

    byte[] byteDataToEncrypt = builder.toString().getBytes();
    byte[] byteCipherText = desCipher.doFinal(byteDataToEncrypt); 
    strCipherText = new BASE64Encoder().encode(byteCipherText);

    System.out.println(strCipherText);

每次使用相同的 key 值 i 编译时,加密的数据都是不同的,我尝试了不同的代码,但加密的数据始终相同,这里出了什么问题?

最佳答案

documentation for javax.crypto.Cipher.init部分说:

If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values)

DES CBC(密码 block 链接)模式需要初始化 vector (IV)。如果您不提供(您不应该提供,因为它会打开 dictionary attacks ),则会生成一个随机的。

但是如果您希望每次加密的数据都相同,则需要使用 IvParameterSpec 指定 IV:

byte[] iv = DatatypeConverter.parseHexBinary("0000000000000000");
IvParameterSpec ips = new IvParameterSpec(iv);
desCipher.init(Cipher.ENCRYPT_MODE, key, ips);

如果您确实让它生成随机 IV,您可以使用 desCipher.getIV() 检索生成的 IV。

关于java - 使用 DES 加密数据 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185728/

相关文章:

java - 使用套接字传输加密文件并使用 DES 和 MD5 解密文件

java - JOptionPane 输入到 int

java - 在recyclerview中,如何让每个事件开启新的 Activity ?

php - Symfony2源代码加密/编码

MySQL 加密

java - 使用 AES 加密和解密图像的正确方法

java - 如何修复错误 "Only the original thread that created a view hierarchy can touch its views."

java - 从 Windows 为 Java 创建 native OSX 可执行文件

java - 在Java中生成并使用两个 key 进行加密和解密

python - Pyocrypt DES3文件加密,解密缺失部分文本