技术文章 > 常用编码工具类,支持base64,md5,des,crc32

常用编码工具类,支持base64,md5,des,crc32

2018-04-26 17:40

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:
常用编码工具类,支持base64,md5,des,crc32
支持从文件到文件,从字符串到字符串的方式操作
以下是源码:
[code]
csharp
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;

namespace YNEC.Services.Encrypt
{
/**/
///
/// CRC 效验
/// 快速检测算法
///

public class CRC32
{
protected ulong[] crc32Table;
/**/
///
/// 构造:初始化效验表
///

public CRC32()
{
const ulong ulPolynomial = 0xEDB88320;
ulong dwCrc;
crc32Table = new ulong[256];
int i, j;
for (i = 0; i < 256; i++)
{
dwCrc = (ulong)i;
for (j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
dwCrc = (dwCrc >> 1) ^ ulPolynomial;
else
dwCrc >>= 1;
}
crc32Table[i] = dwCrc;
}
}
/**/
///
/// 字节数组效验
///

/// ref 字节数组
///
public ulong ByteCRC(ref byte[] buffer)
{
ulong ulCRC = 0xffffffff;
ulong len;
len = (ulong)buffer.Length;
for (ulong buffptr = 0; buffptr < len; buffptr++)
{
ulong tabPtr = ulCRC & 0xFF;
tabPtr = tabPtr ^ buffer[buffptr];
ulCRC = ulCRC >> 8;
ulCRC = ulCRC ^ crc32Table[tabPtr];
}
return ulCRC ^ 0xffffffff;
}

/**/
///
/// 字符串效验
///

/// 字符串
///
public ulong StringCRC(string sInputString)
{
byte[] buffer = Encoding.Default.GetBytes(sInputString);
return ByteCRC(ref buffer);
}
/**/
///
/// 文件效验
///

/// 输入文件
///
public ulong FileCRC(string sInputFilename)
{
FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bInput = new byte[inFile.Length];
inFile.Read(bInput, 0, bInput.Length);
inFile.Close();
return ByteCRC(ref bInput);
}
}
/**/
///
/// MD5 无逆向编码
/// 获取唯一特征串,可用于密码加密
/// (无法还原)
///

public class MD5
{
public MD5()
{
}
/**/
///
/// 获取字符串的特征串
///

/// 输入文本
///
public string HashString(string sInputString)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(sInputString))).Replace("-", "");
return encoded;
}
/**/
///
/// 获取文件的特征串
///

/// 输入文件
///
public string HashFile(string sInputFilename)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bInput = new byte[inFile.Length];
inFile.Read(bInput, 0, bInput.Length);
inFile.Close();
string encoded = BitConverter.ToString(md5.ComputeHash(bInput)).Replace("-", "");
return encoded;
}
}
/**/
///
/// Base64 UUEncoded 编码
/// 将二进制编码为ASCII文本,用于网络传输
/// (可还原)
///

public class BASE64
{
public BASE64()
{
}
/**/
///
/// 解码字符串
///

/// 输入文本
///
public string DecryptString(string sInputString)
{
char[] sInput = sInputString.ToCharArray();
try
{
byte[] bOutput = System.Convert.FromBase64String(sInputString);
return Encoding.Default.GetString(bOutput);
}
catch (System.ArgumentNullException)
{
//base 64 字符数组为null
return "";
}
catch (System.FormatException)
{
//长度错误,无法整除4
return "";
}
}
/**/
///
/// 编码字符串
///

/// 输入文本
///
public string EncryptString(string sInputString)
{
byte[] bInput = Encoding.Default.GetBytes(sInputString);
try
{
return System.Convert.ToBase64String(bInput, 0, bInput.Length);
}
catch (System.ArgumentNullException)
{
//二进制数组为NULL.
return "";
}
catch (System.ArgumentOutOfRangeException)
{
//长度不够
return "";
}
}
/**/
///
/// 解码文件
///

/// 输入文件
/// 输出文件
public void DecryptFile(string sInputFilename, string sOutputFilename)
{
System.IO.StreamReader inFile;
char[] base64CharArray;
try
{
inFile = new System.IO.StreamReader(sInputFilename,
System.Text.Encoding.ASCII);
base64CharArray = new char[inFile.BaseStream.Length];
inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length);
inFile.Close();
}
catch
{//(System.Exception exp) {
return;
}
// 转换Base64 UUEncoded为二进制输出
byte[] binaryData;
try
{
binaryData =
System.Convert.FromBase64CharArray(base64CharArray,
0,
base64CharArray.Length);
}
catch (System.ArgumentNullException)
{
//base 64 字符数组为null
return;
}
catch (System.FormatException)
{
//长度错误,无法整除4
return;
}
// 写输出数据
System.IO.FileStream outFile;
try
{
outFile = new System.IO.FileStream(sOutputFilename,
System.IO.FileMode.Create,
System.IO.FileAccess.Write);
outFile.Write(binaryData, 0, binaryData.Length);
outFile.Close();
}
catch
{
// (System.Exception exp) {
//流错误
}
}
/**/
///
/// 编码文件
///

/// 输入文件
/// 输出文件
public void EncryptFile(string sInputFilename, string sOutputFilename)
{
System.IO.FileStream inFile;
byte[] binaryData;
try
{
inFile = new System.IO.FileStream(sInputFilename,
System.IO.FileMode.Open,
System.IO.FileAccess.Read);
binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0,
(int)inFile.Length);
inFile.Close();
}
catch
{ //(System.Exception exp) {
return;
}
// 转换二进制输入为Base64 UUEncoded输出
// 每3个字节在源数据里作为4个字节
long arrayLength = (long)((4.0d / 3.0d) * binaryData.Length);

// 如果无法整除4
if (arrayLength % 4 != 0)
{
arrayLength += 4 - arrayLength % 4;
}

char[] base64CharArray = new char[arrayLength];
try
{
System.Convert.ToBase64CharArray(binaryData,
0,
binaryData.Length,
base64CharArray,
0);
}
catch (System.ArgumentNullException)
{
//二进制数组为NULL.
return;
}
catch (System.ArgumentOutOfRangeException)
{
//长度不够
return;
}
// 写UUEncoded数据到文件内
System.IO.StreamWriter outFile;
try
{
outFile = new System.IO.StreamWriter(sOutputFilename,
false,
System.Text.Encoding.ASCII);
outFile.Write(base64CharArray);
outFile.Close();
}
catch
{// (System.Exception exp) {
//文件流出错
}

}
}
/**/
///
/// DES 加密
/// 支持Key(钥匙)加密变化
/// 支持还原
///
/// 演示操作:
/// // 64位,8个字节
/// string sSecretKey;
///
/// // 获取Key
/// sSecretKey = GenerateKey();
///
/// // 托管
/// GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
///
/// // 加密文件
/// EncryptFile(@"C:\MyData.txt",
/// @"C:\Encrypted.txt",
/// sSecretKey);
///
/// // 解密文件
/// DecryptFile(@"C:\Encrypted.txt",
/// @"C:\Decrypted.txt",
/// sSecretKey);
///
/// // 释放托管内容
/// ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
/// gch.Free();
///

public class DES
{
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
public DES()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/**/
///
/// 创建Key
///

///
public string GenerateKey()
{
// 创建一个DES 算法的实例。自动产生Key
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
// 返回自动创建的Key 用于加密
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
/**/
///
/// 加密字符串
///

/// 输入字符
/// Key
/// 加密结果
public string EncryptString(string sInputString, string sKey)
{
byte[] data = Encoding.Default.GetBytes(sInputString);
byte[] result;
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
result = desencrypt.TransformFinalBlock(data, 0, data.Length);
string desString = "";
for (int i = 0; i < result.Length; i++)
{
desString += result[i].ToString() + "-";
}

//return desString.TrimEnd("-");
return BitConverter.ToString(result);
}
/**/
///
/// 解密字符串
///

/// 输入字符
/// Key
/// 解密结果
public string DecryptString(string sInputString, string sKey)
{
string[] sInput = sInputString.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
byte[] result;
for (int i = 0; i < sInput.Length; i++)
data[i] = byte.Parse(sInput[i], System.Globalization.NumberStyles.HexNumber);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.Default.GetString(result);
}
/**/
///
/// 加密文件
///

/// 输入文件
/// 输出文件
/// Key
public 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();
}
/**/
///
/// 解密文件
///

/// 输入文件
/// 输出文件
/// Key
public void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
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();
}
}
}
[/code]