无法在VB .net中正确设置AES解密

时间:2013-05-16 14:00:10

标签: vb.net cryptography aes

我正在尝试跨两个不同的平台设置AES加密/解密。当我加密或解密时,我一直无法让VB.net给我预期的输出,所以我做了一个小实验:

使用相同的System.Security.Cryptography.AesManaged对象进行加密和解密我得到了原始数据但是使用不同的对象进行加密和解密我得到了不同的答案。我的代码如下

    Dim AES As New System.Security.Cryptography.AesManaged
    Dim AES2 As New System.Security.Cryptography.AesManaged
    Dim key() As Byte = New Byte() {&HDE, &HAD, &HBE, &HEF, &HA5, &HF4, &H56, &H12, &HDE, &HAD, &HBA, &HAB, &H1, &H92, &H83, &H74}
    Dim nulliv() As Byte = New Byte() {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

    AES.Key = key
    AES.KeySize = 128
    AES.BlockSize = 128
    AES.Padding = Security.Cryptography.PaddingMode.None
    AES.Mode = Security.Cryptography.CipherMode.CBC
    AES.IV = nulliv

    AES2.Key = key
    AES2.KeySize = 128
    AES2.BlockSize = 128
    AES2.Padding = Security.Cryptography.PaddingMode.None
    AES2.Mode = Security.Cryptography.CipherMode.CBC
    AES2.IV = nulliv

    Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor()

    Dim input() As Byte = New Byte() {&H12, &H34, &H56, &H78, &H9A, &HBC, &HDE, &HF0, &H24, &H68, &HAC, &HE0, &H78, &H94, &H56, &H12}

    Dim enc() As Byte = DESEncrypter.TransformFinalBlock(input, 0, input.Length)

    Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
    Dim out() As Byte = DESDecrypter.TransformFinalBlock(enc, 0, enc.Length)

    Dim DESDecrypter2 As System.Security.Cryptography.ICryptoTransform = AES2.CreateDecryptor
    Dim out2() As Byte = DESDecrypter2.TransformFinalBlock(enc, 0, enc.Length)

我希望输入,输出和输出2匹配,但他们不匹配。输入和输出是相同的但是out2是不同的。我只能假设AES对象中存储了一些我没有正确设置或正确地在对象之间传输的东西。

我最初尝试使用ECB模式来简化问题但是想知道是否设置IV没有效果。所以,我尝试使用CBC,将IV作为零,这意味着它应该与ECB相同。在这两种情况下,我都会遇到out和out2不匹配的问题。

任何人都可以向我解释我错过了什么吗?感谢

1 个答案:

答案 0 :(得分:1)

不要将KeySize属性分配给128.执行此操作时,会导致AesManaged清空您之前提供的密钥。 AesManaged可以从您提供的实际密钥中获取密钥大小,因此请将其更改为:

Dim AES As New System.Security.Cryptography.AesManaged
Dim AES2 As New System.Security.Cryptography.AesManaged
Dim key() As Byte = New Byte() {&HDE, &HAD, &HBE, &HEF, &HA5, &HF4, &H56, &H12, &HDE, &HAD, &HBA, &HAB, &H1, &H92, &H83, &H74}
Dim nulliv() As Byte = New Byte() {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

AES.Key = key
AES.Padding = Security.Cryptography.PaddingMode.None
AES.Mode = Security.Cryptography.CipherMode.CBC
AES.IV = nulliv

AES2.Key = key
AES2.Padding = Security.Cryptography.PaddingMode.None
AES2.Mode = Security.Cryptography.CipherMode.CBC
AES2.IV = nulliv
'Rest of the code is the same.