0

我正在传递 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

密钥:bc03f2e674a0d482d0c6677d211eb14e

4

1 回答 1

0

我这样重写了您的代码,并且无法重现您的结果。我的输入是 20 个字节,作为字母表的 20 个字符,输出是 32 个字节,正如预期的那样。我把日志放在加密大小和输出之前验证输入。

尝试像我一样输入日志并在此处验证输入/输出。

    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);
     }
于 2014-11-09T04:42:31.327 回答