Java AES 256 CBC模式无法正常工作

时间:2012-12-07 16:33:20

标签: java aes cbc-mode

以下是在ECB和CBC中执行AES的红宝石代码:


require 'openssl'
require 'base64'
def encrypt(data, key, cipher_type)
  aes = OpenSSL::Cipher::Cipher.new(cipher_type)
  key = key.ljust(32, "\0")
  aes.encrypt
  aes.key = key
  Base64.encode64(aes.update(data) + aes.final).tr("\n","")
end


puts encrypt("XJ5QJSVMKZGBOQO7HMSIJO5BERW2OYWDVNPM3BH32NLSWUCNJ4FIP3BML7EKUBNO", "000000", 'AES-256-ECB')
puts encrypt("XJ5QJSVMKZGBOQO7HMSIJO5BERW2OYWDVNPM3BH32NLSWUCNJ4FIP3BML7EKUBNO", "000000", 'AES-256-CBC')

这是Java Equivalent:


import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESTest 
{ 
    public static void main(String [] args)
    {
        System.out.println(AESEncryptToBase64("AES/ECB/PKCS5padding", "000000", "XJ5QJSVMKZGBOQO7HMSIJO5BERW2OYWDVNPM3BH32NLSWUCNJ4FIP3BML7EKUBNO"));
        System.out.println(AESEncryptToBase64("AES/CBC/PKCS5padding", "000000", "XJ5QJSVMKZGBOQO7HMSIJO5BERW2OYWDVNPM3BH32NLSWUCNJ4FIP3BML7EKUBNO"));
    }

    /**
     * 
     * @param secret
     * @param cleartext
     * @return encrypted b64 string
     */
    public static String AESEncryptToBase64(String cypher, String secret, String clearText) {
        byte[] rawKey = new byte[32];
        java.util.Arrays.fill(rawKey, (byte) 0);
        byte[] secretBytes = secret.getBytes();
        for(int i = 0; i < secretBytes.length; i++){
            rawKey[i] = secretBytes[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
        try{ 
            Cipher cipher = Cipher.getInstance(cypher);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encryptedData = cipher.doFinal(clearText.getBytes());
            if(encryptedData == null) return null;
            // return "l";
            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;      

    }
}

COMPILE :commons jar:http://apache.mirrors.pair.com//commons/codec/binaries/commons-codec-1.7-bin.zip


 $ javac -cp .:commons-codec-1.7.jar AESTest.java 

生成


$ ruby aestest.rb 
hYnClaUD9brJfNpEp4YDH0l1Y/QBlGkclnVN8MObNZFsvykd2da8iT2pcwLftNfox1HK/KFWrdfXt0qhP0Aq/fudP1FPIhF3vUTOEDzJbiY=
hYnClaUD9brJfNpEp4YDH5xcdKI4W5soPmWMpU+NikmAEKGSZkDP3KaJVSqRyOHt3JlcoyQzPbuoHxPV6kw6GH/4atDrcmCwV5LacTp+mBg=

$ java -cp .:commons-codec-1.7.jar AESTest
hYnClaUD9brJfNpEp4YDH0l1Y/QBlGkclnVN8MObNZFsvykd2da8iT2pcwLftNfox1HK/KFWrdfXt0qhP0Aq/fudP1FPIhF3vUTOEDzJbiY=
kZZNkbxis/W9UtEgRkxakGH28QetvK4lbf/SxBLrNDYPkGnf3w4MwonOCsoi9FjLAQ34aElOJ3KUjm62fiYLWxwNiE/wls7AcQnXLD19ano=

请注意,ECB模式完全适用于两者。但CBC模式不同。我也在C上运行它,结果证明Ruby是正确的,Java不是。

我在Java中做错了什么?

1 个答案:

答案 0 :(得分:3)

对于CBC,您需要提供初始化向量,例如:

cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));

在您的代码中有一个if语句和两个不同的inits。对于欧洲央行来说,这个很好,而且这个不适用于欧洲央行。