Trying to figure out RSA encryption/Decryption

  • Thread starter Thread starter AndyNakamura
  • Start date Start date
A

AndyNakamura

Guest
I've been investigating RSA Encryption/Decryption and I've kind of got something working. After generating the keypair. I've got one application that encrypts a string from a textbox with the public key, and another application that decrypts with the private key. It works. If I click the encrypt button, I get the encrypted output in a textbox and write the byte array to a file(byte1.bin). I can then go to the other app and decrypt by using the private key and the byte1.bin file . The original text appears in a textbox.
The strange thing is, if I keep clicking the encrypt button, the encrypted output in the textbox keeps changing even though the plaintext is the same and the public key is the same. However the decrypt still works.
Anybody decipher what's happening? Or point me to a good tutorial on this.
I had to bodge the code below from a couple of C# examples.

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Public Enum KeySizes
size_512 = 512
size_1024 = 1024
size_2048 = 2048
size_4096 = 4096
End Enum

Public Class Form1
Dim publicKeyfilePath As String = "C:\RSA-PUBLIC-KEY\PublicKey.xml"
Dim privateKeyfilePath As String = "C:\RSA-PRIVATE-KEY\PrivateKey.xml"
Dim encrypted As Byte()

Private Sub btnGenKeys_Click(sender As Object, e As EventArgs) Handles btnGenKeys.Click
generateKeys(publicKeyfilePath, privateKeyfilePath)
End Sub
Sub generateKeys(publicKeyFile As String, privateKeyfile As String)
Dim RSA_ENCRYPT As RSACryptoServiceProvider = New RSACryptoServiceProvider((KeySizes.size_2048))
File.WriteAllText(publicKeyFile, RSA_ENCRYPT.ToXmlString(False)) 'Public Key
File.WriteAllText(privateKeyfile, RSA_ENCRYPT.ToXmlString(True)) 'Private Key
TxtPublicKey.Text = File.ReadAllText(publicKeyFile) 'Display public key in textbox
TxtPrivateKey.Text = File.ReadAllText(privateKeyfile) 'Display private key in textbox
End Sub

Private Sub BtnEncrypt_Click(sender As Object, e As EventArgs) Handles BtnEncrypt.Click
encrypted = encrypt(publicKeyfilePath, Encoding.UTF8.GetBytes(TextBox1.Text))
TextBox2.Text = BitConverter.ToString(encrypted)
File.WriteAllBytes("C:\RSA\Byte1.bin", encrypted)
End Sub
Function encrypt(publicKeyfile, Plain) As Byte()
Dim encrypted As Byte()
Dim RSA_ENCRYPT As RSACryptoServiceProvider = New RSACryptoServiceProvider((KeySizes.size_2048))
RSA_ENCRYPT.PersistKeyInCsp = False
Dim publicKey As String = File.ReadAllText(publicKeyfile)
RSA_ENCRYPT.FromXmlString(publicKey)
encrypted = RSA_ENCRYPT.Encrypt(Plain, True)
Return encrypted

End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'If Directory.Exists("C:\RSA") = False Then
' Directory.CreateDirectory("C:\RSA")
' generateKeys(publicKeyfilePath, privateKeyfilePath)

'End If
End Sub

End Class

Continue reading...
 
Back
Top