I created a public and private key using openssl in the cmd line of a linux machine using the following commands:
openssl genrsa -out rsa_1024_priv.pem 1024
openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
Now I want to be able to decrypt data in VB.NET that was already encrypted with the public key.
I am using the method found in the MSDN documentation for decryption. I am trying to set the RSAParameters to pass in to the RSADecrypt
method, but I'm not really sure what goes into each field.
Whenever I try running the code I get the following error:
System.Security.Cryptography.CryptographicException: Bad Data. at System.Security.Cryptography.CryptographicException.ThrowCryptographicExce ption(Int32 hr) at System.Security.Cryptography.Utils._ImportKey(SafeProvHandle hCSP, Int32 k eyNumber, CspProviderFlags flags, Object cspObject, SafeKeyHandle& hKey) at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSA Parameters parameters) at Decryptor.Module1.RSADecrypt(Byte[] DataToDecrypt, RSAParameters RSAKeyInf o, Boolean DoOAEPPadding) in C:\Users\yhorowitz\AppData\Local\Temporary Projects \Decryptor\Module1.vb:line 30
The error is being thrown on this line RSA.ImportParameters(RSAKeyInfo)
in the RSADecrypt
method
This is the code I have so far:
Imports System.Security.Cryptography
Imports System.Text
Module Module1
Dim encoder As New UTF8Encoding
Sub Main()
Dim MyPrivateKey As String = "" 'Removed
Dim MyPublicKey As String = "" 'Removed
Dim MyModulus as String = "" 'Removed
Dim DataToDecrypt() As Byte = Convert.FromBase64String("CourNHBC55DgGtBZU6Ahtm0emywGi5hWo5/h9zD6A/NASKMpZ/A5GCU8G5TNTMgJQxVFsabbdeuNhf4VQzBuFqewuD8eD7MwpJvjmuPfrs7xcEzOrwbF549v0PHv/nfN+03winW6s3ecnv1dm0TctQgqsauEuvXu2PMVEFivqPo=")
Dim params As RSAParameters = New RSAParameters()
params.Exponent = Convert.FromBase64String(MyPublicKey)
params.D = Convert.FromBase64String(MyPrivateKey)
params.Modulus = Convert.FromBase64String(MyModulus)
Console.WriteLine(Convert.ToString(RSADecrypt(DataToDecrypt, params, False)))
Console.Read()
End Sub
Public Function RSADecrypt(ByVal DataToDecrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
Try
Dim decryptedData() As Byte
'Create a new instance of RSACryptoServiceProvider.
Using RSA As New RSACryptoServiceProvider(1024)
RSA.ImportParameters(RSAKeyInfo)
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding)
End Using
Return decryptedData
Catch e As CryptographicException
Console.WriteLine(e.ToString())
Return Nothing
End Try
End Function
End Module