2014-09-12 129 views
-1

我有一个使用AES加密数据的Java代码。这里是一段简单的字符串编码在Java vs .NET中进行AES加密

String key="MySecretKeyABCDE"; 
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); 
byte[] ivbytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 
IvParameterSpec iv = new IvParameterSpec(ivbytes);//need IV in CBC mode 

Cipher m_enc_cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
m_enc_cipher.init(Cipher.ENCRYPT_MODE, skey, iv); 

String content ="Hello"; 
byte[] contentBArr = content.getBytes(); 
byte[] block = new byte[4080]; 
System.arraycopy(contentBArr,0,block,0,contentBArr.length); 
byte[] res = m_enc_cipher.doFinal(block,0,block.length); 

我需要创建一个等效的.NET代码。我写了这个

var csp = new RijndaelManaged 
{ 
    Mode = CipherMode.CBC, 
    Padding = PaddingMode.PKCS7,     
    Key = Encoding.UTF8.GetBytes("MySecretKeyABCDE"), 
    IV = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15} 
}; 

var e = csp.CreateEncryptor(); 
var content = Encoding.UTF8.GetBytes("Hello"); 
var block = new byte[4080]; 
Array.Copy(content,block,content.Length); 
var res = e.TransformFinalBlock(block,0,block.Length); 

当我比较res变量时,它们在Java版本和.NET版本中是不同的。我知道Java使用无符号字节,但结果是非常不同的,不仅“移位”。

回答

1

是否有任何理由使用不同的IVs?

您使用IV

new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 

在Java中,而使用C#中的IV

new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15} 

在Java中使用十进制数,并在C#十六进制数,其转化为

new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21} 

十进制。

如果您使用不同的IV,您将得到不同的密文。