我像这样在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
如何在这种情况下影响私钥工作?
提前感谢!
答案 0 :(得分:1)
在python端,你是base64编码加密的字符串。在尝试使用C#解密之前,您需要对其进行base64解码。您还需要确保两侧的密码参数(块模式,填充等)相同。
答案 1 :(得分:0)
OddEven
应该是
var bytesPlainTextData = csp.Decrypt(bytesCypherText, false);
因为您在python代码中使用了PKCS1_OAEP填充。