java Cipher.doFinal() 使用相同的输入、键和 iv 时返回不同的结果

java Cipher.doFinal() returning different results when using same input, key and iv

如果我使用相同的输入字符串、相同的密钥和相同的 iv,我希望得到相同的加密结果。然而,每次我 运行 我的加密程序都会产生不同的结果。加密代码是否使用了其他随机数?

我的加密密码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import javax.xml.bind.DatatypeConverter;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.BadPaddingException;

public class Encrypt
{
    private static byte[] _key = new byte[] {
            (byte) 0x02, (byte) 0xb2, (byte) 0xc4, (byte) 0x9e,
            (byte) 0xf9, (byte) 0x44, (byte) 0x99, (byte) 0xc9,
            (byte) 0x80, (byte) 0x65, (byte) 0xcd, (byte) 0x8f,
            (byte) 0x69, (byte) 0x2b, (byte) 0x74, (byte) 0x34};

    private static byte[] _iv = new byte[] {
            (byte) 0x69, (byte) 0x2b, (byte) 0x74, (byte) 0x34,
            (byte) 0x02, (byte) 0xb2, (byte) 0xc4, (byte) 0x9e,
            (byte) 0xf9, (byte) 0x44, (byte) 0x99, (byte) 0xc9,
            (byte) 0x80, (byte) 0x65, (byte) 0xcd, (byte) 0x8f};

    public static void main(String[] args)
            throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException,
            NoSuchPaddingException, InvalidAlgorithmParameterException,
            BadPaddingException
    {
        if (args.length != 1)
            System.out.println("Error, expecting a single string to encrypt as a command line argument.");
        else
            {
            Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(_key, "AES"),
                    new IvParameterSpec(_iv));
            byte[] encrypted = cipher.doFinal(args[0].getBytes(StandardCharsets.US_ASCII));
            String result = DatatypeConverter.printBase64Binary(encrypted);
            System.out.println("result: " + result);
            }
    }
}

谢谢, 尼克

是的,您的填充算法 ISO 10126 中有随机字节。消息的最后一个块用随机字节填充到(块大小 -1),最后添加的字节保存随机序列的长度。

这是避免某些攻击的重要机制,详情请参阅https://en.m.wikipedia.org/wiki/Padding_(cryptography)

注意:ISO 10126 已于 2007 年撤销,不应再使用。考虑任何其他填充算法。