C#获取文件MD5字符串
备注
哈希函数将任意长度的二进制字符串映射为固定长度的小型二进制字符串。加密哈希函数有这样一个属性:在计算不大可能找到散列为相同的值的两个不同的输入;也就是说,两组数据的哈希值仅在对应的数据也匹配时才会匹配。数据的少量更改会在哈希值中产生不可预知的大量更改。
MD5 算法的哈希值大小为 128 位。
MD5 类的 ComputeHash 方法将哈希作为 16 字节的数组返回。请注意,某些 MD5 实现会生成 32 字符的十六进制格式哈希。若要与此类实现进行互操作,请将 ComputeHash 方法的返回值格式化为十六进制值。
示例
下面的代码示例计算字符串的 MD5 哈希值,并将该哈希作为 32 字符的十六进制格式字符串返回。此代码示例中创建的哈希字符串与能创建 32 字符的十六进制格式哈希字符串的任何 MD5 哈希函数(在任何平台上)兼容。
using System;
using System.Security.Cryptography;
using System.Text;
class Example
{
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool verifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = getMd5Hash(input);
// Create a StringComparer an comare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
static void Main()
{
string source = "Hello World!";
string hash = getMd5Hash(source);
Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
Console.WriteLine("Verifying the hash...");
if (verifyMd5Hash(source, hash))
{
Console.WriteLine("The hashes are the same.");
}
else
{
Console.WriteLine("The hashes are not same.");
}
}
}
// This code example produces the following output:
//
// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
// Verifying the hash...
// The hashes are the same.
代码:
1)获取文件MD5字符串:
// filename:文件的物理路径(如:D:\dwb\excel\AA.xls)
string ByteArrayToHexString(string filename) {
FileStream fs = new FileStream(filename, FileMode.Open);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.Initialize();
byte[] bytes = md5.ComputeHash(fs);
md5.Clear();
fs.Close();
StringBuilder sb = new StringBuilder();
foreach (byte b in bytes)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
2)加密配置文件:
string sSecretKey;// 密钥
先生成加密解密需要的密钥 sSecretKey = GenerateKey();
/// <summary>
/// 根据KEY生成密钥
/// </summary>
/// <param name="key">KEY字符串</param>
/// <returns></returns>
string GenerateKey(string key)
{
byte[] keys = new byte[8];
int j = 0;
for (int i = 0; i < keys.Length; i++)
{
keys[i] = Convert.ToByte(System.Text.Encoding.Unicode.GetBytes(key.Substring(j, 1))[0] - 5);
j += 2;
}
byte[] keys1 = new byte[8];
for (int i = 0; i < keys.Length; i++)
{
keys1[i] = keys[keys.Length - i - 1];
}
return ASCIIEncoding.ASCII.GetString(keys1);
}
/// <summary>
/// 加密文件
/// </summary>
/// <param name="sInputFilename">需要加密的文件(包括路径)</param>
/// <param name="sOutputFilename">加密后的文件(包括路径)</param>
/// <param name="sKey">密钥</param>
void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
3)解密配置文件:
/// <summary>
/// 解密文件
/// </summary>
/// <param name="sInputFilename">需要解密的文件(包括路径)</param>
/// <param name="sOutputFilename">解密后的文件(包括路径)</param>
/// <param name="sKey">密钥</param>
void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
fsread.Close();
}
C#获取文件MD5字符串的更多相关文章
- QT 获取文件MD5值
/* 方法1 */ QFile theFile(fileNamePath); theFile.open(QIODevice::ReadOnly); QByteArray ba = QCryptogra ...
- JAVA中获取文件MD5值的四种方法
JAVA中获取文件MD5值的四种方法其实都很类似,因为核心都是通过JAVA自带的MessageDigest类来实现.获取文件MD5值主要分为三个步骤,第一步获取文件的byte信息,第二步通过Messa ...
- c#获取文件MD5算法
//获取文件MD5算法 private static string GetMD5FromFile(string fileName) { try { FileStream file = new File ...
- C# 获取文件MD5值的方法
可用于对比文件是否相同 /// <summary> /// 获取文件MD5值 /// </summary> /// <param name="fileName& ...
- 基于js-spark-md5前端js类库,快速获取文件Md5值
js-spark-md5是歪果仁开发的东西,有点多,但是我们只要一个js文件即可,具体类包我存在自己的oschina上,下载地址:https://git.oschina.net/jianqingwan ...
- 获取文件MD5值(JS、JAVA)
文章HTML代码翻译于地址:https://www.cnblogs.com/linyihai/p/7040786.html 文件MD5有啥用? 文 ...
- C# 获取文件MD5与SHA1
之前刚开始学习编程的时候,总想着自己写一些小软件小工具. 而这个就是经典的文件MD5校验,顺便加上了一个SHA1. 在网络上下载一些东西时,会有作者提供MD5值. 它的作用就在于我们可以在下载该软件后 ...
- Java 获取 文件md5校验码
讯雷下载的核心思想是校验文件的md5值,两个文件若md5相同则为同一文件. 当得到用户下载某个文件的请求后它根据数据库中保留的文件md5比对出拥有此文件的url, 将用户请求挂接到此url上并仿造一个 ...
- window/linux下获取文件MD5
MD5消息摘要算法(英语: MD5 Message-Digest Algorithm), 主要用于确保信息传输过程的一致性校验. 首先介绍两个工具: window: WinMD5Free Linu ...
随机推荐
- C++ virtual虚函数
#include<iostream> using namespace std; class Base{ public: void m() { cout << "it' ...
- RPM方式安装MySQL5.5.48 (Aliyun CentOS 7.0 & 卸载MySQL5.7)
环境是阿里云的CentOS7.0,更新了yum源(更新yum源请参考https://help.aliyun.com/knowledge_detail/5974184.html)之后先是尝试安装了MyS ...
- my_strstr()
const char* my_strstr(const char* S1,const char* S2){ int i=0,flag=0; while('\0'!=*(S1+i)){ if(*(S1+ ...
- (转)android.intent.action.MAIN与android.intent.category.LAUNCHER
android.intent.action.MAIN决定应用程序最先启动的Activity android.intent.category.LAUNCHER决定应用程序是否显示在程序列表里 在网上看到 ...
- Mac os下换行符导致发布到npm里的命令行模块不能使用问题
学习node,弄一个命令行模块,发布到npm后,Windows安装后可以使用,但Mac 终端下则不行.对比grunt-cli搞了一夜,甚是郁闷,最后发现竟然是操作系统的换行符问题. npm insta ...
- Azure 删除VHD时报错:There is currently a lease on the blob and no lease ID was specified in the request
可下载:http://clumsyleaf.com/products/cloudxplorer 然后在Accounts中新建一个Account,账号与Key,可在相应的storage Manage A ...
- [转]PLSQL Developer备份恢复oracle数据
本文转自:http://www.cnblogs.com/iampkm/archive/2013/06/09/3128273.html 使用PL sql提供的功能可以快速的备份恢复oracle数据. 1 ...
- 太阳系Demo(openGL)
这个是8年前写的demo,提交的一份作业,按照提出的需求点,以最快和最简单的方式完成功能,因此代码比较简单. 1)截图 2) 功能点描述: 1.公转,自传 2.基础的摄像机运动 3.正视和顶视 4.天 ...
- dotNet开发游戏微端
需求分析 功能要求 当玩家使用不支持 unity webplayer 的浏览器进入游戏时,让玩家通过微端玩游戏. 确保微端的功能和页游戏功能一致. 大体功能就是为unity web game开发微端, ...
- 【Unity3d】Ray射线初探-射线的原理及用法
http://www.xiaobao1993.com/231.html 射线是一个无穷的线,开始于origin并沿着direction方向. 当射线碰到物体后.它就会停止发射. 在屏幕中拉一个CUBE ...