MD5 加密、解密、数字签名及验证

 

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using System.Security.Cryptography;
  7 using System.ComponentModel;
  8 
  9 
 10 namespace ConsoleApplication2
 11 {
 12  
 13     class Class1
 14     {
 15 
 16         //创建了密钥对
 17         static RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
 18         private string privateKey = RSA.ToXmlString(true);
 19         private string publicKey = RSA.ToXmlString(false);
 20         static byte[] AOutput;
 21 
 22         public static string GetKeyFromContainer(string ContainerName, bool privatekey)
 23         {
 24             CspParameters cp = new CspParameters();
 25             cp.KeyContainerName = ContainerName;
 26             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
 27             return rsa.ToXmlString(privatekey);
 28         }
 29 
 30         //加密
 31         public static string RSAEncrypt(string publicKey, string content)
 32         {
 33             RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider();
 34 
 35             Rsa.FromXmlString(publicKey);
 36             byte[] cipherbytes = Rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
 37             AOutput = Rsa.Encrypt(cipherbytes, false);
 38             return Convert.ToBase64String(AOutput);
 39         }
 40 
 41         //解密
 42         public static string RSADecrypt(string privateKey, string content)
 43         {
 44             RSACryptoServiceProvider Rsa2 = new RSACryptoServiceProvider();
 45             Rsa2.FromXmlString(privateKey);
 46             byte[] cipherbytes = Rsa2.Decrypt(Convert.FromBase64String(content), false);
 47             return Encoding.UTF8.GetString(cipherbytes);
 48         }
 49 
 50         //获取hash值
 51         private byte[] GetHash(string content)
 52         {
 53             try
 54             {
 55                 //FileStream objFile = File.OpenRead(filePath);
 56                 byte[] data_Bytes = Encoding.ASCII.GetBytes(content);
 57                 HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
 58                 byte[] Hashbyte = MD5.ComputeHash(data_Bytes);
 59                 //objFile.Close();
 60                 return Hashbyte;
 61             }
 62             catch
 63             {
 64                 return null;
 65             }
 66             throw new NotImplementedException();
 67         }
 68 
 69         //获取文件hash
 70         public static byte[] GetFileHash(string filePath)
 71         {
 72             try
 73             {
 74                 FileStream objFile = File.OpenRead(filePath);
 75                 HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
 76                 byte[] Hashbyte = MD5.ComputeHash(objFile);
 77                 objFile.Close();
 78                 return Hashbyte;
 79             }
 80             catch
 81             {
 82                 return null;
 83             }
 84         }
 85 
 86         //创建数字签名
 87         byte[] EncryptHash(string privateKey, byte[] hash_Bytes)
 88         {
 89             RSACryptoServiceProvider Rsa3 = new RSACryptoServiceProvider();
 90             Rsa3.FromXmlString(privateKey);
 91 
 92             RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(Rsa3);
 93             RSAFormatter.SetHashAlgorithm("MD5");
 94             
 95             
 96 
 97             //AOutput = Rsa3.SignData(data_Bytes, "SHA1");
 98 
 99             return RSAFormatter.CreateSignature(hash_Bytes); ;
100         }
101 
102         //验证数字签名
103         public bool DecryptHash(string publicKey, byte[] hash_byte, byte[] eSignature)
104         {
105             try
106             {
107                 RSACryptoServiceProvider Rsa4 = new RSACryptoServiceProvider();
108                 Rsa4.FromXmlString(publicKey);
109             
110                 //bool bVerify = Rsa4.VerifyData(strData, "SHA1", AOutput);
111                 RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(Rsa4);
112                 RSADeformatter.SetHashAlgorithm("MD5");
113 
114                 bool bVerify = RSADeformatter.VerifySignature(hash_byte,eSignature);
115 
116                 if (bVerify)
117                 {
118                     return true;
119                 }
120                 return false;
121             }
122             catch (CryptographicException e)
123             {
124                 return false;
125             }
126         }
127 
128         // 将Byte[]转换成十六进制字符串
129         public static string ConvertBytesToString(byte[] bytes)
130         {
131             string bytestring = string.Empty;
132             if (bytes != null && bytes.Length > 0)
133             {
134                 for (int i = 0; i < bytes.Length; i++)
135                 {
136                     bytestring += bytes[i].ToString("X") + " ";
137                 }
138             }
139             return bytestring;
140         }
141 
142         static void Main(string[] args)
143         {
144             //打开文件,或者是获取网页数据
145             Console.WriteLine("接收方收到电子文件。");
146             string strMsg = "dadfdfgdgdgagdgadg";  //test data
147             Console.WriteLine(strMsg);
148             Class1 cls = new Class1();
149 
150 
151             //对电子文件进行哈希
152             Console.WriteLine("哈希值:");
153             byte[] hash_data = cls.GetHash(strMsg);
154             Console.WriteLine(ConvertBytesToString(hash_data));
155 
156             //创建数据签名
157             
158             Console.WriteLine("私钥:");
159             Console.WriteLine(cls.privateKey);
160 
161             Console.WriteLine("用私钥进行数字签名");
162             byte[] eSingnature = cls.EncryptHash(cls.privateKey,hash_data);
163             Console.WriteLine(ConvertBytesToString(eSingnature));
164       
165             //测试数据
166             string strMsgCopy = string.Copy(strMsg);
167             Console.WriteLine("被验证的哈希值:");
168             byte[] hash_dataCopy = cls.GetHash(strMsgCopy);
169             Console.WriteLine(ConvertBytesToString(hash_dataCopy));
170 
171             Console.WriteLine("公钥:");
172             Console.WriteLine(cls.publicKey);
173 
174 
175             if (cls.DecryptHash(cls.publicKey, hash_dataCopy, eSingnature))
176             {
177                 Console.WriteLine("通过验证,电子文件合法有效。");
178             }
179 
180             else
181             {
182                 Console.WriteLine("未通过验证,电子文件非法或被人篡改过。");
183 
184             }
185 
186             Console.ReadLine();
187             //Class1 cls = new Class1();
188             //string filePath = "D://公文.txt";
189             //StreamWriter sw = File.CreateText(filePath);
190             //sw.Write("测试公文");
191             //sw.Close();
192 
193 
194             //byte[] fileHash = GetFileHash(filePath);
195             //string publicKey = GetKeyFromContainer("公文", false);
196             //string privateKey = GetKeyFromContainer("公文", true);
197 
198             //byte[] ElectronicSignature = cls.EncryptHash(privateKey, fileHash);
199 
200             //string fileCopyPath = "D://公文接收.txt";
201             //File.Copy(filePath, fileCopyPath, true);
202             //byte[] fileCopyHash = GetFileHash(fileCopyPath);
203             //if (cls.DecryptHash(publicKey, fileCopyHash, ElectronicSignature)) 
204             //{ 
205             //    Console.WriteLine("通过验证,电子文件合法有效。"); 
206             //} 
207             //else 
208             //{ 
209             //    Console.WriteLine("未通过验证,电子文件非法或被人篡改过。"); 
210             //}
211 
212             //Console.Read();     
213         }
214         
215     }
216 }

 

posted @ 2014-07-15 10:11  小丸子学编程  阅读(8526)  评论(0编辑  收藏  举报