加密时为什么会有额外的块?

时间:2014-11-09 03:55:18

标签: java encryption cryptography aes cbc-mode

我传输的输入数据长度为20个字节,java AES-CBC返回48个字节而不是32个字节,这是我认为它应该因为填充而输出。我的密钥是16个字节长。

byte[] ciphertext;
byte[] thekey = new byte[16];
new Random().nextBytes(thekey);
byte[] vector = new byte[16];
new Random().nextBytes(vector);
String s = "c6be25d903159d680d81f3d99bb702451e9f7158";
byte[] data = s.getBytes();
Cipher enc = Cipher.getInstance("AES/CBC/PKCS5Padding");           
enc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(thekey, "AES"), 
        new IvParameterSpec(vector));
ciphertext = enc.doFinal(data);


/* Sample Output*/
StringBuffer testvec = new StringBuffer();
StringBuffer test = new StringBuffer();
StringBuffer testkey = new StringBuffer();
for (byte b:vector){
testvec.append(String.format("%02x", b));
                                }
System.out.println("Vector:"  + " " +testvec.toString());
for (byte b:ciphertext){
test.append(String.format("%02x", b));
                                }

System.out.println(" Cipher:"+ " " + test.toString());


for (byte b:thekey){
testkey.append(String.format("%02x", b));
                                }

System.out.println("theKey:"+ " " + testkey.toString());

示例输出:

载体:c6ab4c2b0b220b8b3520bd20e3741a1e

密码: 3dd2cb1f94c99940fd4f7d1a503a091844dc16c8bae480d748453859701b72fecd949e158d2103ba99560d64ee65f6cb

theKey:bc03f2e674a0d482d0c6677d211eb14e

1 个答案:

答案 0 :(得分:0)

我重写了你的代码,我无法重现你的结果。我的输入为20个字节,为字母表的20个字符,输出为32个字节。我把Logs验证加密大小和输出之前的输入。

尝试按照我的方式放入日志,并在此处验证输入/输出。

    try {

         byte[] inputBytes = "abcdefghijklmnopqrst".getBytes("UTF-8");

         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");   
         SecretKey sk = getCastedActivity().getSecretKey();

         SecretKeySpec skeySpec = new SecretKeySpec(sk.getEncoded(), "AES");

         //Confirmed 20 bytes input 
         Log.i(TAG, "InputBytes length " + inputBytes.length);

         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(MyEncrypt.generateIv()));
         byte[] encryptedBytes = encryptedBytes = cipher.doFinal(inputBytes);

         //As expected 32 byte encrypted size.
         Log.i(TAG, "OutputBytes length " + encryptedBytes.length);

     } catch (Exception e) {
         Log.e(TAG, "encryption exception", e);
     }