我像这样用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);
}
}
}
Bad Data exception appear
在 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 解码。您还需要确保两侧的密码参数( block 模式、填充等)相同。
关于C# 如果我有私钥我该如何解密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23615181/