2014-11-09 77 views
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

theKey:bc03f2e674a0d482d0c6677d211eb14e

+0

什么是数据? – 2014-11-09 14:18:51

+1

关于Crypto.SE的相同问题:http://crypto.stackexchange.com/questions/20114/why-is-there-an-extra-block-when-encrypting – 2014-11-09 14:47:18

+1

如果您不能复制和粘贴可编译的内容代码,那么我们无法回答你的问题。 String类没有getbytes方法。 – 2014-11-09 15:44:10

回答

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); 
    } 
+0

我发布了我运行以获得结果的代码 – dfs 2014-11-10 19:15:22

+0

您的输入是40字节,而不是20.您的输出是48字节,而不是96字节。你正在通过格式化.02x运行的东西,它将字节转换成2位数的字符,因此你似乎是双重计数。这些数字与预期相符。 – NameSpace 2014-11-11 07:07:02

+0

”。getBytes()不是如何将十六进制转换回原始二进制。当您将字节转换为十六进制时,每个字节变为2个字符,并且当您调用getBytes()时,每个字符变为一个字节,因此您的原始字节数增加了一倍... http://stackoverflow.com/questions/9246326/convert-十六进制字符串十六进制二进制字符串 – NameSpace 2014-11-11 17:01:51

相关问题