
官網上的代碼
/*****************c#代碼*********************/
/// <summary>
/// 加密敏感信息,傳入明文和從微信支付獲取到的敏感信息加密公鑰,事先使用OpenSSL轉換cert.pem文件輸出為der文件
/// </summary>
/// <param name="text"></param>
/// <param name="publicKeyBase64"></param>
/// <returns></returns>
public static string Encrypt(string text, byte[] publicKeyDER)
{
var x509 = new X509Certificate2(publicKeyDER);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key;
var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), false);
return Convert.ToBase64String(buff);
}
需要用到OpenSSL,可能本人比較笨,使用OpenSSL老是報錯,cmd各種找不到,直接不用這個方式,使用github上的方式
- 通過獲取證書接口獲取證書相關值
ciphertextassociated_datanonce_dc
key這個key是api秘鑰,商戶自己設置的;
string ciphertext = "獲取到的值";
string associated_data = "certificate";
string nonce_dc = "獲取證書的隨機數";
string key = "商戶api秘鑰";
byte[] nsec = Convert.FromBase64String(ciphertext);
//crypto_aead_aes256gcm_decrypt
byte[] text = SecretAeadAes.Decrypt(
nsec,
System.Text.Encoding.Default.GetBytes(nonce_dc),
System.Text.Encoding.Default.GetBytes(key),
System.Text.Encoding.UTF8.GetBytes(associated_data));
System.IO.FileStream fs = new System.IO.FileStream(@"3914A32659462BB090D406D3230842EEF3ED8130.txt", System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write);
fs.Write(text,0,text.Length);
var res= Encrypt("sss", text);
//加密
public static string Encrypt(string text, byte[] publicKeyDER)
{
var x509 = new X509Certificate2(publicKeyDER);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key;
var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), false);
return Convert.ToBase64String(buff);
}
SecretAeadAes是使用github上的
libsodium-net項目編譯的方法,其中ciphertextassociated_datanonce_dc
key這幾個值加密就是生成der文件流,可以將它保存為文件,下次直接讀取文件,不用每次都去生成
