zoukankan      html  css  js  c++  java
  • C#中RSA加密解密和签名与验证的实现

    RSA加密算法是一种非对称加密算法。在公钥加密标准和电子商业中RSA被广泛使用。RSA是1977年由罗纳德•李维斯特(Ron Rivest)、阿 迪•萨莫尔(Adi Shamir)和伦纳德•阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们 三人姓氏开头字母拼在一起组成的。.Net的推出,我们能够利用.Net Framework中的类提供的加密服务来保证数据安全。目前应用较为广泛的加 密方法是使用RSA算法进行加密。在.Net Framework中与RSA加密算法相关的类主要有两个:RSA 类和 RSACryptoServiceProvider 类。按照MSDN的说法RSA 类是“表示 RSA 算法的所有实现均从中继承的基类”,而 RSACryptoServiceProvider 类是“使用加密服务提供程序 (CSP) 提供的 RSA 算法的实现执行不对称加密和解密”。另 外,“表示 RSA 算法的标准参数”的RSAParameters 结构也是很重要的,它保存了RSA算法的参数。
    这里具体讲述一下在C#中如何使用框架提供的RSA算法来对我们的信息加密、签名、验证签名、解密的这个几个步骤的实现

      class Program
        {
            static void Main()
            {
                try
                {
                    //string str_DataToSign = @"Data to Sign!Data to Sign!Data to Sign!";
                    //Console.WriteLine("原文:" + str_DataToSign);
                    //Console.WriteLine("长度:" + str_DataToSign.Length.ToString());
                    //Console.WriteLine();

                    string filePath = @"C:md5main.js";
                    string str_DataToSign = GetFileMD5(filePath);
                    Console.WriteLine(str_DataToSign);
                    //WriteDateToFile(@"C:md5md5.txt", str_DataToSign);


                    RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

                    string str_Private_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(true));
                    string str_Public_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(false));
                    Console.WriteLine("公钥:" + str_Public_Key);
                    //WriteDateToFile(@"C:md5public.txt",str_Public_Key);
                    Console.WriteLine();
                    Console.WriteLine("私钥:" + str_Private_Key);
                    //WriteDateToFile(@"C:md5private.txt", str_Private_Key);
                    Console.WriteLine();

                    string str_SignedData = HashAndSign(str_DataToSign, str_Private_Key);// Hash and sign the data.
                    Console.WriteLine("签名数据:" + str_SignedData);
                    //WriteDateToFile(@"C:md5sign.txt", str_SignedData);
                    Console.WriteLine();

                    if (VerifySignedHash(str_DataToSign, str_SignedData, str_Public_Key))
                    {
                        Console.WriteLine("验证签名OK.");
                    }
                    else
                    {
                        Console.WriteLine("签名不匹配!");
                    }
                    Console.ReadKey();
                }
                catch (ArgumentNullException)
                {
                    Console.WriteLine("The data was not signed or verified");
                }
            }

            //对数据签名
            public static string HashAndSign(string str_DataToSign, string str_Private_Key)
            {
                ASCIIEncoding ByteConverter = new ASCIIEncoding();
                byte[] DataToSign = ByteConverter.GetBytes(str_DataToSign);
                try
                {
                    RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
                    RSAalg.ImportCspBlob(Convert.FromBase64String(str_Private_Key));
                    byte[] signedData = RSAalg.SignData(DataToSign, new SHA1CryptoServiceProvider());
                    string str_SignedData = Convert.ToBase64String(signedData);
                    return str_SignedData;
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return null;
                }
            }

            //验证签名
            public static bool VerifySignedHash(string str_DataToVerify, string str_SignedData, string str_Public_Key)
            {
                byte[] SignedData = Convert.FromBase64String(str_SignedData);

                ASCIIEncoding ByteConverter = new ASCIIEncoding();
                byte[] DataToVerify = ByteConverter.GetBytes(str_DataToVerify);
                try
                {
                    RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
                    RSAalg.ImportCspBlob(Convert.FromBase64String(str_Public_Key));

                    return RSAalg.VerifyData(DataToVerify, new SHA1CryptoServiceProvider(), SignedData);

                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);

                    return false;
                }
            }

            /// <summary>
            /// 对文件进行MD5加密
            /// </summary>
            /// <param name="filepath">文件路径</param>
            /// <returns></returns>
            public static string GetFileMD5(string filepath)
            {
                StringBuilder sb = new StringBuilder();
                using (MD5 md5 = MD5.Create())
                {
                    using (FileStream fs = File.OpenRead(filepath))
                    {
                        byte[] newB = md5.ComputeHash(fs);
                        foreach (byte item in newB)
                        {
                            sb.Append(item.ToString("x2"));
                        }
                    }
                }

                return sb.ToString();
            }

            /// <summary>
            /// 写文件操作
            /// </summary>
            /// <param name="filePath"></param>
            /// <param name="content"></param>
            public static void WriteDateToFile(string filePath, string content)
            {
                using (StreamWriter sw = new StreamWriter(File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None)))
                {
                    //写入文件  
                    sw.WriteLine(content);
                    sw.Flush();
                }
            }
        }

     相关代码

  • 相关阅读:
    [导入]【翻译】WF从入门到精通(第十三章):打造自定义活动
    [导入]关于网页标准与JAVAScript执行的问题
    html包含html文件的方法
    [导入]C#加密方法汇总
    8、步步为营VS 2008 + .NET 3.5(8) DLINQ(LINQ to SQL)之面向对象的添加、查询、更新和删除
    [导入]【翻译】WF从入门到精通(第十五章):工作流和事务
    [导入]存储过程得到某个表的所有字段信息
    1、步步为营VS 2008 + .NET 3.5(1) VS 2008新特性之Multi Targeting(多定向)、Web Designer and CSS(集成了CSS的web设计器)和Nested Master Page(嵌套母版页)
    [导入]vbs修改注册表
    正则表达式30分钟入门教程
  • 原文地址:https://www.cnblogs.com/lidj/p/5220722.html
Copyright © 2011-2022 走看看