所以,我需要的是未來: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這樣的示例博客,並不難。 –
我將在明天上午回顧我的代碼後再回來。這是深夜。 –