在路上

 

C#RSA加密解密详解

    //需要添加BouncyCastle引用
    public class RSAEncryptAndDecrypt
    {
        public static bool Login()
        {
            try
            {
                string userpwd = "a123456";
                string publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCicdRcD669oTrlnnqQL6GD8pbnMjgOW2zUAA2qvRn+IQ7QtkPtCYzbdxSEomg8M49zMYZLb3547IPTAmBJw3PDgHiSFgHSWDq851N8eQgi6vWuDI+X+/1nxJ84rlM2c0GGOU761GQDll1vUxuFEORpJg6/MCyluBOEfkvLcMN5YwIDAQAB";
                string privatekey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKJx1FwPrr2hOuWeepAvoYPylucyOA5bbNQADaq9Gf4hDtC2Q+0JjNt3FISiaDwzj3Mxhktvfnjsg9MCYEnDc8OAeJIWAdJYOrznU3x5CCLq9a4Mj5f7/WfEnziuUzZzQYY5TvrUZAOWXW9TG4UQ5GkmDr8wLKW4E4R+S8tww3ljAgMBAAECgYEAhuB6kWHYFc1cCLF4VGWn9tWipB4XWxxgFPpiXqSag13RXkwnxBWM5eBOof3zDCFHdz7koZfWa/L9VWOArV5iq9J86okA7KEPygO9Jkk582JKKDD7TQsxxPvnaYAonGPXmrVBg3RGHxsVGXj9KLuLsDUdzHOUADyZbPyBHkeuB/kCQQD//498ZgeWy/x8Bqc2hS5vs1hvksAWNkEexmO253J8BZdffcM5MCsFu3/lWvFcBKaoNdv10IrNr97evICBW3v9AkEAonIbwX3rbJ8AYojjD7EGLdLlCCfirs94+F963JEQyOh4mNiMXqlFRw58ey5NpuZDO8VzRqCRL5+eRml82NnY3wJANIq0XXjnd9jYMnB/I16EYGKz9PpuuGBcTz+yuZiZU8EmB3BdgEBVpDCOmHlo7lT6C646PiKWSo8dNCQGUAaB1QJAE79pbmE/YGoH4vKfH8Y2aRWtMAuhO/0OyKraxbuA3duc5X/VuKA9QsEZEuRzHin53GdJdzmHzNFLrWWffsEk4wJBAPcsbafg740NKy7duPHtZJCA9/WI1nWHrkLR1DZqrl7eSXXCN5XQvpB4Q+38WgvLogmQ2+4AqrT5/VAaesPd8YU=";
                string publickey2xml = RSAPublicKey2xml(publickey);                 //公钥转换成xml格式
                string xml2publickey = RSAxml2PublicKey(publickey2xml);             //xml格式转换为公钥
                string password = Encrypt(userpwd, publickey2xml);                  //公钥加密
                string privatekey2xml = RSAPrivateKey2xml(privatekey);              //公钥转换成xml格式
                string xml2privatekey = RSAxml2PrivateKey(privatekey2xml);          //xml格式转换成公钥
                string upwd = Decrypt(password, privatekey2xml);                    //私钥解密
                return userpwd == upwd;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        static string RSAPublicKey2xml(string publicKey)
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
        }

        static string RSAxml2PublicKey(string publickey2xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(publickey2xml);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPublicBytes);
        }

        static string Encrypt(string content, string key)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(key);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }

        static string RSAPrivateKey2xml(string privateKey)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
        }

        static string RSAxml2PrivateKey(string privatekey2xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(privatekey2xml);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }

        static string Decrypt(string content, string key)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(key);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

    }

 

posted on 2021-04-04 09:46  hsliuyl  阅读(601)  评论(0编辑  收藏  举报

导航