簡體   English   中英

如果有私鑰,則為C#如何解密?

[英]C# if I have private key How do I decrypt?

我像這樣用python加密

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

我在C#中嘗試過像這樣解密,但是它不起作用

namespace ConsoleApplication1
{

    class Program
    {
        private static string _message = @"gvVweOVn/+IBKNrFV1sb+khVu8PdBC78WusGH7IuCXxK4pEsFo8JbOb68phJAMVM1F8XPoq1PX4D
0VuVPmDFHadOUr59IX0IBbQ72bQ1/BoINimSVOzXRbHOfsNxd0kIEdCv6jNlA7ut7hcoGUz6XzdM
b+k8N2K9Dykjehoo9gZEhaXnws1YiuBVN4B+XyjB1VUrgji9fW60lcpL+0UYZ5mcUvK6T7hS7R9W
9QIf5T02iZJLsp3hxS9j/UxPCvK5Cj6t2h4fRCOYgiQv0L21ZD23nKYWgiGyGEmfArqIswUmZ0h2
I2zMs9vC2JVFIid6FpExHUScItBeuM8qYLA/YQ==";

        static void Main(string[] args)
        {

            Decrypt(_message);

        }

        private static void Decrypt(string text)
        {
            StreamReader sr = new StreamReader("./key.private");
        PemReader pr = new PemReader(sr);
        AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
        RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);            
        RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
        csp.ImportParameters(rsa);

        var bytesCypherText = Convert.FromBase64String(text);
        var bytesPlainTextData = csp.Decrypt(bytesCypherText, false);
        var plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);

        Console.WriteLine(plainTextData);

        }


    }
}

錯誤數據異常出現

在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

在這種情況下如何影響私鑰工作?

預先感謝!

在python端,您正在對加密的字符串進行base64編碼。 在嘗試使用C#對其解密之前,您需要對其進行base64解碼。 您還需要確保密碼參數(塊模式,填充等)在兩側都相同。

var bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

應該

var bytesPlainTextData = csp.Decrypt(bytesCypherText, true);

因為您在python代碼中使用PKCS1_OAEP填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM