ASP.NET Rijndael加密错误 - 指定密钥不是此算法的有效大小

时间:2009-12-02 21:17:54

标签: asp.net encryption cryptography rijndaelmanaged

我似乎无法解决这个问题,我使用GRC处的随机生成器创建了我认为是256位密钥,并将其与我的IV相结合。我一直收到以下错误:

指定密钥不是此算法的有效大小。

感谢任何帮助,这是我用于加密/解密的代码:

Private Function Rijndael(ByVal sInput As String, ByVal bEncrypt As Boolean) As String
    ' Setup the Key and Initialization Vector.
    Dim byteKey As Byte() = Encoding.UTF8.GetBytes("C3CA193570B26E5C3CBB50FD805A0E23BAFFABA135E82C41517EEDCB9B7C90AC")
    Dim byteIV As Byte() = Encoding.UTF8.GetBytes("c+O2r)J~?L:$]u[2")
    ' Create an instance of the encyrption algorithm. 
    Dim _rijndael As New RijndaelManaged()
    ' Create an encryptor using our key and IV 
    Dim transform As ICryptoTransform
    If bEncrypt Then
        transform = _rijndael.CreateEncryptor(byteKey, byteIV)
    Else
        transform = _rijndael.CreateDecryptor(byteKey, byteIV)
    End If
    ' Create the streams for input and output 
    Dim msOutput As New System.IO.MemoryStream()
    Dim msInput As New CryptoStream(msOutput, transform, CryptoStreamMode.Write)
    ' Feed data into the crypto stream. 
    msInput.Write(Encoding.UTF8.GetBytes(sInput), 0, Encoding.UTF8.GetBytes(sInput).Length)
    ' Flush crypto stream. 
    msInput.FlushFinalBlock()
    Return Convert.ToBase64String(msOutput.ToArray)
End Function

1 个答案:

答案 0 :(得分:4)

C3CA193570B26E5C3CBB50FD805A0E23BAFFABA135E82C41517EEDCB9B7C90AC是256位长比特流的十六进制代码。

但是Encoding.UTF8.GetBytes不会像你想的那样将十六进制代码转换成相应的字节。

因为该字符串中有64个字符,所以可以获得64字节的UTF-8字节。这是一个512位长的比特流。