官网上的代码
/*****************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上的方式
- 通过获取证书接口获取证书相关值
ciphertext
associated_data
nonce_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
项目编译的方法,其中ciphertext
associated_data
nonce_dc
key
这几个值加密就是生成der文件流,可以将它保存为文件,下次直接读取文件,不用每次都去生成