所以,我需要的是未来:RSA加密和解密使用X509certificate2
- 创造发展certifiactes,得到一个客户端和一个服务器
- 检索通过API,它是从客户端编码的密码和解码它在服务器上
现在,我设法创建了以下this link certifiactes。在那里的女孩一步一步地指导如何获得自签名certifiactes,把它们放在商店,等等...现在,我有问题的部分:
我设法使用此加密我的数据代码:
public static string Encrypt(string stringForEncription, string PathToPrivateKey)
{
X509Certificate2 myCertificate;
try
{
myCertificate = new X509Certificate2(PathToPrivateKey, "Test123");
}
catch (Exception e)
{
throw new CryptographicException("Unable to open key file.");
}
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;
byte[] array = Encoding.UTF8.GetBytes(stringForEncription);
try
{
decryptedBytes = rsaObj.Encrypt(array, false);
//decryptedBytes = rsaObj.Encrypt(Convert.FromBase64String(Base64EncryptedData), false);
}
catch (Exception e)
{
throw new CryptographicException("Unable to encrypt data.");
}
// Check to make sure we decrpyted the string
if (decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
对于PathToPrivate密钥变量我正在使用我的客户ClientCert.pfx的路径。我不知道我是否应该使用任何其他,但这里是该文件夹的卡扣与所有我做的证书:现在
,对于解密,我使用下面的代码:
public static string DecryptEncryptedData(string Base64EncryptedData, string PathToPrivateKey)
{
X509Certificate2 myCertificate;
try
{
myCertificate = new X509Certificate2(PathToPrivateKey, "Test123");
}
catch (Exception e)
{
throw new CryptographicException("Unable to open key file.");
}
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 (Exception e)
{
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);
}
而且不管我尝试这样做,它给了我异常:
{"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "}
真的会apreciate有人帮助我。
@KayLee试过了,没有工作,证明是好的,关键是有的,我认为这个问题是在转换为Base64String和Base64String –
尝试测试DecryptEncryptedData(“你好”,串PathToPrivateKey);也许,同样的异常信息会根据我的经验显示出来。这意味着参数格式不正确(未正确加密)。希望这提供了一些线索。我确定这是关于byte,base64string,decryptedplainstring的格式。仔细分析一些像MSDN这样的示例博客,并不难。 –
我将在明天上午回顾我的代码后再回来。这是深夜。 –