微信小微商戶敏感信息加密


官網上的代碼

/*****************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上的方式

  1. 通過獲取證書接口獲取證書相關值
  2. 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文件流,可以將它保存為文件,下次直接讀取文件,不用每次都去生成


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM