AES字符串加密“无效的IV块大小”

时间:2019-02-25 18:33:12

标签: encryption aes

我正在尝试使用以下代码对字符串进行加密。问题是我收到此错误,但不知道(我只是在学习加密)要做什么,甚至不知道在哪里看。 SharedKey和IV已作为十六进制值提供。 SharedKey为64字节,IV为32字节。

System.Security.Cryptography.CryptographicException:'指定的初始化向量(IV)与该算法的块大小不匹配。'

@OneToMany(fetch=FetchType.EAGER, mappedBy="parent", orphanRemoval = true, cascade = { CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH, CascadeType.REMOVE})
 private Collection<Sub_Engagement> subs_engs;

2 个答案:

答案 0 :(得分:0)

对于CBC模式(和大多数其他模式),IV长度必须与块长度相同。默认情况下,.NET CLR RijndaelManaged密码的块长度为128位(16字节)。您可以使用

进行设置

aes.BlockSize = 256

允许使用32字节的IV,但也使用32字节的块。

此外,您的评论还建议您使用的是64字节(512位)密钥。那应该是一个32字节(256位)的密钥。

答案 1 :(得分:0)

这些是我用的。返回的值是否正确,我还不知道。

Public Function Encrypt(ByVal strValue As String) As String
        'Create instance of a Rijndael Managed object
        Dim aes As New RijndaelManaged
        'Set appropriate values of object
        aes.Padding = PaddingMode.PKCS7
        aes.KeySize = 256
        aes.Mode = CipherMode.CBC
        'Create streams to work with encryption process
        Dim msEncrypt As New MemoryStream()
        Dim SharedKey As Byte()
        'SharedKey = ""
        'IV = ""
        SharedKey = StringToByteArray(strSharedKey)
        Dim IV As Byte()
        IV = StringToByteArray(strIV)

        Dim csEncrypt As New CryptoStream(msEncrypt, aes.CreateEncryptor(SharedKey, IV), CryptoStreamMode.Write)
        'Convert string value to byte array
        Dim toEncrypt As Byte() = Encoding.GetEncoding(1252).GetBytes(strValue)
        toEncrypt = Encoding.Convert(Encoding.GetEncoding(1252), Encoding.UTF8, toEncrypt)
        'Perform encryption
        csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
        csEncrypt.FlushFinalBlock()
        'Return Base64 string
        Return Convert.ToBase64String(msEncrypt.ToArray())
End Function

Function StringToByteArray(text As String) As Byte()
        Dim bytes As Byte() = New Byte(text.Length \ 2 - 1) {}
        For i As Integer = 0 To text.Length - 1 Step 2
            bytes(i \ 2) = Byte.Parse(text(i).ToString() & text(i + 1).ToString(), System.Globalization.NumberStyles.HexNumber)
        Next
        Return bytes
End Function

其他任何想法都会很有帮助

相关问题