https://www.bouncycastle.org/csharp/index.html https://github.com/bcgit/bc-csharp

工具类

  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using Org.BouncyCastle.Asn1;
  6. using Org.BouncyCastle.Asn1.Pkcs;
  7. using Org.BouncyCastle.Asn1.X509;
  8. using Org.BouncyCastle.Crypto;
  9. using Org.BouncyCastle.Crypto.Encodings;
  10. using Org.BouncyCastle.Crypto.Engines;
  11. using Org.BouncyCastle.Crypto.Generators;
  12. using Org.BouncyCastle.Crypto.Parameters;
  13. using Org.BouncyCastle.Math;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.Security;
  16. using Org.BouncyCastle.X509;
  17. namespace Common.Util
  18. {
  19. public static class RsaUtil
  20. {
  21. /// <summary>
  22. /// 生成密钥对
  23. /// </summary>
  24. /// <param name="privateKey">私钥</param>
  25. /// <param name="publicKey">公钥</param>
  26. public static void CreateKey(out string privateKey, out string publicKey)
  27. {
  28. //RSA密钥对的构造器
  29. RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
  30. //RSA密钥构造器的参数
  31. RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3),new SecureRandom(),1024, 25);//密钥长度
  32. //用参数初始化密钥构造器
  33. keyGenerator.Init(param);
  34. //产生密钥对
  35. AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
  36. //获取公钥和密钥
  37. AsymmetricKeyParameter keyPairPublic = keyPair.Public;
  38. AsymmetricKeyParameter keyPairPrivate = keyPair.Private;
  39. SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPairPublic);
  40. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPairPrivate);
  41. Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
  42. byte[] publicInfoByte = asn1ObjectPublic.GetEncoded();
  43. publicKey = Convert.ToBase64String(publicInfoByte);
  44. Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
  45. byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();
  46. privateKey = Convert.ToBase64String(privateInfoByte);
  47. }
  48. public static string Sign(string data, string privateKey, string charset = "utf-8", string signType = "RSA")
  49. {
  50. RSACryptoServiceProvider rsaCsp = DecodePrivateKeyInfo(privateKey, signType);
  51. byte[] dataBytes = null;
  52. if (string.IsNullOrEmpty(charset))
  53. {
  54. dataBytes = Encoding.UTF8.GetBytes(data);
  55. }
  56. else
  57. {
  58. dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
  59. }
  60. HashAlgorithm hash = new SHA1CryptoServiceProvider();
  61. if ("RSA2".Equals(signType))
  62. {
  63. hash = new SHA256CryptoServiceProvider();
  64. }
  65. byte[] signatureBytes = rsaCsp.SignData(dataBytes, hash);
  66. return Convert.ToBase64String(signatureBytes);
  67. }
  68. public static string SignWithMd5(string data, string privateKey, string charset = "utf-8", string signType = "RSA")
  69. {
  70. RSACryptoServiceProvider rsaCsp = DecodePrivateKeyInfo(privateKey, signType);
  71. byte[] dataBytes = null;
  72. if (string.IsNullOrEmpty(charset))
  73. {
  74. dataBytes = Encoding.UTF8.GetBytes(data);
  75. }
  76. else
  77. {
  78. dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
  79. }
  80. byte[] signatureBytes = rsaCsp.SignData(dataBytes, "MD5");
  81. return Convert.ToBase64String(signatureBytes);
  82. }
  83. //public static string Sign(string data, string privateKey, string charset = "utf-8", string signType = "RSA")
  84. //{
  85. // RSACryptoServiceProvider rsaCsp = DecodePrivateKeyInfo(privateKey, signType);
  86. // byte[] dataBytes = null;
  87. // if (string.IsNullOrEmpty(charset))
  88. // {
  89. // dataBytes = Encoding.UTF8.GetBytes(data);
  90. // }
  91. // else
  92. // {
  93. // dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
  94. // }
  95. // HashAlgorithm hash = new SHA1CryptoServiceProvider();
  96. // if ("RSA2".Equals(signType))
  97. // {
  98. // hash = new SHA256CryptoServiceProvider();
  99. // }
  100. // byte[] signatureBytes = rsaCsp.SignData(dataBytes, hash);
  101. // return Convert.ToBase64String(signatureBytes);
  102. //}
  103. public static bool Verify(string data, string publicKeyJava, string signature, string charset = "utf-8", string signType = "RSA")
  104. {
  105. RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKeyJava));
  106. ISigner signer = SignerUtilities.GetSigner("RSA2".Equals(signType) ? "SHA256withRSA" : "SHA1withRSA");
  107. signer.Init(false, publicKeyParam);
  108. byte[] dataByte = Encoding.GetEncoding(charset).GetBytes(data);
  109. signer.BlockUpdate(dataByte, 0, dataByte.Length);
  110. byte[] signatureByte = Convert.FromBase64String(signature);
  111. return signer.VerifySignature(signatureByte);
  112. }
  113. public static bool VerifyWithMd5(string data, string publicKeyJava, string signature)
  114. {
  115. RSACryptoServiceProvider rsaCsp = DecodePublicKey(publicKeyJava);
  116. var result = rsaCsp.VerifyData(Encoding.UTF8.GetBytes(data), "MD5", Convert.FromBase64String(signature));
  117. return result;
  118. }
  119. //public static bool Verify(string data, string publicKey, string signature, string charset = "utf-8", string signType = "RSA")
  120. //{
  121. // //RSACryptoServiceProvider rsaCsp = GetRsaPublicProvider(publicKey);
  122. // RSACryptoServiceProvider rsaCsp = DecodePublicKey(publicKey);
  123. // var encoding = string.IsNullOrEmpty(charset) ? Encoding.UTF8 : Encoding.GetEncoding(charset);
  124. // var dataBytes = encoding.GetBytes(data);
  125. // HashAlgorithm hash = signType== "RSA2" ? new SHA256CryptoServiceProvider() as HashAlgorithm
  126. // : new SHA1CryptoServiceProvider() as HashAlgorithm;
  127. // byte[] signatureBytes = Convert.FromBase64String(signature);
  128. // return rsaCsp.VerifyData(dataBytes, hash, signatureBytes);
  129. //}
  130. //public static string Encrypt(string data, string privateKey, string charset = "utf-8", string signType = "RSA")
  131. //{
  132. // RSACryptoServiceProvider rsaCsp = DecodePrivateKeyInfo(privateKey, signType);
  133. // byte[] dataBytes = null;
  134. // if (string.IsNullOrEmpty(charset))
  135. // {
  136. // dataBytes = Encoding.UTF8.GetBytes(data);
  137. // }
  138. // else
  139. // {
  140. // dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
  141. // }
  142. // var temp = rsaCsp.Encrypt(dataBytes, false);
  143. // var result = Convert.ToBase64String(temp);
  144. // return result;
  145. //}
  146. public static string Encrypt(string data, string publicKey, string charset = "utf-8")
  147. {
  148. RSACryptoServiceProvider rsa = GetRsaPublicProvider(publicKey);
  149. var encoding = string.IsNullOrEmpty(charset) ? Encoding.UTF8 : Encoding.GetEncoding(charset);
  150. encoding = Encoding.UTF8;
  151. var dataBytes = encoding.GetBytes(data);
  152. var temp = rsa.Encrypt(dataBytes, false);
  153. var result = Convert.ToBase64String(temp);
  154. return result;
  155. }
  156. public static string Decrypt(string data, string privateKey, string charset = "utf-8")
  157. {
  158. RSACryptoServiceProvider rsa = GetRsaPrivateProvider(privateKey);
  159. var dataBytes = Convert.FromBase64String(data);
  160. byte[] source = rsa.Decrypt(dataBytes, false);
  161. var encoding = string.IsNullOrEmpty(charset) ? Encoding.UTF8 : Encoding.GetEncoding(charset);
  162. encoding = Encoding.UTF8;
  163. var result = encoding.GetString(source);
  164. return result;
  165. }
  166. public static string EncryptByPrivateKey(string data, string privateKey)
  167. {
  168. IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
  169. string result;
  170. try
  171. {
  172. engine.Init(true, GetPrivateKeyParameter(privateKey));
  173. byte[] bytes = Encoding.UTF8.GetBytes(data);
  174. result = Convert.ToBase64String(engine.ProcessBlock(bytes, 0, bytes.Length));
  175. }
  176. catch (Exception ex)
  177. {
  178. result = ex.Message;
  179. }
  180. return result;
  181. }
  182. public static string DecryptByPublicKey(string data, string publicKey)
  183. {
  184. IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
  185. string result;
  186. try
  187. {
  188. engine.Init(false, GetPublicKeyParameter(publicKey));
  189. byte[] byteData = Convert.FromBase64String(data);
  190. byte[] ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
  191. result = Encoding.UTF8.GetString(ResultData);
  192. }
  193. catch (Exception ex)
  194. {
  195. result = ex.Message;
  196. }
  197. return result;
  198. }
  199. private static AsymmetricKeyParameter GetPublicKeyParameter(string publicKey)
  200. {
  201. publicKey = publicKey.Replace("\r", "").Replace("\n", "").Replace(" ", "");
  202. byte[] bytes = Convert.FromBase64String(publicKey);
  203. Asn1Object.FromByteArray(bytes);
  204. return PublicKeyFactory.CreateKey(bytes);
  205. }
  206. private static AsymmetricKeyParameter GetPrivateKeyParameter(string privateKey)
  207. {
  208. privateKey = privateKey.Replace("\r", "").Replace("\n", "").Replace(" ", "");
  209. return PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
  210. }
  211. public static RSACryptoServiceProvider GetRsaPrivateProvider(string privateKey)
  212. {
  213. RsaPrivateCrtKeyParameters privateKeyParams =
  214. PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)) as RsaPrivateCrtKeyParameters;
  215. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  216. RSAParameters rsaParams = new RSAParameters()
  217. {
  218. Modulus = privateKeyParams.Modulus.ToByteArrayUnsigned(),
  219. Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(),
  220. D = privateKeyParams.Exponent.ToByteArrayUnsigned(),
  221. DP = privateKeyParams.DP.ToByteArrayUnsigned(),
  222. DQ = privateKeyParams.DQ.ToByteArrayUnsigned(),
  223. P = privateKeyParams.P.ToByteArrayUnsigned(),
  224. Q = privateKeyParams.Q.ToByteArrayUnsigned(),
  225. InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned()
  226. };
  227. rsa.ImportParameters(rsaParams);
  228. return rsa;
  229. }
  230. public static RSACryptoServiceProvider GetRsaPublicProvider(string pubilcKey)
  231. {
  232. RsaKeyParameters p =
  233. PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters;
  234. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  235. RSAParameters rsaParams = new RSAParameters
  236. {
  237. Modulus = p.Modulus.ToByteArrayUnsigned(),
  238. Exponent = p.Exponent.ToByteArrayUnsigned()
  239. };
  240. rsa.ImportParameters(rsaParams);
  241. return rsa;
  242. }
  243. /// <summary>
  244. /// 根据私钥生成RSACryptoServiceProvider
  245. /// </summary>
  246. /// <param name="privateKey">私钥</param>
  247. /// <param name="rsaType">RSA类型</param>
  248. /// <returns></returns>
  249. public static RSACryptoServiceProvider DecodePrivateKeyInfo(string privateKey,string rsaType)
  250. {
  251. if (string.IsNullOrEmpty(privateKey))
  252. {
  253. throw new Exception("传入私钥不能为空!");
  254. }
  255. var privateKeyByte = Convert.FromBase64String(privateKey);
  256. byte[] seqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  257. byte[] seq = new byte[15];
  258. MemoryStream mem = new MemoryStream(privateKeyByte);
  259. int lenstream = (int)mem.Length;
  260. BinaryReader binr = new BinaryReader(mem); ////wrap Memory Stream with BinaryReader for easy reading
  261. byte bt = 0;
  262. ushort twobytes = 0;
  263. try
  264. {
  265. twobytes = binr.ReadUInt16();
  266. if (twobytes == 0x8130) ////data read as little endian order (actual data order for Sequence is 30 81)
  267. binr.ReadByte(); ////advance 1 byte
  268. else if (twobytes == 0x8230)
  269. binr.ReadInt16(); ////advance 2 bytes
  270. else
  271. return null;
  272. bt = binr.ReadByte();
  273. if (bt != 0x02)
  274. return null;
  275. twobytes = binr.ReadUInt16();
  276. if (twobytes != 0x0001)
  277. return null;
  278. seq = binr.ReadBytes(15); ////read the Sequence OID
  279. if (!CompareBytearrays(seq, seqOID)) ////make sure Sequence for OID is correct
  280. return null;
  281. bt = binr.ReadByte();
  282. if (bt != 0x04) ////expect an Octet string
  283. return null;
  284. bt = binr.ReadByte(); ////read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
  285. if (bt == 0x81)
  286. binr.ReadByte();
  287. else
  288. if (bt == 0x82)
  289. binr.ReadUInt16();
  290. ////------ at this stage, the remaining sequence should be the RSA private key
  291. byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
  292. RSACryptoServiceProvider rsacsp = DecodePrivateKey(rsaprivkey, rsaType);
  293. return rsacsp;
  294. }
  295. catch (Exception e)
  296. {
  297. throw e;
  298. }
  299. finally
  300. {
  301. binr.Close();
  302. }
  303. }
  304. private static RSACryptoServiceProvider DecodePrivateKey(byte[] privkey, string rsaType)
  305. {
  306. byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
  307. // --------- Set up stream to decode the asn.1 encoded RSA private key ------
  308. MemoryStream mem = new MemoryStream(privkey);
  309. BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
  310. byte bt = 0;
  311. ushort twobytes = 0;
  312. int elems = 0;
  313. try
  314. {
  315. twobytes = binr.ReadUInt16();
  316. if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  317. binr.ReadByte(); //advance 1 byte
  318. else if (twobytes == 0x8230)
  319. binr.ReadInt16(); //advance 2 bytes
  320. else
  321. return null;
  322. twobytes = binr.ReadUInt16();
  323. if (twobytes != 0x0102) //version number
  324. return null;
  325. bt = binr.ReadByte();
  326. if (bt != 0x00)
  327. return null;
  328. //------ all private key components are Integer sequences ----
  329. elems = GetIntegerSize(binr);
  330. MODULUS = binr.ReadBytes(elems);
  331. elems = GetIntegerSize(binr);
  332. E = binr.ReadBytes(elems);
  333. elems = GetIntegerSize(binr);
  334. D = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length);
  335. BitConverter.ToInt64(D, 0);
  336. elems = GetIntegerSize(binr);
  337. P = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length / 2);
  338. elems = GetIntegerSize(binr);
  339. Q = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length / 2);
  340. elems = GetIntegerSize(binr);
  341. DP = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length / 2);
  342. elems = GetIntegerSize(binr);
  343. DQ = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length / 2);
  344. elems = GetIntegerSize(binr);
  345. IQ = FixShortageOfArray(binr.ReadBytes(elems), MODULUS.Length / 2);
  346. // ------- create RSACryptoServiceProvider instance and initialize with public key -----
  347. CspParameters CspParameters = new CspParameters();
  348. CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
  349. int bitLen = 1024;
  350. if ("RSA2".Equals(rsaType))
  351. {
  352. bitLen = 2048;
  353. }
  354. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(bitLen, CspParameters);
  355. RSAParameters RSAparams = new RSAParameters();
  356. RSAparams.Modulus = MODULUS;
  357. RSAparams.Exponent = E;
  358. RSAparams.D = D;
  359. RSAparams.P = P;
  360. RSAparams.Q = Q;
  361. RSAparams.DP = DP;
  362. RSAparams.DQ = DQ;
  363. RSAparams.InverseQ = IQ;
  364. RSA.ImportParameters(RSAparams);
  365. return RSA;
  366. }
  367. catch (Exception ex)
  368. {
  369. return null;
  370. }
  371. finally
  372. {
  373. binr.Close();
  374. }
  375. }
  376. /// <summary>
  377. /// 根据公钥的Byte[],生成RSACryptoServiceProvider
  378. /// </summary>
  379. /// <param name="publickey">公钥Byte[]</param>
  380. /// <returns></returns>
  381. private static RSACryptoServiceProvider DecodePublicKey(string publicKey)
  382. {
  383. byte[] keyData = Convert.FromBase64String(publicKey);
  384. if (keyData.Length < 162)
  385. {
  386. throw new Exception("公钥Byte[]长度小于162");
  387. }
  388. byte[] pemModulus = new byte[128];
  389. byte[] pemPublicExponent = new byte[3];
  390. try
  391. {
  392. Array.Copy(keyData, 29, pemModulus, 0, 128);
  393. Array.Copy(keyData, 159, pemPublicExponent, 0, 3);
  394. RSAParameters para = new RSAParameters();
  395. para.Modulus = pemModulus;
  396. para.Exponent = pemPublicExponent;
  397. CspParameters CspParameters = new CspParameters();
  398. CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
  399. int bitLen = 1024;
  400. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(bitLen, CspParameters);
  401. RSA.ImportParameters(para);
  402. return RSA;
  403. }
  404. catch (Exception e)
  405. {
  406. throw e;
  407. }
  408. finally
  409. {
  410. }
  411. }
  412. /// <summary>
  413. /// base64 public key string -> xml public key
  414. /// </summary>
  415. /// <param name="pubilcKey"></param>
  416. /// <returns></returns>
  417. public static string ToXmlPublicKey(string pubilcKey)
  418. {
  419. RsaKeyParameters p =
  420. PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters;
  421. using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  422. {
  423. RSAParameters rsaParams = new RSAParameters
  424. {
  425. Modulus = p.Modulus.ToByteArrayUnsigned(),
  426. Exponent = p.Exponent.ToByteArrayUnsigned()
  427. };
  428. rsa.ImportParameters(rsaParams);
  429. return rsa.ToXmlString(false);
  430. }
  431. }
  432. private static bool CompareBytearrays(byte[] a, byte[] b)
  433. {
  434. if (a.Length != b.Length)
  435. return false;
  436. int i = 0;
  437. foreach (byte c in a)
  438. {
  439. if (c != b[i])
  440. return false;
  441. i++;
  442. }
  443. return true;
  444. }
  445. private static int GetIntegerSize(BinaryReader binr)
  446. {
  447. byte bt = 0;
  448. byte lowbyte = 0x00;
  449. byte highbyte = 0x00;
  450. int count = 0;
  451. bt = binr.ReadByte();
  452. if (bt != 0x02) //expect integer
  453. return 0;
  454. bt = binr.ReadByte();
  455. if (bt == 0x81)
  456. count = binr.ReadByte(); // data size in next byte
  457. else
  458. if (bt == 0x82)
  459. {
  460. highbyte = binr.ReadByte(); // data size in next 2 bytes
  461. lowbyte = binr.ReadByte();
  462. byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
  463. count = BitConverter.ToInt32(modint, 0);
  464. }
  465. else
  466. {
  467. count = bt; // we already have the data size
  468. }
  469. while (binr.ReadByte() == 0x00)
  470. { //remove high order zeros in data
  471. count -= 1;
  472. }
  473. binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
  474. return count;
  475. }
  476. /// <summary>
  477. /// 修复位数不足的数组
  478. /// </summary>
  479. /// <param name="needFixArray">待修复数组</param>
  480. /// <param name="lenth">正确的位数长度</param>
  481. /// <returns></returns>
  482. private static byte[] FixShortageOfArray(byte[] needFixArray, int lenth)
  483. {
  484. //不需要修复
  485. if (needFixArray.Length == lenth)
  486. {
  487. return needFixArray;
  488. }
  489. else
  490. {
  491. byte[] newArray = new byte[lenth];
  492. Buffer.BlockCopy(needFixArray, 0, newArray, newArray.Length - needFixArray.Length, needFixArray.Length);
  493. return newArray;
  494. }
  495. }
  496. }
  497. }

单元测试

  1. using System;
  2. using System.Web;
  3. using System.Linq;
  4. using System.Text;
  5. using Common.Util;
  6. using System.Security.Cryptography;
  7. using System.Security.Cryptography.X509Certificates;
  8. using Microsoft.VisualStudio.TestTools.UnitTesting;
  9. namespace Test.Util
  10. {
  11. [TestClass]
  12. public class RsaTest
  13. {
  14. [TestMethod]
  15. public void CreateTest()
  16. {
  17. RsaUtil.CreateKey(out string privateKey,out string publicKey);
  18. }
  19. [TestMethod]
  20. public void CertificateSignTest()
  21. {
  22. X509Certificate2 certificate2 = new X509Certificate2("D:\\client34.pfx", "123456");
  23. string privateKey= @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/lc0yBwq4kbkKJgf0rcJ5mTmnbjOwBVs1U6ZZr/kf8iwgx0e1GSuqlMMAVCMdRSakQbSYgm2KlAs7YKKlH8QiqKfnpZnhIQwpKMWg20OCNA5/e9FoZRH1aRmSc6QV8zopJd2udN0+bFgd4AtMcOZLUOwMwNX7CF5hb+W0iFdEfL1WPYGT1V1QCPleZCbCE1XpJvQcTTBKua4sNsVDbiCd40uFjy1OGEt/7mfO95vCsu/NhWTIUN9En5igvmJ/XpMaz3cuBMPqHjvTQkJpT1On2gzas2JhhUW1vsZC9//wQmuWEVwyoqB3Wx+65vY90mUVqnXzSxx7JlHTzQntGMAhAgMBAAECggEAQXb0qNWTKkJRElCwg0EkpNxgwP99FfaelfhBbYAeBnZ/8atmq1EwhJdUkrYtUYEhlRsGlN5sg9/WfrGkofvaz2UGCrehfzYFq8LM1QxXYxRap+EtSxjOLCd/n3V4ai+0ff78YvJ37y6iZYL7GWGyr6W1Ix55f8/6QB02RpwYBcRqBjlltrYRudwI9I4zMhTqJfdJ6B0nxDmy9gj+vzz37SARd6drBvcYke7xqWskm9tpRCcD5Smr7TdGwOMumSsNpNeJbyH6YqO7So0YkIQE7WCYxdqLLrBVEHvMHm9RCyNnNfQEzJx/G6Ho3LpJcqMccoXTsww17/o/fj+E3jIHiQKBgQDy8+rwq4tF6KFxircjtbXmAm5izsPXDls+ibZcJpbeKIuYgM8Sh91wq1zC+4Q5AnO0GGqfCSJxmNjUvZAqtD9pdlkz2D96htqnLnn9ZqcV7VzsTEQmuXw46THSfBb/GTny16/WOsYGHG00R14a1g2bDk9bi964ggyMLrHeTUU9YwKBgQDJ37A80Ka6dy7MKI3Ob8vLpDfZTl7NKN9k6jljasMaj5b0hmXbARn1uoiAz+urSOCuR78RPUEeO96uNg+EuW32i1JdUqr/2jhg4MVmHu6wcLzBAXHOA0+huJTDvQ3d8geNmjJ8JxUZ7kWA1SXJ29D2gIFT9rVhtRprE++I11P1qwKBgD0suf271CfYOb6TRSYSvSibeBwdICbokIUgu/BcLyTlZLETzhBGcbXLEGJwXozUVzoD4+UDsc6UxBRdXw3BsS3nBPMPAnzhs/DgvQrXbD8TM5C0a3ysu+DApzDu2gOF4JeLQ9VXm0EyqzS8u69aMrbWVZkhkQU4idxKbbMiFcstAoGBAKwkiDdDwXkuGoTTbCEGKiWL8mfmsWaHHQADz04cgyTKHvKDDKYVKVrmZnJZWuBjs9xJp/9+WWH7saaiyNbn/IIJSgH0dYbZQcwyv4GWjPl+GScIIVCIeEYyjQDg3MtPEOvJ+pTuCsti6He0ypV4UZdx+1ZrAT7BXTbD+DWbUKgjAoGAVD4FuWYul7SJ9gNP5Ozu+IliUhnbfrxzw+oneFwAF2Vse1nwdz6kqq0+JfZNhOC553AzX9zZbtzGTzi26D9hh8rOOP8SpJ1Hav6JzVMIQLooyBY/amLgV2N11qgJ9n91NX4o4BcNXXUPr0AkyeSxXmE2zGeXwEbth4svRxH9/+I=";
  24. string publicKey= @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv5XNMgcKuJG5CiYH9K3CeZk5p24zsAVbNVOmWa/5H/IsIMdHtRkrqpTDAFQjHUUmpEG0mIJtipQLO2CipR/EIqin56WZ4SEMKSjFoNtDgjQOf3vRaGUR9WkZknOkFfM6KSXdrnTdPmxYHeALTHDmS1DsDMDV+wheYW/ltIhXRHy9Vj2Bk9VdUAj5XmQmwhNV6Sb0HE0wSrmuLDbFQ24gneNLhY8tThhLf+5nzvebwrLvzYVkyFDfRJ+YoL5if16TGs93LgTD6h4700JCaU9Tp9oM2rNiYYVFtb7GQvf/8EJrlhFcMqKgd1sfuub2PdJlFap180sceyZR080J7RjAIQIDAQAB";
  25. var value = @"certId=1cb30bf9ffcd6615d4c44292894dc6691d0eca22&encoding=UTF-8&legalPersonEdate=2099-12-31&legalPersonIdentityNo=1d63ff61a2c83ee94c30f390d32d52fc497f6ad001db82da69c8ae0df2bc483d&legalPersonName=d7ecc34011e355d97ac04fcaa5ca1389&legalPersonSdate=2018-05-10&licenseEdate=2099-12-31&licenseSdate=2018-05-10&licenseType=2&merAddress=豪威科技大厦一楼排队美食&merCatCode=5812&merCityId=440300&merCreationDate=2018-05-10&merEnglishName=PDMS&merMobile=cb8e86fded5847a89405d28bae10b4cd&merName=排队美食10&merProvinceId=440000&merScope=就餐场所和餐馆(包括快餐)&merShortName=排队美食&merTownId=440305&merType=B&pnrNo=8610284486&receiveAddress=豪威科技大厦一楼排队美食&receiveEmail=f875c1c461782ca043b0355fd1b31822&receiveLinkMan=d7ecc34011e355d97ac04fcaa5ca1389&signMethod=RSA&timestamp=1571214971502&version=3.0.4&key=8610284486";
  26. var sign = Convert.ToBase64String(certificate2.GetRSAPrivateKey().SignData(Encoding.UTF8.GetBytes(value), HashAlgorithmName.SHA256,
  27. RSASignaturePadding.Pkcs1));
  28. var sign2 = RsaUtil.Sign(value, privateKey,signType:"RSA2");
  29. Assert.AreEqual(sign2,sign);
  30. }
  31. [TestMethod]
  32. public void SignTest()
  33. {
  34. string privateKey = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJRrRt9KG57PXf5GFtVPWZkX8ZNdAsEMRQJ8dI9/1fCgF6W98RDzFKN9U8m1cPJUQvsNH8EZ+x0FeCe6wiyNGwnUnUVctFcPp4WyqqwTi46jFxcnM5ESddHpriwW437xKf2MwXRoUh4qThvdEunGqzDg4iRPxlvAP29QojGmvfcJAgEDAoGAGLyLz+GvRSKPqmEDzjfkRC6oQzorICy2KxS+F+qjqBqum5+oLX3Yxeo4oZ49fbi11IIv9YRUhNY+sUnLB2zZ1rdoZy8l7exfpVPcH8HbjADoPWAHyAFNj7qoIVGkb6oBS3rN5Dq8sO8XT5PDhsLKwQ7ogYsf5FbyEKG+9hFHJlkCQQDZYVHaBc3mbvOfwMXnluX8M7YOM1GWyf77Zk1fBNeN3TIVH86FzKvKNGFqeN0INUCgCOP3eoyZDvu6nFEnf57/AkEArsmIZ8r1nvqyG8EnoM9goXHw2NGPc9p0jlcWzgQJZ0UGls5MghlMxY3c/ATkLbVp52Y3FYx1HYQPy4wcF5Nx9wJBAJDri+auiURJ97/V2UUPQ/13zrQiNmSGqfzu3j9Yj7PozA4VNFkzHTF4QPGl6LAjgGqwl/pRsxC0p9G9i2+qaf8CQHSGWu/co79RzBKAxRXflcD2oJCLtPfm+F7kud6tW5ouBGSJiFa7iIOz6KgDQskjm++Zeg5do2kCtTJdaA+3oU8CQQDBoYzu1nLR1ZE+MqqgWEPTnwCf6FN7oYG233+lts01ebiW5FXO8XMOPy6Iu83R0lKUjMF6U97+tfGwLJQQd1NI";
  35. var value = "amount=1&appid=wx2cfc213a5b6f76d8&body=测试商品&merchant_code=8886841641&nonce_str=182371781&notify_url=http://www.liushuqi123456.site/weixin/jhf/notify&openid=oNmgpxF3XJoVIFXBj5-i7HD36QKY&out_trade_no=20210220&pay_way=1";
  36. var sign = RsaUtil.Sign(value, privateKey);
  37. }
  38. [TestMethod]
  39. public void VerifyTest()
  40. {
  41. //string privateKey = string.Empty;
  42. //string publicKey = string.Empty;
  43. //RsaUtil.CreateKey(out privateKey, out publicKey);
  44. string privateKey = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIV9Wl4WV4tgaVqUOfpSbcdcpkoGxaiQRdPHtraN2B3NaCr5j+1SXuX+p9zRQlHBAC0+6X25FYyIb08MaOVc0gHSDQE8HndKfBKo4srkCEQ1ONtQCXZzKKGUYHXJviNjUzUsnTgQlJ/HqC+BiU12QaeRYZAROJXWBRBUTWBbsoDRAgMBAAECgYBarc+AUH8Br+mBXWWRFQN7xQU1DiqhGfhFJ8qHcg2YGRuk7ciGd0j9xaJ0DzaU4J1lHvJvtBXeVCQAt7Zd8FK7YoUOKIroyHLSJZwEMwM3ADOW0kxEDG8b+0Y/LSicV8+Ht5Vdjr0DXOUBRlF4UpAJrni+EpHwf1CNgGMR74gwbQJBAPWJnjxRW4nLaMrBq2z2oq7No5xOpgBXKsWJcviwEBJj699W62gKrSl2lfjRpbW3F9aiZcz96oFvuOvjtMMg6ksCQQCLLX1iWDmPexh3r5bKYKtj6c5FHY00ogtWX9l+A+3PVvfKOTvcaNYr5ck+LVIyus41u50vf8PfF4NkhbIXJQ/TAkBpBumxgVd3dJOpjvgFzuW9gebHGHk3UhHQlz+fkqf9RdKCIQrm4RI61yfFW9/W/69ptuN2sPIbVa+y7x7GDJFLAkBdrA9Aupp7HGFaZJ67tRaFl55R3FLmgs3Yo4hRjTlonGMIAz9r2E+VmgG5TG2PYTVa6twfVQGyzDON24ICm9orAkABpI+ZgSYQSzqBiNKKT788hZGY5QZvmg6kSDLf20qLRo86fICoeOGivCSMgT5rEcQTuUTn/QsHy0Fg4pZsbgmS";
  45. string publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFfVpeFleLYGlalDn6Um3HXKZKBsWokEXTx7a2jdgdzWgq+Y/tUl7l/qfc0UJRwQAtPul9uRWMiG9PDGjlXNIB0g0BPB53SnwSqOLK5AhENTjbUAl2cyihlGB1yb4jY1M1LJ04EJSfx6gvgYlNdkGnkWGQETiV1gUQVE1gW7KA0QIDAQAB";
  46. //var value = "address=豪威科技大厦一楼排队美食&agent_mer_no=8000100098271&bank_branch_name=招商银行总行营业部&bank_city=深圳市&bank_code=308584001024&bank_mer_name=凌晔&bank_name=招商银行&bank_province=广东&cert_type=2&city_no=440300&contact=凌晔&contact_phone=18620331255&district_no=440305&legal_idcard=430204198605194024&legal_idcard_back=f9d94fbcb4cd42ebb8bae7c2a1893273.jpg&legal_idcard_front=0581d34fd0b64388a86a0bb145e294ac.jpg&legal_name=凌晔&license_pic=83698a754f584a10a3b21aebbb3a7020.jpg&mer_type=2&merchant_name=排队美食10&merchant_sub_name=排队美食&product_info=[{\"channel_type\":\"UP_WX\",\"fee_exp\":\"0.0025\"},{\"channel_type\":\"UP_ALIPAY\",\"fee_exp\":\"0.0025\"}]&province_no=440000&request_id=2a249c6ed13548e8be6ac4233a2e1a19&service_phone=18620331255&service_type=xh.uni.merchant.reg&settle_card_no=6225880001401414&settle_type=1&shop_entrance_pic=49f3aac41bd24c90967709c36a3074cc.jpg&version=1.0";
  47. var value = "agent_mer_no=8000100098271&buyer_pay_amount=0.01&buyer_user_id=2088302018893091&channel_type=UP_ALIPAY&fund_bill_list=[{\"amount\":\"0.01\",\"fund_channel\":\"BANKCARD\"}]&merchant_no=8000105201870&out_trade_no=20191111140039&receipt_amount=0.01&rsp_code=0000&rsp_msg=支付成功&time_end=2019-11-11 14:00:44&total_fee=0.01&trx_external_id=10071193770509167366144&trx_status=SUCCESS&version=1.0";
  48. var sign = RsaUtil.Sign(value, privateKey, signType: "RSA2");
  49. var flag = RsaUtil.Verify(value, publicKey, sign, signType: "RSA2");
  50. Assert.AreEqual(true, flag);
  51. var sign1 = RsaUtil.SignWithMd5(value, privateKey, signType: "RSA2");
  52. var flag2 = RsaUtil.VerifyWithMd5(value, publicKey, sign1);
  53. }
  54. [TestMethod]
  55. public void EncryptTest()
  56. {
  57. //string privateKey = string.Empty;
  58. //string publicKey = string.Empty;
  59. //RsaUtil.CreateKey(out privateKey1,out publicKey1);
  60. string privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI/LhgrjSfyhVSQ6Xjfeoty7nWO7/+9/ppBqDwXyCoA2qNleIL9iptDn0wZOM//n81a3hwz8r059vml1gd8tVtIs4jtxByYgcJHbYcQ01iHSAoTzTX46sE/AxQmd9MpIhiXSnfNtrBx/rcBwZOaR0ypLnMqbzb+gV3TEL8OB25l3AgMBAAECgYBJ3wCpr0JfKnKW/fVRNmrsguXEStycqTNklVfKciG65Fmx8Y1ZRND2GWJrptlH6l00e2xB274j0K11eAyUHrKu16MR4Kb79M08uTu3ktSoHxRVPO3OK2My9t9y5baVec88oIboOx0M/lIY7xm1boCDuoVfqmKo618xaMKmFuHcQQJBANxOeCyuuiRk9NgriTLuyt7CEXOwzCkEVfv8zJcfB6Hfg5TsfTk1+jkEhlR49ovTZ+jRdTR7AZkSCfDxEnnpKa8CQQCnF6ENeIj4qQckDmle0ZIb0kl0s1S3qho8WqvhFETDBbjHsB4joeZVY33ssrF1e/x0bSc8a7+YMjB1uC0kO6a5AkBvL9tPEdA4VguMnkxcPFB/JIsSTIR9nwaWavwGuU5s0BXkr4ZzvV5QMIxrTbGA2G10/2Gb3wjrbENAKyscBCVZAkB0AZey/og5+0AV7FuDlQRXhHuzJf4fNV3ZoSnLroK+024iVUfXfUOo7NY0SyuhYV84hb/D1xrB07aJREEy8qchAkEAw3eiSON0FSdgRDl4b+EnJdUfWG77Amh5A6quWbx7LJ8E0QrDiM3qVKexoKPnCnRB1oGJgyy47rrhzmj05Dz4kg==";
  61. string publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPy4YK40n8oVUkOl433qLcu51ju//vf6aQag8F8gqANqjZXiC/YqbQ59MGTjP/5/NWt4cM/K9Ofb5pdYHfLVbSLOI7cQcmIHCR22HENNYh0gKE801+OrBPwMUJnfTKSIYl0p3zbawcf63AcGTmkdMqS5zKm82/oFd0xC/DgduZdwIDAQAB";
  62. var value = "asd";
  63. var encryptStr = RsaUtil.Encrypt(value, publicKey);
  64. var decryptStr = RsaUtil.Decrypt(encryptStr, privateKey);
  65. Assert.AreEqual(value, decryptStr);
  66. //var encryptStr1 = RsaUtil.Encrypt1(value, privateKey);
  67. //var decryptStr1 = RsaUtil.Decrypt1(encryptStr1, publicKey);
  68. var encryptStr1 = RsaUtil.EncryptByPrivateKey(value, privateKey);
  69. var decryptStr1 = RsaUtil.DecryptByPublicKey(encryptStr1, publicKey);
  70. Assert.AreEqual(value, decryptStr1);
  71. }
  72. [TestMethod]
  73. public void asd()
  74. {
  75. //var authUrl = $"FT_CORPID=FTC_PDW&FT_TILEID=05VMC5001&FT_SCENARIO=FTC_PDW05VMC5001001&SYS_TIME={DateTime.Now.ToString("yyyyMMdd HH:mm:ss")}";
  76. //var authUrl = $"FT_CORPID=FTC_PDW&FT_TILEID=05VMC5001&FT_SCENARIO=PDW&SYS_TIME={DateTime.Now.ToString("yyyyMMdd HH:mm:ss")}";
  77. ////var authUrl = "FT_CORPID=FTC_PDW&FT_TILEID=05VMC5001&FT_SCENARIO=PDW&SYS_TIME=20210224 16:07:31";
  78. //var key = @"30820154020100300d06092a864886f70d01010105000482013e3082013a020100024100cd01a8b61bb50f72c93ee175f15b3e53a516d7675b765a62749eadf0c157649f9657338c8981a4c91c5f61864e117503a7cd4313650ee854d3824a2bfb73f4830203010001024100b34d8829ff01d58927caff97108a2571332b4f2aef2c0cd19ffe4954114646925d3a11ee5d2f75c79174b6f16308d8d22898f59fb57abac8f645bbbc5c0d22c1022100e8c27a9724f89006355303fa9b513243fefc6cba5cbc937d8fb844bcc5a24c95022100e179c952140c16442ca1362e38c2ec5789c0cd85097d624b58291f9d566edeb702207e49768627330dc1b090f829b2b79d543336f62f2f3dc9b068980c03781f94f902201b01e5756965513d75431224533435eefe5713c6fdae011a194343c02adc38dd022032553430562ea8700e4df68a9a5654a57c6fed3c479de5399223f75f65bbd78d";
  79. //byte[] returnBytes = new byte[key.Length / 2];
  80. //for (int i = 0; i < returnBytes.Length; i++)
  81. //{
  82. // returnBytes[i] = Convert.ToByte(key.Substring(i * 2, 2), 16);
  83. //}
  84. //var privateKey = Convert.ToBase64String(returnBytes);
  85. //var sign = Sign(authUrl, privateKey);
  86. //authUrl += "&SIGN=" + sign;
  87. //var pubKey = "305c300d06092a864886f70d0101010500034b003048024100cd01a8b61bb50f72c93ee175f15b3e53a516d7675b765a62749eadf0c157649f9657338c8981a4c91c5f61864e117503a7cd4313650ee854d3824a2bfb73f4830203010001";
  88. //string ccbParam = HttpUtility.UrlEncode(AESEncrypt(authUrl, pubKey.Substring(pubKey.Length - 32)));
  89. //var sendUrl = "https://static.fcc.ccb.com/CCBIS/ReqCorpAccAuth?FT_CORPID=FTC_PDW&ccbParam=" + ccbParam;
  90. //var result = NetUtil.SendGetRequest(sendUrl);
  91. //var result =
  92. // "{\"SUCCEED\":\"true\",\"ACCESS_TOKEN\":\"WLul+HP3NMaCVd4pCOn1l7Wiw1FJeqiLbqA5TIdhO6hzhEJascNK8SZbX3Z9SeXT4Wl6CBdUXeOXXyva2YEkkO9p+2goDDGbNPAX9tg94Z/Sxh61fX2iGAsTXmvNqxnYUqCXTxC8HM1mD4Imc29mewjYz5ztIEsUvYu8ngYGlnOh83UXNDZc5jiL8AfsLNYWPX3ZFRqMJ68UjmWb5yBxX0xyvmfXbNOpSFvLc0Pdl5A4rrbZ5L/PxfcNBWHD3xe3iIiowJ8zVMsZhTsTFgST3g==\",\"COMMUNICATION_PWD\":\"Q8wvjh8tgrgNKXdGL2s/dNh9l6k42Rgp5mA46ub5TPgYVIsd0dtcIW71khq7L1d9qvsW6gPZ/rV2Kcnz+z+E59uGTOOrcAOXMn6lmJGa0do19VzHNQyasTteDJC/Fb4LHYU7wrBSuxUphm/qjV9b3ene2U4UHduwXgUqDCMZFnwa4Cec3/lgMxeq/qNZvkNEa20ZiN6gVn1HHwRu+7lfnpbMuYkM2p2wPq7ELCYCanj3X/cCL1myII9K0E6nXVqAPKbG2eaOLxhJ4iLHrwnzMHJNNZeBZrdS17sFgkreUrF2edKTIAXBEiadD5Bw0KuyTmK1/7hgDXr16PHcewcIQzAYs+inDANQ6ZJ9kINBpnU=\",\"ACC_ENTRY\":\"https://mapp.dcep.ccb.com/NCCB/MMER10FTMainPlat\",\"EXPIRATION_TIME\":\"2021-03-26 17:39:27\"}";
  93. //result = result.Replace("\'", "\"");
  94. //var dictionary = JsonUtil.JsonToDictionary(result);
  95. //var COMMUNICATION_PWD = dictionary["COMMUNICATION_PWD"];
  96. //var pubKey2 =
  97. // "305c300d06092a864886f70d0101010500034b003048024100a4e530b13157bb468582fbc6e3b88920c5999f1d5c4938bc4ecc9eb12cf57f433f1d3b3a7a053d8b7d45a79f613c61c2b664580b8c635eab63635e9443121c4d0203010001";
  98. //var com = AESDecrypt(COMMUNICATION_PWD, pubKey2.Substring(pubKey2.Length - 32));
  99. //var com1 = com.Substring(0, com.IndexOf("&SYS_TIME="));
  100. var authUrl = $"FT_CORPID=FTC_PDW&FT_TILEID=05VMC5001&FT_SCENARIO=FTC_PDW05VMC5001001&FT_ORDERNO={DateTime.Now.ToString("yyyyMMddHHmmss")}"
  101. + $"&CUSTOMERID=105000248166077&USERID=REF&PASSWORD=jhf123456"
  102. + $"&TXCODE=5W5004&LANGUAGE=CN"
  103. + $"&MONEY=0.01&ORDER=20210301150545" +
  104. $"&REFUND_CODE={DateTime.Now.ToString("yyyyMMddHHmmss")}&Mrch_No=105000248166077";
  105. var comkey = "LOMMOZiW6RojihZ0ZoE7lavuLr7PXe8J";
  106. string ccbParam = HttpUtility.UrlEncode(AESEncrypt(authUrl, comkey));
  107. var baseUrl = "https://mmerchant.ccb.com/NCCB/MMER00FTMainPlat";
  108. var ACCESS_TOKEN2 = "44yTKbCPoyLeE9l+wOeqJHQ7B3LSctjSqus+pJ+rFX4vo/k0XtWIOSR6irbYu4EYUTZqHcOKsOVNl562oVF858Tj10UAj4ZykxvvnlcBj36PT+SWW7YJQSZiApYg1uun4Cugpu+cQtvJ4X88PuKT4zj54I/CTzkD4poCjlgJLmBQhKvjOChACdOgdPptW0Bze3GUIWuVCTb0DujKyhTEScWnFV8XtWG3pWCyXs5OI7TED4gEuUWHicqlXtfyzrqsVjRJvsGvx+DlZ1c/Xnu205ubtLvQnLziJCeHabzaVR4=";
  109. var sendUrl = baseUrl + "?FT_CORPID=FTC_PDW&ccbParam=" + ccbParam + "&ACCESS_TOKEN=" + HttpUtility.UrlEncode(ACCESS_TOKEN2);
  110. var result = NetUtil.SendGetRequest(sendUrl);
  111. var com = AESDecrypt(result, comkey);
  112. }
  113. public static string AESEncrypt(string data, string key)
  114. {
  115. if (string.IsNullOrEmpty(data))
  116. {
  117. return string.Empty;
  118. }
  119. byte[] keyArray = null;
  120. using (var sha1 = new SHA1CryptoServiceProvider())
  121. {
  122. byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
  123. var rd = sha1.ComputeHash(hash);
  124. keyArray = rd.Take(16).ToArray();
  125. }
  126. byte[] plainText = System.Text.Encoding.UTF8.GetBytes(data);
  127. RijndaelManaged AesCipher = new RijndaelManaged();
  128. AesCipher.KeySize = 128;
  129. AesCipher.BlockSize = 128;
  130. AesCipher.Mode = CipherMode.ECB;
  131. AesCipher.Padding = PaddingMode.PKCS7;
  132. AesCipher.Key = keyArray;
  133. ICryptoTransform crypto = AesCipher.CreateEncryptor();
  134. byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
  135. var result = Encoding.UTF8.GetString(encode(cipherText));
  136. return result;
  137. }
  138. public static string AESDecrypt(string data, string key)
  139. {
  140. if (string.IsNullOrEmpty(data))
  141. {
  142. return string.Empty;
  143. }
  144. byte[] keyArray = null;
  145. using (var sha1 = new SHA1CryptoServiceProvider())
  146. {
  147. byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
  148. var rd = sha1.ComputeHash(hash);
  149. keyArray = rd.Take(16).ToArray();
  150. }
  151. byte[] plainText = decode(System.Text.Encoding.UTF8.GetBytes(data));
  152. RijndaelManaged AesCipher = new RijndaelManaged();
  153. AesCipher.KeySize = 128;
  154. AesCipher.BlockSize = 128;
  155. AesCipher.Mode = CipherMode.ECB;
  156. AesCipher.Padding = PaddingMode.PKCS7;
  157. AesCipher.Key = keyArray;
  158. ICryptoTransform crypto = AesCipher.CreateDecryptor();
  159. byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
  160. var result = Encoding.UTF8.GetString(cipherText);
  161. return result;
  162. }
  163. public string Sign(string data, string privateKey, string charset = "utf-8", string signType = "RSA")
  164. {
  165. RSACryptoServiceProvider rsaCsp = RsaUtil.DecodePrivateKeyInfo(privateKey, signType);
  166. byte[] dataBytes = null;
  167. if (string.IsNullOrEmpty(charset))
  168. {
  169. dataBytes = Encoding.UTF8.GetBytes(data);
  170. }
  171. else
  172. {
  173. dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
  174. }
  175. HashAlgorithm hash = new SHA1CryptoServiceProvider();
  176. if ("RSA2".Equals(signType))
  177. {
  178. hash = new SHA256CryptoServiceProvider();
  179. }
  180. byte[] signatureBytes = rsaCsp.SignData(dataBytes, hash);
  181. var result = bytesToHexStr(encode(signatureBytes));
  182. return result;
  183. return Convert.ToBase64String(signatureBytes);
  184. }
  185. private static byte[] DECODE_TABLE = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56,
  187. 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  188. 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  189. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0 };
  190. private static byte[] ENCODE_TABLE = new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  191. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  192. 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43,
  193. 47 };
  194. private static char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  195. public static byte[] encode(byte[] data)
  196. {
  197. if (data == null)
  198. return null;
  199. int fullGroups = data.Length / 3;
  200. int resultBytes = fullGroups * 4;
  201. if (data.Length % 3 != 0)
  202. resultBytes += 4;
  203. byte[] result = new byte[resultBytes];
  204. int resultIndex = 0;
  205. int dataIndex = 0;
  206. int temp = 0;
  207. for (int i = 0; i < fullGroups; i++)
  208. {
  209. temp = (data[dataIndex++] & 0xff) << 16 | (data[dataIndex++] & 0xff) << 8 | data[dataIndex++] & 0xff;
  210. result[resultIndex++] = ENCODE_TABLE[(temp >> 18) & 0x3f];
  211. result[resultIndex++] = ENCODE_TABLE[(temp >> 12) & 0x3f];
  212. result[resultIndex++] = ENCODE_TABLE[(temp >> 6) & 0x3f];
  213. result[resultIndex++] = ENCODE_TABLE[temp & 0x3f];
  214. }
  215. temp = 0;
  216. while (dataIndex < data.Length)
  217. {
  218. temp <<= 8;
  219. temp |= data[dataIndex++] & 0xff;
  220. }
  221. switch (data.Length % 3)
  222. {
  223. case 1:
  224. temp <<= 8;
  225. temp <<= 8;
  226. result[resultIndex++] = ENCODE_TABLE[(temp >> 18) & 0x3f];
  227. result[resultIndex++] = ENCODE_TABLE[(temp >> 12) & 0x3f];
  228. result[resultIndex++] = 0x3D;
  229. result[resultIndex++] = 0x3D;
  230. break;
  231. case 2:
  232. temp <<= 8;
  233. result[resultIndex++] = ENCODE_TABLE[(temp >> 18) & 0x3f];
  234. result[resultIndex++] = ENCODE_TABLE[(temp >> 12) & 0x3f];
  235. result[resultIndex++] = ENCODE_TABLE[(temp >> 6) & 0x3f];
  236. result[resultIndex++] = 0x3D;
  237. break;
  238. default:
  239. break;
  240. }
  241. return result;
  242. }
  243. public static byte[] decode(byte[] base64Data)
  244. {
  245. if (base64Data == null)
  246. return null;
  247. if (base64Data.Length == 0)
  248. return new byte[0];
  249. if (base64Data.Length % 4 != 0)
  250. throw new ArgumentException("数据不完整,长度为: " + base64Data.Length);
  251. byte[] result = null;
  252. int groupCount = base64Data.Length / 4;
  253. int lastData = base64Data.Length;
  254. while (base64Data[lastData - 1] == 0x3D)
  255. {
  256. if (--lastData == 0)
  257. return new byte[0];
  258. }
  259. result = new byte[lastData - groupCount];
  260. int temp = 0;
  261. int resultIndex = 0;
  262. int dataIndex = 0;
  263. for (; dataIndex + 4 < base64Data.Length;)
  264. {
  265. temp = DECODE_TABLE[base64Data[dataIndex++]];
  266. temp = (temp << 6) + DECODE_TABLE[base64Data[dataIndex++]];
  267. temp = (temp << 6) + DECODE_TABLE[base64Data[dataIndex++]];
  268. temp = (temp << 6) + DECODE_TABLE[base64Data[dataIndex++]];
  269. result[resultIndex++] = (byte)((temp >> 16) & 0xff);
  270. result[resultIndex++] = (byte)((temp >> 8) & 0xff);
  271. result[resultIndex++] = (byte)(temp & 0xff);
  272. }
  273. temp = 0;
  274. int j = 0;
  275. for (; dataIndex < base64Data.Length; dataIndex++, j++)
  276. temp = (temp << 6) + DECODE_TABLE[base64Data[dataIndex]];
  277. for (; j < 4; j++)
  278. temp <<= 6;
  279. result[resultIndex++] = (byte)((temp >> 16) & 0xff);
  280. if (base64Data[dataIndex - 2] != '=')
  281. result[resultIndex++] = (byte)((temp >> 8) & 0xff);
  282. if (base64Data[dataIndex - 1] != '=')
  283. result[resultIndex++] = (byte)(temp & 0xff);
  284. return result;
  285. }
  286. public static string bytesToHexStr(byte[] paramArrayOfByte)
  287. {
  288. StringBuilder localStringBuffer = new StringBuilder(paramArrayOfByte.Length * 2);
  289. for (int i = 0; i < paramArrayOfByte.Length; i++)
  290. {
  291. localStringBuffer.Append(bcdLookup[(paramArrayOfByte[i] >> 4 & 0xF)]);
  292. localStringBuffer.Append(bcdLookup[(paramArrayOfByte[i] & 0xF)]);
  293. }
  294. return localStringBuffer.ToString();
  295. }
  296. }
  297. }