I have written a function in Python to encrypt data following RSA rules:
def encrypt_RSA(public_key_loc, message):
'''
param: public_key_loc Path to public key
param: message String to be encrypted
return base64 encoded encrypted string
'''
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(key)
rsakey = PKCS1_OAEP.new(rsakey)
encrypted = rsakey.encrypt(message)
return encrypted.encode('base64')
I have decrypt method in Python like this:
def decrypt_RSA(private_key_loc, package):
'''
param: public_key_loc Path to your private key
param: package String to be decrypted
return decrypted string
'''
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from base64 import b64decode
key = open(private_key_loc, "r").read()
rsakey = RSA.importKey(key)
rsakey = PKCS1_OAEP.new(rsakey)
decrypted = rsakey.decrypt(b64decode(package))
return decrypted
In C# I receive a encrypt string and decode but I have some trouble when import private key to decrypt
public static string DecryptEncryptedData(string Base64EncryptedData, string PathToPrivateKeyFile)
{
X509Certificate2 myCertificate;
myCertificate = new X509Certificate2(@"C:\Users\xxx\Documents\Visual Studio 2010\Projects\RSA\RSA\key.private");
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
But I have exception in this line `myCertificate = new X509Certificate2(@"C:\Users\xxx\Documents\Visual Studio 2010\Projects\RSA\RSA\key.private");
{"Cannot find the requested object.\r\n"}
But this file exist and here is the content.
-----BEGIN RSA PRIVATE KEY-----
KIIEpAIBAAKCAQEA2nUYgUoIm7Zy/5e+
9oeIQW9i6bF3Xb09drBANFu9jpp+Z5F5epp9PO2RhImRihaAvr5RT0dI
GAbDQJmZ5hIi+YpIXmELJrUCgYBZkAfOgfgsZNan3FVsZArO4ZH+mWQV5wEpAoxR
vL6eYgS1+fsy2e/qMTB/UOk8jIb5vJCVNTx7lfTGc9JKm50ia7ptoJmfAFBSjIWG
RjEAdTj5qxPaEbsgQKNvwnbtv7Obwg==
-----END RSA PRIVATE KEY-----
How can I do this in C#?