田草博客

互联网田草博客


网友交流QQ群:11740834 需注明申请加入原因

微信 公众号:ByCAD

邮箱:tiancao1001x126.com
ByCAD,微信公众号
首页 | 普通 | 电脑 | AutoCAD | VB/VB.NET | FLash | 结构 | 建筑 | 电影 | BIM | 规范 | 软件 | ID
-随机-|-分布-
-博客论坛-|-﨣﨤﨧﨨-
-网站导航-|-规范下载-
-BelovedFLash欣赏-

用户登陆
用户:
密码:
 

站点日历
73 2024 - 3 48
     12
3456789
10111213141516
17181920212223
24252627282930
31


站点统计

最新评论



win7 搜索功能不能使用的解决办法 word的锁定与解锁
未知 MD5 加密、解密、数字签名及验证   [ 日期:2017-05-08 ]   [ 来自:转帖 ]  HTML
转帖http://www.cnblogs.com/yn-jiang/p/3844151.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.ComponentModel;


namespace ConsoleApplication2
{
 
    class Class1
    {

        //创建了密钥对
        static RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        private string privateKey = RSA.ToXmlString(true);
        private string publicKey = RSA.ToXmlString(false);
        static byte[] AOutput;

        public static string GetKeyFromContainer(string ContainerName, bool privatekey)
        {
            CspParameters cp = new CspParameters();
            cp.KeyContainerName = ContainerName;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
            return rsa.ToXmlString(privatekey);
        }

        //加密
        public static string RSAEncrypt(string publicKey, string content)
        {
            RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider();

            Rsa.FromXmlString(publicKey);
            byte[] cipherbytes = Rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            AOutput = Rsa.Encrypt(cipherbytes, false);
            return Convert.ToBase64String(AOutput);
        }

        //解密
        public static string RSADecrypt(string privateKey, string content)
        {
            RSACryptoServiceProvider Rsa2 = new RSACryptoServiceProvider();
            Rsa2.FromXmlString(privateKey);
            byte[] cipherbytes = Rsa2.Decrypt(Convert.FromBase64String(content), false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

        //获取hash值
        private byte[] GetHash(string content)
        {
            try
            {
                //FileStream objFile = File.OpenRead(filePath);
                byte[] data_Bytes = Encoding.ASCII.GetBytes(content);
                HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
                byte[] Hashbyte = MD5.ComputeHash(data_Bytes);
                //objFile.Close();
                return Hashbyte;
            }
            catch
            {
                return null;
            }
            throw new NotImplementedException();
        }

        //获取文件hash
        public static byte[] GetFileHash(string filePath)
        {
            try
            {
                FileStream objFile = File.OpenRead(filePath);
                HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
                byte[] Hashbyte = MD5.ComputeHash(objFile);
                objFile.Close();
                return Hashbyte;
            }
            catch
            {
                return null;
            }
        }

        //创建数字签名
        byte[] EncryptHash(string privateKey, byte[] hash_Bytes)
        {
            RSACryptoServiceProvider Rsa3 = new RSACryptoServiceProvider();
            Rsa3.FromXmlString(privateKey);

            RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(Rsa3);
            RSAFormatter.SetHashAlgorithm("MD5");
            
            

            //AOutput = Rsa3.SignData(data_Bytes, "SHA1");

            return RSAFormatter.CreateSignature(hash_Bytes); ;
        }

        //验证数字签名
        public bool DecryptHash(string publicKey, byte[] hash_byte, byte[] eSignature)
        {
            try
            {
                RSACryptoServiceProvider Rsa4 = new RSACryptoServiceProvider();
                Rsa4.FromXmlString(publicKey);
            
                //bool bVerify = Rsa4.VerifyData(strData, "SHA1", AOutput);
                RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(Rsa4);
                RSADeformatter.SetHashAlgorithm("MD5");

                bool bVerify = RSADeformatter.VerifySignature(hash_byte,eSignature);

                if (bVerify)
                {
                    return true;
                }
                return false;
            }
            catch (CryptographicException e)
            {
                return false;
            }
        }

        // 将Byte[]转换成十六进制字符串
        public static string ConvertBytesToString(byte[] bytes)
        {
            string bytestring = string.Empty;
            if (bytes != null && bytes.Length > 0)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    bytestring += bytes[i].ToString("X") + " ";
                }
            }
            return bytestring;
        }

        static void Main(string[] args)
        {
            //打开文件,或者是获取网页数据
            Console.WriteLine("接收方收到电子文件。");
            string strMsg = "dadfdfgdgdgagdgadg";  //test data
            Console.WriteLine(strMsg);
            Class1 cls = new Class1();


            //对电子文件进行哈希
            Console.WriteLine("哈希值:");
            byte[] hash_data = cls.GetHash(strMsg);
            Console.WriteLine(ConvertBytesToString(hash_data));

            //创建数据签名
            
            Console.WriteLine("私钥:");
            Console.WriteLine(cls.privateKey);

            Console.WriteLine("用私钥进行数字签名");
            byte[] eSingnature = cls.EncryptHash(cls.privateKey,hash_data);
            Console.WriteLine(ConvertBytesToString(eSingnature));
      
            //测试数据
            string strMsgCopy = string.Copy(strMsg);
            Console.WriteLine("被验证的哈希值:");
            byte[] hash_dataCopy = cls.GetHash(strMsgCopy);
            Console.WriteLine(ConvertBytesToString(hash_dataCopy));

            Console.WriteLine("公钥:");
            Console.WriteLine(cls.publicKey);


            if (cls.DecryptHash(cls.publicKey, hash_dataCopy, eSingnature))
            {
                Console.WriteLine("通过验证,电子文件合法有效。");
            }

            else
            {
                Console.WriteLine("未通过验证,电子文件非法或被人篡改过。");

            }

            Console.ReadLine();
            //Class1 cls = new Class1();
            //string filePath = "D://公文.txt";
            //StreamWriter sw = File.CreateText(filePath);
            //sw.Write("测试公文");
            //sw.Close();


            //byte[] fileHash = GetFileHash(filePath);
            //string publicKey = GetKeyFromContainer("公文", false);
            //string privateKey = GetKeyFromContainer("公文", true);

            //byte[] ElectronicSignature = cls.EncryptHash(privateKey, fileHash);

            //string fileCopyPath = "D://公文接收.txt";
            //File.Copy(filePath, fileCopyPath, true);
            //byte[] fileCopyHash = GetFileHash(fileCopyPath);
            //if (cls.DecryptHash(publicKey, fileCopyHash, ElectronicSignature)) 
            //{ 
            //    Console.WriteLine("通过验证,电子文件合法有效。"); 
            //} 
            //else 
            //{ 
            //    Console.WriteLine("未通过验证,电子文件非法或被人篡改过。"); 
            //}

            //Console.Read();     
        }
        
    }
}



暂时没有评论
发表评论 - 不要忘了输入验证码哦!
作者: 用户:  密码:   注册? 验证:  防止恶意留言请输入问题答案:2*8=?  
评论:

禁止表情
禁止UBB
禁止图片
识别链接
识别关键字

字体样式 文字大小 文字颜色
插入粗体文本 插入斜体文本 插入下划线
左对齐 居中对齐 右对齐
插入超级链接 插入邮件地址 插入图像
插入 Flash 插入代码 插入引用
插入列表 插入音频文件 插入视频文件
插入缩进符合
点击下载按钮 下标 上标
水平线 简介分割标记
表  情
 
Tiancao Blog All Rights Reserved 田草博客 版权所有
Copyright ©