![](/img/trans.png)
[英]How to parse(Convert to RSAParameters) X.509 private key in C#?
[英]How to import private key to c# RSAParameters object?
我想用 rsa 加密和解密 c# 中的数据。 我写了这段代码,它可以很好地加密,但我在解密时遇到了问题。 我的问题是什么?!
这是我的代码:
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Cry
{
public class CryptoUtils
{
public CryptoUtils ()
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData;
string decrptedStr = "";
var pub = Convert.FromBase64String("MCgCIQCfkl4xV5T/v3r1bifOc1mVHa9yak5pGjUfAv0r+s6+AwIDAQAB");
var prv = Convert.FromBase64String("MIGsAgEAAiEAn5JeMVeU/7969W4nznNZlR2vcmpOaRo1HwL9K/rOvgMCAwEAAQIg\nMce6pM/6xpIYrMoxluE7JBkVe9Sme9d6NPPJJX3NyBECEgCmwIarl1hSBnTqZNwJ\n8hZhqwIQAPT6CO/l/ma1sDi7eM7tCQISAKH90lYLlr9IinfSN3hp95g1AhAAlyNf\nuioqX1G+y/GVogyJAhEmQQB52juSQ574HnampzXUpQ==");
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) {
RSAParameters myRSAParameters = RSA.ExportParameters(false);
myRSAParameters.Modulus = pub;
myRSAParameters.Exponent = ByteConverter.GetBytes("65537");
myRSAParameters.D = prv;
encryptedData = RSAEncrypt(dataToEncrypt, myRSAParameters, false);
decryptedData = RSADecrypt(encryptedData, myRSAParameters, false);
decrptedStr = ByteConverter.GetString(decryptedData);
}
}
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) {
try {
byte[] encryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) {
RSA.ImportParameters(RSAKeyInfo);
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
} catch (CryptographicException e) {
Console.WriteLine(e.Message);
return null;
}
}
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) {
try {
byte[] decryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) {
RSA.ImportParameters(RSAKeyInfo);
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
} catch (CryptographicException e) {
Console.WriteLine(e.ToString());
return null;
}
}
}
}
行内encryptedData = RSAEncrypt(dataToEncrypt, myRSAParameters, false);
数据加密,但在下一行我有这个错误:
System.Security.Cryptography.CryptographicException: PKCS1 decoding error.
at System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter.DecryptKeyExchange (System.Byte[] rgbIn) [0x00000] in <filename unknown>:0
at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt (System.Byte[] rgb, Boolean fOAEP) [0x00000] in <filename unknown>:0
我想我没有正确填充myRSAParameters
属性,但我不知道如何填充它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.