R – ASP.NET Rijndael Encryption Error – Specified key is not a valid size for this algorithm

asp.netcryptographyencryptionrijndaelmanaged

I can't seem to get past this problem, I've created what I assume to be a 256-bit key using the random generator at GRC and combined that with my IV. I keep getting the error below:

Specified key is not a valid size for this algorithm.

Any help is gratefully received, here is the code I am using to Encrypt/Decrypt:

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

Best Answer

C3CA193570B26E5C3CBB50FD805A0E23BAFFABA135E82C41517EEDCB9B7C90AC is hex code for a 256-bit-long bitstream.

But Encoding.UTF8.GetBytes does not turn hex code into the corresponding bytes in the way you were thinking.

Because you had 64 characters in that string, you get 64 bytes of UTF-8 bytes. That's a 512-bit-long bitstream.

Related Topic