Groups | Blog | Home
all groups > dotnet security > october 2004 >

dotnet security : RSA Conversion Issue



peter NO[at]SPAM mclinn.com
10/13/2004 7:24:19 AM
I've encrypted the contents of a textbox using RSA encryption with no
issues but when I try to decode the message in another application I'm
getting a 'bad data' error. Here is the the general proceedure I'm
using:
VB.net

'This is how I encoded:
Dim xmlPublicKey As String = "MyKeyPublic" 'Fake key for illustration
purposes
Dim rsa As New RSACryptoServiceProvider
rsa.FromXmlString(xmlPublicKey)
Dim message As String = txtSerial.Text
Dim plainTextinBytes As Byte()
plainTextinBytes = (New UnicodeEncoding).GetBytes(message)

'I removed error handling to illustrate point
plainTextinBytes = rsa.Encrypt(plainTextinBytes, False)

For i As Integer = 0 To plainTextinBytes.Length - 1
txtReg.Text += (Chr(plainTextinBytes(i))) 'Encrypted data
Me.Refresh()
Next
Dim MyStringToDecrypt as string = txtReg.Text

Now I take MyStringToDecrypt at this point and save it to a text file.
On another computer I try to decode this message using this code:

Dim rsa As New RSACryptoServiceProvider
Dim plainTextInBytes As Byte()
Dim xmlKeys As String
Dim DecryptedSerial As String

rsa.FromXmlString("MyPrivateKLeyData")
'RegText holds the data encrypted with the public key
Dim Z() As Byte
For i As Integer = 0 To txtReg.Text.Length - 1
ReDim Preserve Z(i)
Z(i) = CType(Asc(Mid(txtReg.Text, i + 1, 1)), Byte)
Next
plainTextInBytes = Z

Dim decrytion As Byte() = rsa.Decrypt(plainTextInBytes,
False)
For i As Integer = 0 To (decrytion.Length - 1) Step 2
Console.Write(Chr(decrytion(i)))
Next

Joe Kaplan (MVP - ADSI)
10/13/2004 9:45:26 AM
I'm not entirely sure if this is the problem, but it might be that the
format you are storing your encrypted binary data in is not correct. If you
want to store it as a string, Base64 is the standard approach and is less
code.

Use Convert.ToBase64String and Convert.FromBase64String to go back and forth
between the encrypted binary data and a string.

Joe K.

[quoted text, click to view]

peter NO[at]SPAM mclinn.com
10/14/2004 7:45:34 AM
Sure enough, I decoded to base 64 here:
txtReg.Text += (Chr(plainTextinBytes(i))) 'Encrypted data
to txtReg.Text = Convert.ToBase64String(plainTextinBytes)
and all of a sudden it started working. It must have been the
character conversions.



Thanks,

AddThis Social Bookmark Button