轉載 MD5 加密、解密、數字簽名及驗證

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();     
        }
        
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章