0

以下代码使用 AES-128 将字节数组 SOURCE_DATA 加密为另一个字节数组 ENCRYPTED_DATA,然后再次将其解密为 DECRYPTED_DATA。对于 <= 256 字节的字节数组大小,代码可以正常工作,但如果字节数组较长,则 DECRYPTED_DATA 在字节 256 之后仅包含零,并且不等于 SOURCE_DATA 数组。我错过了什么?

输出:

源数据:...fbfcfdfeff0001
解密数据:...fbfcfdfeff000 0

代码:

// Create data array with size greater 256 bytes
byte[] SOURCE_DATA = new byte[257];     
for (int i=0;i<SOURCE_DATA.length; i++) {
    SOURCE_DATA[i] = (byte)((i+1) & 0xff);
}

// Init ciphers
Cipher encC = Cipher.getInstance("AES/ECB/PKCS5Padding");
Cipher decC = Cipher.getInstance("AES/ECB/PKCS5Padding");
encC.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[] {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6}, "AES"));                  
decC.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new byte[] {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6}, "AES"));          

// Encrypt
ByteArrayOutputStream bos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(bos, encC);
DataOutputStream dos = new DataOutputStream(cos);

dos.write(SOURCE_DATA, 0, SOURCE_DATA.length);
dos.close();

byte[] ENCRYPTED_DATA = bos.toByteArray();

// Decrypt
ByteArrayInputStream bis = new ByteArrayInputStream(ENCRYPTED_DATA);
CipherInputStream cis = new CipherInputStream(bis, decC);
DataInputStream dis = new DataInputStream(cis);

byte[] DECRYPTED_DATA = new byte[SOURCE_DATA.length];
dis.read(DECRYPTED_DATA, 0, DECRYPTED_DATA.length);
cis.close();

System.out.println("Source Data:    "+toHex(SOURCE_DATA));
System.out.println("Decrypted Data: "+toHex(DECRYPTED_DATA));            
4

1 回答 1

1

尝试使用DataInputStream.readFully(即您只读取部分结果,这就是为什么您总是InputStream.read在 while 循环中调用)。

于 2012-07-03T20:48:33.627 回答