如何使用私钥解密RSA

时间:2014-05-12 07:29:24

标签: c# python encryption cryptography rsa

我在python中编写函数来加密数据遵循RSA规则。

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')

我在python中有解密方法

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

在C#中,我收到一个加密字符串并解码,但是在导入私钥解密时我遇到了一些麻烦

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); 
        }

但我在这行中有例外`myCertificate = new X509Certificate2(@" C:\ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ RSA \ RSA \ key.private");

  

{"找不到请求的对象。\ r \ n"}

但是这个文件存在,这里是内容。

-----BEGIN RSA PRIVATE KEY-----
KIIEpAIBAAKCAQEA2nUYgUoIm7Zy/5e+
9oeIQW9i6bF3Xb09drBANFu9jpp+Z5F5epp9PO2RhImRihaAvr5RT0dI
GAbDQJmZ5hIi+YpIXmELJrUCgYBZkAfOgfgsZNan3FVsZArO4ZH+mWQV5wEpAoxR
vL6eYgS1+fsy2e/qMTB/UOk8jIb5vJCVNTx7lfTGc9JKm50ia7ptoJmfAFBSjIWG
RjEAdTj5qxPaEbsgQKNvwnbtv7Obwg==
-----END RSA PRIVATE KEY-----

其实不知道怎么做C#。 提前谢谢!

0 个答案:

没有答案