Anthony Matovu
asked on
encryption
I am try to encrypt a text for the first time
I have the code below but when i try to run it with input string
"MessageBox.Show(Encrypt(" string is that you need to encrypt", "abc123¿"))"
i get the message
"Specified key is not a valid size for this algorithm." when it reach line 8
1.Public Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
2. Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
3. Try
4. Dim bykey() As Byte = System.Text.Encoding.UTF8. GetBytes(L eft(strEnc rKey, 8))
5. Dim InputByteArray() As Byte = System.Text.Encoding.UTF8. GetBytes(s trText)
6. Dim des As New DESCryptoServiceProvider
7. Dim ms As New MemoryStream
8. Dim cs As New CryptoStream(ms, des.CreateEncryptor(bykey, IV), CryptoStreamMode.Write)
cs.Write(InputByteArray, 0, InputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms. ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
.
I have the code below but when i try to run it with input string
"MessageBox.Show(Encrypt("
i get the message
"Specified key is not a valid size for this algorithm." when it reach line 8
1.Public Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
2. Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
3. Try
4. Dim bykey() As Byte = System.Text.Encoding.UTF8.
5. Dim InputByteArray() As Byte = System.Text.Encoding.UTF8.
6. Dim des As New DESCryptoServiceProvider
7. Dim ms As New MemoryStream
8. Dim cs As New CryptoStream(ms, des.CreateEncryptor(bykey,
cs.Write(InputByteArray, 0, InputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.
Catch ex As Exception
Return ex.Message
End Try
End Function
.
I *think* your problem is that you are using UTF8.GetBytes and a character in unicode is actually 2 bytes. When your call returns, you have a byte array of length 16, not 8. You can easily check this by putting a breakpoint at line 5 and inspecting the value of bykey. Is there a reason not use use ASCII.GetBytes?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.