如何用私钥解密RSA

问题描述 投票:0回答:0

我用 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");

{“找不到请求的对象。 "}

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

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

如何在 C# 中执行此操作?

c# python encryption cryptography rsa
© www.soinside.com 2019 - 2024. All rights reserved.