using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography; namespace Kad.ThridParty.ChinaPayWap { /// /// 非对称RSA加解密,私钥加密/公钥解密 /// 仅用于银联Wap支付报文收发 /// By : EnVon(E旺) 2013-08-20 /// internal class RSAHelper { /// /// RSA加密(用私钥加密哟) /// /// 私钥 /// 待加密的数据 /// public static byte[] Encrypt(String key, byte[] data) { //由密钥xml取得RSA对象 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(key); //取得加密时使用的2个参数 RSAParameters par = rsa.ExportParameters(true); BigInteger mod = new BigInteger(par.Modulus); BigInteger ep = new BigInteger(par.D); //计算填充长度 int mLen = par.Modulus.Length; int fLen = mLen - data.Length - 3; //组建bytes List lis = new List(); lis.Add(0x00); lis.Add(0x01);//兼容java for (int i = 0; i < fLen; i++) lis.Add(0xff); lis.Add(0x00); lis.AddRange(data); byte[] bytes = lis.ToArray(); //加密就这么简单? BigInteger m = new BigInteger(bytes); BigInteger c = m.modPow(ep, mod); return c.getBytes(); } /// /// RSA解密(用公钥解密哟) /// /// 公钥 /// 待解密的数据 /// public static byte[] Decrypt(String key, byte[] data) { //由密钥xml取得RSA对象 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(key); //取得解密时使用的2个参数 RSAParameters par = rsa.ExportParameters(false); BigInteger mod = new BigInteger(par.Modulus); BigInteger ep = new BigInteger(par.Exponent); //解密? BigInteger m = new BigInteger(data); BigInteger c = m.modPow(ep, mod); byte[] bytes = c.getBytes(); //去掉填充域(头部可能填充了一段0xff) byte flag = 0; for (int i = 1/*我从1开始啦*/; i < bytes.Length; i++) { if (bytes[i] == flag && i != (bytes.Length - 1)) { byte[] retBytes = new byte[bytes.Length - i - 1]; Array.Copy(bytes, i + 1, retBytes, 0, retBytes.Length); return retBytes; } } return bytes; } /// /// 取得证书私钥 /// /// 证书的绝对路径 /// 访问证书的密码 /// public static String GetPrivateKey(string pfxPath, string password) { X509Certificate2 pfx = new X509Certificate2(pfxPath, password, X509KeyStorageFlags.Exportable); string privateKey = pfx.PrivateKey.ToXmlString(true); return privateKey; } /// /// 取得证书的公钥 /// /// 证书的绝对路径 /// public static String GetPublicKey(string cerPath) { X509Certificate2 cer = new X509Certificate2(cerPath); string publicKey = cer.PublicKey.Key.ToXmlString(false); return publicKey; } } }