Last active
June 22, 2016 06:41
-
-
Save hathawad/6296051 to your computer and use it in GitHub Desktop.
Use a .pfx file to RSA Encrypt via VB.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System | |
Imports System.IO | |
Imports System.Security.Cryptography | |
Imports System.Text | |
Imports System.Security.Cryptography.X509Certificates | |
Class Module1 | |
Public Shared Sub Main() | |
Dim plainString As String | |
Dim encryptedString As String | |
Dim decryptedString As String | |
plainString = "account_name='Doug Hathaway'&account_number=123135235234&..." | |
encryptedString = encryptString(plainString) | |
'Console Output | |
Console.WriteLine("Plain String: " + plainString) | |
Console.WriteLine("Encryped String: " + encryptedString) | |
' Now decrypt same string | |
decryptedString = decryptString(encryptedString) | |
Console.WriteLine("Decrypted String: " + decryptedString) | |
'Write to a file for easy copy/paste | |
Using outfile As New StreamWriter("c:\test_encrypted_string.txt") | |
outfile.Write(encryptedString) | |
End Using | |
Console.WriteLine("Press Any Key to Continue...") | |
Console.ReadKey() | |
End Sub | |
Public Shared Function encryptString(ByVal plainString As String) As String | |
'Note: the .pfx certifcation file can be located anywhere, just need to point to it | |
'Load the .pfx file (this contains the public encryption key) | |
Dim cert As New X509Certificate2("c:\certificate.pfx", "", X509KeyStorageFlags.Exportable) | |
Dim rsaProvider As RSACryptoServiceProvider = DirectCast(cert.PublicKey.Key, RSACryptoServiceProvider) | |
'Convert the string into a Byte Array and encrypt w/ public key | |
Dim bytesToEncrypt() As Byte = Encoding.ASCII.GetBytes(plainString) | |
Dim encryptedBytes() As Byte = rsaProvider.Encrypt(bytesToEncrypt, False) | |
'Return binary as base64 string | |
Return Convert.ToBase64String(encryptedBytes) | |
End Function | |
Public Shared Function decryptString(ByVal plainString As String) As String | |
'Note: the .pfx certifcation file can be located anywhere, just need to point to it | |
'Load the .pfx file (this contains the public encryption key) | |
Dim cert As New X509Certificate2("c:\certificate.pfx", "", X509KeyStorageFlags.Exportable) | |
Dim rsaProvider As RSACryptoServiceProvider = DirectCast(cert.PrivateKey, RSACryptoServiceProvider) | |
'Convert the string into a Byte Array and dencrypt w/ private key | |
Dim bytesToDecrypt() As Byte = Convert.FromBase64String(plainString) | |
Dim decryptedBytes() As Byte = rsaProvider.Decrypt(bytesToDecrypt, False) | |
'Return ASCII string | |
Return Encoding.ASCII.GetString(decryptedBytes) | |
End Function | |
End Class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment