首页 > 编程语言 >c# mvc+RSA 加密

c# mvc+RSA 加密

时间:2023-09-14 17:14:45浏览次数:51  
标签:Convert BouncyCastle string c# BigInteger RSA mvc Org Math

密钥生成:http://web.chacuo.net/netrsakeypair

生成一套 密钥 

前端引用 

<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.3.2/jsencrypt.min.js"></script>

  function EncryptLogin() {
        var publicKey = "";
        var encryptionMessage = RsaEncrypt(publicKey, $('#username').val() + "_" + $('#password').val() + "_" + $('#num').val());
            //console.log(encryptionMessage);
        $('#messageLabel').html('');
        var index_wait = layer.load(1, { shade: [0.2, '#000'] });
        $.ajax({
            type: "POST", //提交方式
            url: "@Url.Action("EncryptLogin", "Account")",
            data: {
                "encryptionMessage": encryptionMessage,
            },
            success: function (data) {
                layer.close(index_wait);
                if (data.StatusCode === 200) {
                    var domain = 'https://' + window.location.host;
                    window.location.href = domain + '/home/index';
                    //layer.alert(data.Message);
                } else {
                    //layer.alert("登录失败,请重试!");
                    $('#messageLabel').html(data.Message);
                }
            }
        });
    }
 function RsaEncrypt(publickey, encrypt_content) {
            var encryptpk = new JSEncrypt();
            encryptpk.setPublicKey(publickey);
            let result = encryptpk.encrypt(encrypt_content)
            //console.log("RsaEncrypt:", result)
            return result;
        }

后端

  var privatekey = “”;
 var decrypt = SecurityRSA.RsaDecrypt(privatekey, encryptionMessage);
            if (string.IsNullOrEmpty(decrypt))
            {
                result.Message = "登录请求异常";
            }
            else
            {
                string[] sArray = decrypt.Split('_');
                if (sArray.Length == 3)
                {
                    username = sArray[0];
                    password= sArray[1];
                    num = sArray[2];
                }
            }
//根据获得信息 判断账户密码 是否有效 验证码是否有效 可以在添加一个时间戳

引用NuGet--- BouncyCastle 

帮助类

  public class SecurityRSA
    {
        /// <summary>
        /// RSA 加密
        /// </summary>
        /// <param name="xmlpublickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RsaEncrypt(string xmlpublickey, string content)
        {
            string encryptedcontent = string.Empty;
            using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
            {
                rSACryptoServiceProvider.FromXmlString(RSAPublicKeyBase64ToXml(xmlpublickey));
                byte[] encrypteddata = rSACryptoServiceProvider.Encrypt(Encoding.Default.GetBytes(content), false);
                encryptedcontent = Convert.ToBase64String(encrypteddata);
            }
            return encryptedcontent;
        }
        /// <summary>
        /// RSA 解密
        /// </summary>
        /// <param name="xmlprivatekey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RsaDecrypt(string xmlprivatekey, string content)
        {
            string decryptedcontent = string.Empty;
            using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
            {
                rSACryptoServiceProvider.FromXmlString(RSAPrivateKeyBase64ToXml(xmlprivatekey));
                byte[] decryptedData = rSACryptoServiceProvider.Decrypt(Convert.FromBase64String(content), false);
                decryptedcontent = Encoding.GetEncoding("UTF-8").GetString(decryptedData);
            }
            return decryptedcontent;
        }
        /// <summary>
        /// 生成 RSA 公钥和私钥
        /// </summary>
        /// <param name="keysize">目前 SET(Secure Electronic Transaction)协议中要求 CA 采用 2048bits 长的密钥,其他实体使用 1024bits 的密钥</param>
        /// <returns></returns>
        public static RsaSecretKey GenerateRsaSecretKey(int keysize)
        {
            RsaSecretKey rSASecretKey = new RsaSecretKey();
            using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(keysize))
            {
                rSASecretKey.PrivateKey = RSAPrivateKeyXmlToBase64(rSACryptoServiceProvider.ToXmlString(true));
                rSASecretKey.PublicKey = RSAPublicKeyXmlToBase64(rSACryptoServiceProvider.ToXmlString(false));
            }
            return rSASecretKey;
        }
        /// <summary>
        /// XML 字符串转 Base64 编码的字符串(公钥)
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string RSAPublicKeyXmlToBase64(string publicKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(publicKey);
            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
            Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPublicBytes);
        }
        /// <summary>
        /// XML 字符串转 Base64 编码的字符串(私钥)
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string RSAPrivateKeyXmlToBase64(string privateKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(privateKey);
            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger exp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger q = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger dp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger dq = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            Org.BouncyCastle.Math.BigInteger qinv = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
            Org.BouncyCastle.Asn1.Pkcs.PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }
        /// <summary>
        /// Base64 编码字符串转 XML 字符串(私钥)
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string RSAPrivateKeyBase64ToXml(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()));
        }
        /// <summary>
        /// Base64 编码字符串转 XML 字符串(公钥)
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static string RSAPublicKeyBase64ToXml(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()));
        }
    }
    /// <summary>
    /// RSA 密钥类
    /// </summary>
    public class RsaSecretKey
    {
        public RsaSecretKey(string privatekey = "", string publickey = "")
        {
            PrivateKey = privatekey;
            PublicKey = publickey;
        }
        public string PublicKey { get; set; }
        public string PrivateKey { get; set; }
        public override string ToString()
        {
            return string.Format(
                "PrivateKey: {0}\r\nPublicKey: {1}", PrivateKey, PublicKey);
        }
    }

 

标签:Convert,BouncyCastle,string,c#,BigInteger,RSA,mvc,Org,Math
From: https://www.cnblogs.com/daboluo/p/17702905.html

相关文章

  • Java集成开发环境(IDE)-IntelliJ IDEA 2023 mac+win版
    IntelliJIDEA是一款由JetBrains开发的集成开发环境(IDE),用于Java、Kotlin和其他编程语言的开发。它是一款功能强大、灵活且易于使用的IDE,被广泛认为是Java开发的首选工具之一。→→↓↓载IntelliJIDEA2023mac/win版 首先,IntelliJIDEA2023引入了更强大的代码分析和智能提......
  • MAC 上 brew update 更换源
    //替换brew-git$cd"$(brew--repo)"$gitremoteset-urloriginhttps://mirrors.ustc.edu.cn/brew.git//替换homebrew-core.git$cd"$(brew--repo)/Library/Taps/homebrew/homebrew-core"$gitremoteset-urloriginhttps://mirrors.ustc.edu.cn/hom......
  • iPad缺席2023秋季发布会,新品或许再等一年?考虑提升iPad生产力,安装Cpolar成为不二之选
    iPad缺席2023秋季发布会,新品或许再等一年?考虑提升iPad生产力,安装Cpolar成为不二之选随着iPad在我们的生活和工作中扮演着越来越重要的角色,我们都迫不及待地期待每一次的新品发布会上都能看到它的身影。然而,刚刚结束的2023苹果秋季发布会上并没有看到新款Ipad的出现,这真的很令人失......
  • 软件测评中心测试项目及测试过程简析,CMA、CNAS软件测试报告获取
    软件测试是产品周期中必不可少的一步,可以更好的保障软件质量,那么我们所知的软件测评中心一般有哪些测试项目以及测试流程是如何?和小编一起往下看看吧!一、软件测评中心的测试项目1、功能测试:通过模拟用户使用场景,测试软件的各项功能是否正常、稳定。2、性能测试:通......
  • CentOS6.4邮件配置一: postfix + dovecot + mysql + postfixadmin + Roundcubemail
    参考文章:----------------------------[size=large][color=red]可以考虑:[/color][/size]Posty——Postfix和Dovecot的管理工具[url][/url]Posty是一款基于Web的Postfix&Dovecot管理工具,功能模块包括:API、CLI和WebUI。基于Centos6.2X64系......
  • 更改Eclipse下Tomcat的部署目录和自定义user library
     更改Eclipse下Tomcat的部署目录http://kingxss.iteye.com/blog/1741438自定义userlibrary......
  • nacos和Euraka的对比
       ......
  • vscode中同一页面使用批量替换
    在vscode中像word中那样批量替换首先搜索要替换的内容快捷键是ctrl+f然后输入你要搜索的内容  第二个框中输入你要替换成的内容点击全部替换,就可以了......
  • AGC058 F Authentic Tree DP
    一道问号题,AT赛场上没人通过。其实是联考题这道题十分有意思,做法很简单但是要想到是极其困难的。考场上我也拿着推了很久猜测这个式子的组合意义,擦到了正解的一些边。然而正解的思想还是太反直觉了。首先题目中的式子实际上是让我们对树上的边建一颗笛卡尔树,然后计算笛卡尔树所......
  • Laravel 执行流程(三)之 探索 Application 构造函数
    备注:纯手打的学习笔记,如有错误之处请指正,谢谢。希望大家学的开心!说明:本来应该是说Container类(下)的,不过经过学习,直接看这个类实在不好理解,一会是绑定,一会共享实例,真心不知道说的什么....还是先从程序的入口处,顺藤摸瓜,用到的时候再结合上下文理解,比较容易消化,希望理解,抱歉!OK,从入......