using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace RuralPower { public static class RSAHelper { private static string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2TEstfATFdDWntbJTCPer9FOdwTRe58Vjy9T238/uUQYyoTHClfQCCKnys4elHCE0D0B7D/k2hK9U+xu1hWv1v4lH+n+t5duNVGq3sa5+pOq8j1ztec3W+wlcFgplYJq78XBYGYDbyfhmu5KeDeImsiccwnq3WvigfZYPbTvGv2YsqXDpTp+/s0hQsrYeATr2MuhiBhQGynLUvKCEcWvd/GNByMxJdJwl0k+IZW+DiCDmNX9Qwj23HF7U+Om7jEZC+Li/j2MHA5C4eEtVzgVC4VZETVOIcLv/UDufnAlneTJK2Exo+4YFEg9S1shpqUz9shSBl8JF9DM2a3KKmxc4wIDAQAB"; // 加密数据 public static string EncryptData(string content) { var public_key = ToXmlPublicKey(publicKey); var data = Encoding.UTF8.GetBytes(content); string encryptedContent = string.Empty; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(public_key); byte[] encryptedData = rsa.Encrypt(data, false); encryptedContent = Convert.ToBase64String(encryptedData); } return encryptedContent; } /// /// base64 private key string -> xml private key /// /// /// public static string ToXmlPrivateKey(string privateKey) { RsaPrivateCrtKeyParameters privateKeyParams = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)) as RsaPrivateCrtKeyParameters; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { RSAParameters rsaParams = new RSAParameters() { Modulus = privateKeyParams.Modulus.ToByteArrayUnsigned(), Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(), D = privateKeyParams.Exponent.ToByteArrayUnsigned(), DP = privateKeyParams.DP.ToByteArrayUnsigned(), DQ = privateKeyParams.DQ.ToByteArrayUnsigned(), P = privateKeyParams.P.ToByteArrayUnsigned(), Q = privateKeyParams.Q.ToByteArrayUnsigned(), InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned() }; rsa.ImportParameters(rsaParams); return rsa.ToXmlString(true); } } /// /// base64 public key string -> xml public key /// /// /// public static string ToXmlPublicKey(string pubilcKey) { RsaKeyParameters p = PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { RSAParameters rsaParams = new RSAParameters { Modulus = p.Modulus.ToByteArrayUnsigned(), Exponent = p.Exponent.ToByteArrayUnsigned() }; rsa.ImportParameters(rsaParams); return rsa.ToXmlString(false); } } } }