C# 实现SHA1withRSA

以你之姓@ 2021-12-04 01:39 343阅读 0赞

对称加密(DES、3DES)、非对称加密(RSA、SHA1withRSA)

参考: https://blog.csdn.net/sinat_16998945/article/details/94639023

#

一、支付宝工具生成公钥私钥

下载地址链接: https://pan.baidu.com/s/15L1GM8mK43tzV9XyyNEV8Q

提取码: vux3

使用方法可参考阿里文档:https://docs.open.alipay.com/291/105971/

二、加密

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzE2OTk4OTQ1_size_16_color_FFFFFF_t_70

说明:1.使用私钥签名, 2.签名后每次结果是不变的

三、解密

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzE2OTk4OTQ1_size_16_color_FFFFFF_t_70 1

说明:1.使用公钥验证签名

四、实现代码

利用工具可生成公私秘钥,注意(java版本与非java版本)

1.公钥 “MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCO772dmiRP4HaddeZTUieS4SWrNnbRPIgxoF5wLZNK1nel3hf7uffWkZ5lzjSuLig5sgPzU/oQgophIG9+NwoHeyXPgnhNV8zPluueHFrQzrSnq9jhUS1yxTezmYr+oxAQIyGQUZO21Sg1+2lqDyatPpRfN4JSKusAw9yOcbkHKQIDAQAB”

2.私钥 “MIICXgIBAAKBgQCO772dmiRP4HaddeZTUieS4SWrNnbRPIgxoF5wLZNK1nel3hf7uffWkZ5lzjSuLig5sgPzU/oQgophIG9+NwoHeyXPgnhNV8zPluueHFrQzrSnq9jhUS1yxTezmYr+oxAQIyGQUZO21Sg1+2lqDyatPpRfN4JSKusAw9yOcbkHKQIDAQABAoGAArchNgZAnFfaSQF9X6XW5J5sVcVSGoV43OB8CsuC2dAbM8Z1VC3jPGtFxA9XxttPnlD4bD3zKS8hq9iu5YnsIdL7bt1hu2vOW2UGtIPfYtTMK49BcgYHk1zIlQh21Jt403SM0hDmbpy/R32QQ3cv5jWnVvlEqiULyOC0joe9vTUCQQDAv4dOl3v3HQ40cWoe7RUKqbn0bBM4xIx2fwMBJTMJFJFWBq97CwtvuwKnlWle5dRDLTrwt7rETfNPW898nb3jAkEAvdeci8MLDAQE9KeIyxJK1170ahwkxTcO8miI5o/u6AekWk+YuNJh871YKoxwqPtD/2cDQH3PLxwklvVJExJ0gwJBAJ7QcP1ZpcPLxfuCA21t7St3A4gYUJIyqIWuS1xzOSTfNI0MPySDyi2KijpoyoRtnEKpjunuiM3caIDX5hMIqf8CQQCfFzYoZa43RpMEl/VqAI1ZiUiYN7eU0fwjpvi7Bvm11tmjmTqqABx4Dz/4gDLVWaP1P9WY0RW0LAh5vVqcsgWTAkEAk27NKkvwGR37bcHF2QwxeQkY+5pamJhIGvEm+dbhOm9P1mmcujrfZ49Aegy3RiIBQACHRNgjC6sYZcrs/wPrXw==”

3.加密调用:SHA1withRSA.Sign(“待签名字符串”, “私钥”, “UTF-8”);

4.解密调用:SHA1withRSA.Verify(“待签名字符串”, “签名后字符串”, “公钥 “, “UTF-8”);

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Common
  9. {
  10. public class SHA1withRSA
  11. {
  12. /// <summary>
  13. /// SHA1withRSA签名
  14. /// </summary>
  15. /// <param name="content">待签名字符串</param>
  16. /// <param name="privateKey">私钥</param>
  17. /// <param name="input_charset">编码格式</param>
  18. /// <returns>签名后字符串</returns>
  19. public static string Sign(string content, string privateKey, string input_charset)
  20. {
  21. byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
  22. RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
  23. using (var sh = SHA1.Create())
  24. {
  25. byte[] signData = rsa.SignData(Data, sh);
  26. return Convert.ToBase64String(signData);
  27. }
  28. }
  29. /// <summary>
  30. /// pem格式公钥验签
  31. /// </summary>
  32. /// <param name="content">待验签字符串</param>
  33. /// <param name="signedString">签名</param>
  34. /// <param name="publicKey">公钥</param>
  35. /// <param name="input_charset">编码格式</param>
  36. /// <returns>true(通过),false(不通过)</returns>
  37. public static bool Verify(string content, string signedString, string publicKey, string input_charset)
  38. {
  39. bool result = false;
  40. byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
  41. byte[] data = Convert.FromBase64String(signedString);
  42. RSAParameters paraPub = ConvertFromPublicKey(publicKey);
  43. RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
  44. rsaPub.ImportParameters(paraPub);
  45. using (var sh = SHA1.Create())
  46. {
  47. result = rsaPub.VerifyData(Data, sh, data);
  48. return result;
  49. }
  50. }
  51. #region 内部方法
  52. private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
  53. {
  54. RSACryptoServiceProvider rsa = DecodeRSAPrivateKey(Convert.FromBase64String(pemstr));
  55. return rsa;
  56. }
  57. private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
  58. {
  59. byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
  60. // --------- Set up stream to decode the asn.1 encoded RSA private key ------
  61. MemoryStream mem = new MemoryStream(privkey);
  62. BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
  63. byte bt = 0;
  64. ushort twobytes = 0;
  65. int elems = 0;
  66. try
  67. {
  68. twobytes = binr.ReadUInt16();
  69. if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  70. binr.ReadByte(); //advance 1 byte
  71. else if (twobytes == 0x8230)
  72. binr.ReadInt16(); //advance 2 bytes
  73. else
  74. return null;
  75. twobytes = binr.ReadUInt16();
  76. if (twobytes != 0x0102) //version number
  77. return null;
  78. bt = binr.ReadByte();
  79. if (bt != 0x00)
  80. return null;
  81. //------ all private key components are Integer sequences ----
  82. elems = GetIntegerSize(binr);
  83. MODULUS = binr.ReadBytes(elems);
  84. elems = GetIntegerSize(binr);
  85. E = binr.ReadBytes(elems);
  86. elems = GetIntegerSize(binr);
  87. D = binr.ReadBytes(elems);
  88. elems = GetIntegerSize(binr);
  89. P = binr.ReadBytes(elems);
  90. elems = GetIntegerSize(binr);
  91. Q = binr.ReadBytes(elems);
  92. elems = GetIntegerSize(binr);
  93. DP = binr.ReadBytes(elems);
  94. elems = GetIntegerSize(binr);
  95. DQ = binr.ReadBytes(elems);
  96. elems = GetIntegerSize(binr);
  97. IQ = binr.ReadBytes(elems);
  98. // ------- create RSACryptoServiceProvider instance and initialize with public key -----
  99. CspParameters CspParameters = new CspParameters();
  100. CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
  101. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024, CspParameters);
  102. RSAParameters RSAparams = new RSAParameters();
  103. RSAparams.Modulus = MODULUS;
  104. RSAparams.Exponent = E;
  105. RSAparams.D = D;
  106. RSAparams.P = P;
  107. RSAparams.Q = Q;
  108. RSAparams.DP = DP;
  109. RSAparams.DQ = DQ;
  110. RSAparams.InverseQ = IQ;
  111. RSA.ImportParameters(RSAparams);
  112. return RSA;
  113. }
  114. catch
  115. {
  116. return null;
  117. }
  118. finally
  119. {
  120. binr.Dispose();
  121. }
  122. }
  123. private static int GetIntegerSize(BinaryReader binr)
  124. {
  125. byte bt = 0;
  126. byte lowbyte = 0x00;
  127. byte highbyte = 0x00;
  128. int count = 0;
  129. bt = binr.ReadByte();
  130. if (bt != 0x02) //expect integer
  131. return 0;
  132. bt = binr.ReadByte();
  133. if (bt == 0x81)
  134. count = binr.ReadByte(); // data size in next byte
  135. else
  136. if (bt == 0x82)
  137. {
  138. highbyte = binr.ReadByte(); // data size in next 2 bytes
  139. lowbyte = binr.ReadByte();
  140. byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
  141. count = BitConverter.ToInt32(modint, 0);
  142. }
  143. else
  144. {
  145. count = bt; // we already have the data size
  146. }
  147. while (binr.ReadByte() == 0x00)
  148. { //remove high order zeros in data
  149. count -= 1;
  150. }
  151. binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
  152. return count;
  153. }
  154. #endregion
  155. #region 生成的Pem
  156. private static RSAParameters ConvertFromPublicKey(string pemFileConent)
  157. {
  158. if (string.IsNullOrEmpty(pemFileConent))
  159. {
  160. throw new ArgumentNullException("pemFileConent", "This arg cann't be empty.");
  161. }
  162. pemFileConent = pemFileConent.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", "");
  163. byte[] keyData = Convert.FromBase64String(pemFileConent);
  164. bool keySize1024 = (keyData.Length == 162);
  165. bool keySize2048 = (keyData.Length == 294);
  166. if (!(keySize1024 || keySize2048))
  167. {
  168. throw new ArgumentException("pem file content is incorrect, Only support the key size is 1024 or 2048");
  169. }
  170. byte[] pemModulus = (keySize1024 ? new byte[128] : new byte[256]);
  171. byte[] pemPublicExponent = new byte[3];
  172. Array.Copy(keyData, (keySize1024 ? 29 : 33), pemModulus, 0, (keySize1024 ? 128 : 256));
  173. Array.Copy(keyData, (keySize1024 ? 159 : 291), pemPublicExponent, 0, 3);
  174. RSAParameters para = new RSAParameters();
  175. para.Modulus = pemModulus;
  176. para.Exponent = pemPublicExponent;
  177. return para;
  178. }
  179. #endregion
  180. }
  181. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzE2OTk4OTQ1_size_16_color_FFFFFF_t_70 2

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SHA256WithRSA

    在[上文][Link 1]中了解到SHA和RSA,工作中恰好用到扩展应用:SHA256WithRSA,本文总结下学习过程,备忘の 再提供另外一种方法,实现Java版pem密