RSA签名和验证数据
1 private const string PubKey = "BgIAAACkAABSU0ExAAQAAAEAAQAxg/L6l3AyA+Zd7Hm7ESCcS4CcgY8PvwE2arRvTbfI4+z6zPJaDkOyho9X6owIwceN9zXH5XNsAmEVYBkgmwdX5r5g8iymKywYSaVpt1FDUHRkGY39NuDVsbVJ/1DW15TTVeYLalbtOOb0h61pnaW9FgQNaYMMZSWPO8UZ9hPepw=="; 2 3 private const string PriKey = "BwIAAACkAABSU0EyAAQAAAEAAQAxg/L6l3AyA+Zd7Hm7ESCcS4CcgY8PvwE2arRvTbfI4+z6zPJaDkOyho9X6owIwceN9zXH5XNsAmEVYBkgmwdX5r5g8iymKywYSaVpt1FDUHRkGY39NuDVsbVJ/1DW15TTVeYLalbtOOb0h61pnaW9FgQNaYMMZSWPO8UZ9hPep+flgoHIqqmP8wwg4XY1KWHUXequmSryPkIpgcSs9EEVGZbxI8ai8i+OlpNH/1a6lmjyQzMzIK1sJ/5WubRFjMon+6iPki2vxviqxQeODX/yNRPglWsTLjzPiVxrPaNan++rAKWBBodsspaU+MZyYt4QT/AXzTi62OB2srB23SrUc89OqR9T7fhnFkfj/AymDqgEEI2JliQPGttj9ycx2e/bCllPISn5BP3Vcq6slUMk05YM/4+BVB/goTCrdXsbJAEoCtGAfkRBzldhHFtw5/vd49anfedXLFQcpkfGJbMVaO9deS6HyMBZ+XqS/6zxUJL2m3n6gKL5bgoCtqqdSYGAR4Hdrt0lWTfnscXauHDZ12FdzSp3egTDSROmEXHoogNhibz3Q0t6nNpwcoBjxCwZnz2Ej1hW84UpTnYN8ixAQbksoAprGCshxUo7x6NAXx/FaO8vxrwPliI8pAcDOJ3Z/JUKhfquRjINsg4DYTxxhEtpynBznRhrKpyifggiRvqeBITpcLpgP83dhEdz8Bf18MJw7lX9usEiX5XighQ0iABVtxTu7dBgIHWNTH6gVUWqe87yguFrfj4OA++CBYM="; 4 static void Main(string[] args) 5 { 6 var aa = "123456"; 7 var e = SignData(aa,PriKey); 8 var dd = VerifySerialNum(aa, e, PubKey); 9 } 10 11 /// <summary> 12 /// RSA签名数据 13 /// </summary> 14 /// <param name="input">要签名的数据</param> 15 /// <param name="priKey">base64编码的私钥</param> 16 /// <returns>签名后数据的base64字符串</returns> 17 public static string SignData(string input,string priKey) 18 { 19 try 20 { 21 using (var rsa = new RSACryptoServiceProvider(1024)) 22 { 23 rsa.ImportCspBlob(Convert.FromBase64String(priKey)); 24 var data = Encoding.UTF8.GetBytes(input); 25 return Convert.ToBase64String(rsa.SignData(data, new SHA1CryptoServiceProvider())); 26 } 27 } 28 catch (Exception) 29 { 30 return string.Empty; 31 } 32 } 33 34 /// <summary> 35 /// 验证数据 36 /// </summary> 37 /// <param name="input">签名前数据</param> 38 /// <param name="serialNum">SHA1签名后数据base64编码字符串</param> 39 /// <param name="pubKey">base64编码的公钥</param> 40 /// <returns></returns> 41 public static bool VerifySerialNum(string input, string serialNum, string pubKey) 42 { 43 try 44 { 45 //导入公钥 46 using (var rsa = new RSACryptoServiceProvider(1024)) 47 { 48 rsa.ImportCspBlob(Convert.FromBase64String(pubKey)); 49 return rsa.VerifyData(Encoding.UTF8.GetBytes(input), new SHA1CryptoServiceProvider(), 50 Convert.FromBase64String(serialNum)); 51 } 52 } 53 catch (Exception) 54 { 55 return false; 56 } 57 }