using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web; namespace WebDemo.Until
{ public class EncryptHelper
{
#region DES对称加密解密 /// <summary> 加密字符串
/// </summary>
/// <param name="strText">需被加密的字符串</param>
/// <param name="strEncrKey">密钥</param>
/// <returns></returns>
public static string DesEncrypt(string strText, string strEncrKey)
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(, ));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return "";
}
} /// <summary> 解密字符串
/// </summary>
/// <param name="strText">需被解密的字符串</param>
/// <param name="sDecrKey">密钥</param>
/// <returns></returns>
public static string DesDecrypt(string strText, string sDecrKey)
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[strText.Length]; byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(, ));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = new UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch
{
return null;
}
} /// <summary> 加密文件
///
/// </summary>
/// <param name="m_InFilePath">原路径</param>
/// <param name="m_OutFilePath">加密后的文件路径</param>
/// <param name="strEncrKey">密钥</param>
public static void DesEncryptFile(string m_InFilePath, string m_OutFilePath, string strEncrKey)
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(, ));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength();
//Create variables to help with read and write.
byte[] bin = new byte[]; //This is intermediate storage for the encryption.
long rdlen = ; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, , );
encStream.Write(bin, , len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
catch
{
} } /// <summary> 解密文件
///
/// </summary>
/// <param name="m_InFilePath">被解密路径</param>
/// <param name="m_OutFilePath">解密后的路径</param>
/// <param name="sDecrKey">密钥</param>
public static void DesDecryptFile(string m_InFilePath, string m_OutFilePath, string sDecrKey)
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(, ));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength();
//Create variables to help with read and write.
byte[] bin = new byte[]; //This is intermediate storage for the encryption.
long rdlen = ; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, , );
encStream.Write(bin, , len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
catch
{
}
}
#endregion #region 3DES对称加密解密
/// <summary>
///3DES加密
/// </summary>
/// <param name="originalValue">加密数据</param>
/// <param name="key">24位字符的密钥字符串</param>
/// <param name="IV">8位字符的初始化向量字符串</param>
/// <returns></returns>
public static string DESEncrypt(string originalValue, string key, string IV)
{
SymmetricAlgorithm sa = new TripleDESCryptoServiceProvider();
sa.Mode = CipherMode.CBC;
sa.Padding = PaddingMode.PKCS7;
sa.Key = Encoding.UTF8.GetBytes(key);
sa.IV = Encoding.UTF8.GetBytes(IV);
ICryptoTransform ct = sa.CreateEncryptor();
byte[] byt = Encoding.UTF8.GetBytes(originalValue);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, , byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 3DES解密
/// </summary>
/// <param name="data">解密数据</param>
/// <param name="key">24位字符的密钥字符串(需要和加密时相同)</param>
/// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
/// <returns></returns>
public static string DESDecrypst(string data, string key, string IV)
{
SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
mCSP.Mode = CipherMode.CBC;
mCSP.Padding = PaddingMode.PKCS7;
mCSP.Key = Encoding.UTF8.GetBytes(key);
mCSP.IV = Encoding.UTF8.GetBytes(IV);
ICryptoTransform ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byte[] byt = Convert.FromBase64String(data);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, , byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
#endregion #region AES RijndaelManaged加密解密 private static readonly string Default_AES_Key = "@#kim123";
private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
public static string AES_Encrypt(string encryptString)
{
return AES_Encrypt(encryptString, Default_AES_Key);
} public static string AES_Decrypt(string decryptString)
{
return AES_Decrypt(decryptString, Default_AES_Key);
} #region AES(CBC)有向量(IV)
/// <summary>对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
///
/// </summary>
/// <param name="encryptString">待加密字符串</param>
/// <param name="encryptKey">加密密钥,须半角字符</param>
/// <returns>加密结果字符串</returns>
public static string AES_Encrypt(string encryptString, string encryptKey)
{
encryptKey = GetSubString(encryptKey, , "");
encryptKey = encryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor(); byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, , inputData.Length); return Convert.ToBase64String(encryptedData);
} /// <summary> 对称加密算法AES RijndaelManaged解密字符串
///
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返回空</returns>
public static string AES_Decrypt(string decryptString, string decryptKey)
{
try
{
decryptKey = GetSubString(decryptKey, , "");
decryptKey = decryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor(); byte[] inputData = Convert.FromBase64String(decryptString);
byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, , inputData.Length); return Encoding.UTF8.GetString(decryptedData);
}
catch
{
return string.Empty;
}
}
#endregion #region AES(ECB)无向量(IV)
/// <summary>
/// AES加密(无向量)
/// </summary>
/// <param name="plainBytes">被加密的明文</param>
/// <param name="key">密钥 32 </param>
/// <returns>密文</returns>
public static string AESEncryptECB(string encryptString, string encryptKey)
{
try
{
encryptKey = GetSubString(encryptKey, , "");
encryptKey = encryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
rijndaelProvider.Mode = CipherMode.ECB;
rijndaelProvider.Padding = PaddingMode.PKCS7;
ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, , inputData.Length);
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
return ex.Message;
}
} /// <summary>
/// AES解密(无向量)
/// </summary>
/// <param name="decryptString">被加密的明文</param>
/// <param name="decryptKey">密钥</param>
/// <returns>明文</returns>
public static string AESDecryptECB(string decryptString, string decryptKey)
{
try
{
decryptKey = GetSubString(decryptKey, , "");
decryptKey = decryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey.Substring(, ));
rijndaelProvider.Mode = CipherMode.ECB;
rijndaelProvider.Padding = PaddingMode.PKCS7;
ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
byte[] inputData = Convert.FromBase64String(decryptString);
byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, , inputData.Length);
return Encoding.UTF8.GetString(decryptedData);
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion /// <summary>
/// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="length">所取字符串字节长度</param>
/// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
/// <returns>某字符串的一部分</returns>
private static string GetSubString(string sourceString, int length, string tailString)
{
return GetSubString(sourceString, , length, tailString);
} /// <summary>
/// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="startIndex">索引位置,以0开始</param>
/// <param name="length">所取字符串字节长度</param>
/// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
/// <returns>某字符串的一部分</returns>
private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
{
string myResult = sourceString; //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") ||
System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
{
//当截取的起始位置超出字段串长度时
if (startIndex >= sourceString.Length)
{
return string.Empty;
}
else
{
return sourceString.Substring(startIndex,
((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
}
} //中文字符,如"中国人民abcd123"
if (length <= )
{
return string.Empty;
}
byte[] bytesSource = Encoding.Default.GetBytes(sourceString); //当字符串长度大于起始位置
if (bytesSource.Length > startIndex)
{
int endIndex = bytesSource.Length; //当要截取的长度在字符串的有效长度范围内
if (bytesSource.Length > (startIndex + length))
{
endIndex = length + startIndex;
}
else
{ //当不在有效范围内时,只取到字符串的结尾
length = bytesSource.Length - startIndex;
tailString = "";
} int[] anResultFlag = new int[length];
int nFlag = ;
//字节大于127为双字节字符
for (int i = startIndex; i < endIndex; i++)
{
if (bytesSource[i] > )
{
nFlag++;
if (nFlag == )
{
nFlag = ;
}
}
else
{
nFlag = ;
}
anResultFlag[i] = nFlag;
}
//最后一个字节为双字节字符的一半
if ((bytesSource[endIndex - ] > ) && (anResultFlag[length - ] == ))
{
length = length + ;
} byte[] bsResult = new byte[length];
Array.Copy(bytesSource, startIndex, bsResult, , length);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + tailString; return myResult;
} return string.Empty; } /// <summary>
/// 加密文件流
/// </summary>
/// <param name="fs"></param>
/// <returns></returns>
public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey)
{
decryptKey = GetSubString(decryptKey, , "");
decryptKey = decryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys; ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
return cytptostreamEncr;
} /// <summary>
/// 解密文件流
/// </summary>
/// <param name="fs"></param>
/// <returns></returns>
public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey)
{
decryptKey = GetSubString(decryptKey, , "");
decryptKey = decryptKey.PadRight(, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
return cytptostreamDecr;
} /// <summary>
/// 对指定文件加密
/// </summary>
/// <param name="InputFile"></param>
/// <param name="OutputFile"></param>
/// <returns></returns>
public static bool AES_EncryptFile(string InputFile, string OutputFile)
{
try
{
string decryptKey = "www.iqidi.com"; FileStream fr = new FileStream(InputFile, FileMode.Open);
FileStream fren = new FileStream(OutputFile, FileMode.Create);
CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
byte[] bytearrayinput = new byte[fr.Length];
fr.Read(bytearrayinput, , bytearrayinput.Length);
Enfr.Write(bytearrayinput, , bytearrayinput.Length);
Enfr.Close();
fr.Close();
fren.Close();
}
catch
{
//文件异常
return false;
}
return true;
} /// <summary>
/// 对指定的文件解压缩
/// </summary>
/// <param name="InputFile"></param>
/// <param name="OutputFile"></param>
/// <returns></returns>
public static bool AES_DecryptFile(string InputFile, string OutputFile)
{
try
{
string decryptKey = "www.iqidi.com";
FileStream fr = new FileStream(InputFile, FileMode.Open);
FileStream frde = new FileStream(OutputFile, FileMode.Create);
CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
byte[] bytearrayoutput = new byte[];
int m_count = ; do
{
m_count = Defr.Read(bytearrayoutput, , bytearrayoutput.Length);
frde.Write(bytearrayoutput, , m_count);
if (m_count < bytearrayoutput.Length)
break;
} while (true); Defr.Close();
fr.Close();
frde.Close();
}
catch
{
//文件异常
return false;
}
return true;
} #endregion #region RSA加密 解密 /// <summary>RSA加密
///
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="publicKey">公钥</param>
/// <returns>密文字符串</returns>
public static string EncryptByRSA(string plaintext, string publicKey)
{
try
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(publicKey);
byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
return Convert.ToBase64String(encryptedData);
}
}
catch (Exception)
{
return null;
} } /// <summary> RSA解密
///
/// </summary>
/// <param name="ciphertext">密文</param>
/// <param name="privateKey">私钥</param>
/// <returns>明文字符串</returns>
public static string DecryptByRSA(string ciphertext, string privateKey)
{
try
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(privateKey);
byte[] encryptedData = Convert.FromBase64String(ciphertext);
byte[] decryptedData = RSA.Decrypt(encryptedData, false);
return byteConverter.GetString(decryptedData);
}
}
catch (Exception)
{
return null;
} } /// <summary>生成RSA加密 解密的 密钥
/// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了
/// </summary>
/// <param name="path">要生成的密钥文件的路径(文件夹)</param>
public static void getRSAKey(string path)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string datetimestr = System.DateTime.Now.ToString("yyyyMMddHHmmss");
using (StreamWriter writer = new StreamWriter("RSA解密_PrivateKey_" + datetimestr + ".xml")) //这个文件要保密...
{
writer.WriteLine(rsa.ToXmlString(true));
}
using (StreamWriter writer = new StreamWriter("RSA加密_PublicKey_" + datetimestr + ".xml"))
{
writer.WriteLine(rsa.ToXmlString(false));
}
}
#endregion #region Base64加密解密 /// <summary>
/// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
/// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
/// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
/// 系統中而不同。
/// Base64加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Encrypt(string str)
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(encbuff);
} /// <summary>
/// Base64解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Decrypt(string str)
{
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
#endregion #region MD5
/// <summary> /// 获得32位的MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetMD5_32(string input)
{
MD5 md5 = MD5.Create();
byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
StringBuilder sb = new StringBuilder();
for (int i = ; i < data.Length; i++)
{
sb.AppendFormat("{0:X2}", data[i]);
}
return sb.ToString();
} /// <summary>
/// 获得16位的MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetMD5_16(string input)
{
return GetMD5_32(input).Substring(, );
}
/// <summary>
/// 获得8位的MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetMD5_8(string input)
{
return GetMD5_32(input).Substring(, );
}
/// <summary>
/// 获得4位的MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetMD5_4(string input)
{
return GetMD5_32(input).Substring(, );
} public static string MD5EncryptHash(String input)
{
MD5 md5 = new MD5CryptoServiceProvider();
//the GetBytes method returns byte array equavalent of a string
byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), , input.Length);
char[] temp = new char[res.Length];
//copy to a char array which can be passed to a String constructor
Array.Copy(res, temp, res.Length);
//return the result as a string
return new String(temp);
}
#endregion #region MD5签名验证 /// <summary>
/// 对给定文件路径的文件加上标签
/// </summary>
/// <param name="path">要加密的文件的路径</param>
/// <returns>标签的值</returns>
public static bool AddMD5(string path)
{
bool IsNeed = true; if (CheckMD5(path)) //已进行MD5处理
IsNeed = false; try
{
FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] md5File = new byte[fsread.Length];
fsread.Read(md5File, , (int)fsread.Length); // 将文件流读取到Buffer中
fsread.Close(); if (IsNeed)
{
string result = MD5Buffer(md5File, , md5File.Length); // 对Buffer中的字节内容算MD5
byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result); // 将字符串转换成字节数组以便写人到文件中
FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
fsWrite.Write(md5File, , md5File.Length); // 将文件,MD5值 重新写入到文件中。
fsWrite.Write(md5, , md5.Length);
fsWrite.Close();
}
else
{
FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
fsWrite.Write(md5File, , md5File.Length);
fsWrite.Close();
}
}
catch
{
return false;
} return true;
} /// <summary>
/// 对给定路径的文件进行验证
/// </summary>
/// <param name="path"></param>
/// <returns>是否加了标签或是否标签值与内容值一致</returns>
public static bool CheckMD5(string path)
{
try
{
FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] md5File = new byte[get_file.Length]; // 读入文件
get_file.Read(md5File, , (int)get_file.Length);
get_file.Close(); string result = MD5Buffer(md5File, , md5File.Length - ); // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。
string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - , ); //读取文件最后32位,其中保存的就是MD5值
return result == md5;
}
catch
{
return false;
}
} /// <summary>
/// 计算文件的MD5值
/// </summary>
/// <param name="MD5File">MD5签名文件字符数组</param>
/// <param name="index">计算起始位置</param>
/// <param name="count">计算终止位置</param>
/// <returns>计算结果</returns>
private static string MD5Buffer(byte[] MD5File, int index, int count)
{
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
string result = System.BitConverter.ToString(hash_byte); result = result.Replace("-", "");
return result;
}
#endregion #region SHA256加密算法 /// <summary>
/// SHA256函数
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
public static string SHA256(string str)
{
byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
SHA256Managed Sha256 = new SHA256Managed();
byte[] Result = Sha256.ComputeHash(SHA256Data);
return Convert.ToBase64String(Result); //返回长度为44字节的字符串
}
#endregion #region RC4加密 解密 /// <summary>RC4加密算法
/// 返回进过rc4加密过的字符
/// </summary>
/// <param name="str">被加密的字符</param>
/// <param name="ckey">密钥</param>
public static string EncryptRC4wq(string str, string ckey)
{
int[] s = new int[];
for (int i = ; i < ; i++)
{
s[i] = i;
}
//密钥转数组
char[] keys = ckey.ToCharArray();//密钥转字符数组
int[] key = new int[keys.Length];
for (int i = ; i < keys.Length; i++)
{
key[i] = keys[i];
}
//明文转数组
char[] datas = str.ToCharArray();
int[] mingwen = new int[datas.Length];
for (int i = ; i < datas.Length; i++)
{
mingwen[i] = datas[i];
} //通过循环得到256位的数组(密钥)
int j = ;
int k = ;
int length = key.Length;
int a;
for (int i = ; i < ; i++)
{
a = s[i];
j = (j + a + key[k]);
if (j >= )
{
j = j % ;
}
s[i] = s[j];
s[j] = a;
if (++k >= length)
{
k = ;
}
}
//根据上面的256的密钥数组 和 明文得到密文数组
int x = , y = , a2, b, c;
int length2 = mingwen.Length;
int[] miwen = new int[length2];
for (int i = ; i < length2; i++)
{
x = x + ;
x = x % ;
a2 = s[x];
y = y + a2;
y = y % ;
s[x] = b = s[y];
s[y] = a2;
c = a2 + b;
c = c % ;
miwen[i] = mingwen[i] ^ s[c];
}
//密文数组转密文字符
char[] mi = new char[miwen.Length];
for (int i = ; i < miwen.Length; i++)
{
mi[i] = (char)miwen[i];
}
string miwenstr = new string(mi);
return miwenstr;
} /// <summary>RC4解密算法
/// 返回进过rc4解密过的字符
/// </summary>
/// <param name="str">被解密的字符</param>
/// <param name="ckey">密钥</param>
public static string DecryptRC4wq(string str, string ckey)
{
int[] s = new int[];
for (int i = ; i < ; i++)
{
s[i] = i;
}
//密钥转数组
char[] keys = ckey.ToCharArray();//密钥转字符数组
int[] key = new int[keys.Length];
for (int i = ; i < keys.Length; i++)
{
key[i] = keys[i];
}
//密文转数组
char[] datas = str.ToCharArray();
int[] miwen = new int[datas.Length];
for (int i = ; i < datas.Length; i++)
{
miwen[i] = datas[i];
} //通过循环得到256位的数组(密钥)
int j = ;
int k = ;
int length = key.Length;
int a;
for (int i = ; i < ; i++)
{
a = s[i];
j = (j + a + key[k]);
if (j >= )
{
j = j % ;
}
s[i] = s[j];
s[j] = a;
if (++k >= length)
{
k = ;
}
}
//根据上面的256的密钥数组 和 密文得到明文数组
int x = , y = , a2, b, c;
int length2 = miwen.Length;
int[] mingwen = new int[length2];
for (int i = ; i < length2; i++)
{
x = x + ;
x = x % ;
a2 = s[x];
y = y + a2;
y = y % ;
s[x] = b = s[y];
s[y] = a2;
c = a2 + b;
c = c % ;
mingwen[i] = miwen[i] ^ s[c];
}
//明文数组转明文字符
char[] ming = new char[mingwen.Length];
for (int i = ; i < mingwen.Length; i++)
{
ming[i] = (char)mingwen[i];
}
string mingwenstr = new string(ming);
return mingwenstr;
}
#endregion
}
}

原文:https://www.cnblogs.com/gygang/p/8873702.html

C# 各种加密的更多相关文章

  1. 关于CryptoJS中md5加密以及aes加密的随笔

    最近项目中用到了各种加密,其中就包括从没有接触过得aes加密,因此从网上各种查,官方的一种说法: 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学 ...

  2. “不给力啊,老湿!”:RSA加密与破解

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 加密和解密是自古就有技术了.经常看到侦探电影的桥段,勇敢又机智的主角,拿着一长串毫 ...

  3. .NET 对接JAVA 使用Modulus,Exponent RSA 加密

    最近有一个工作是需要把数据用RSA发送给Java 虽然一开始标准公钥 net和Java  RSA填充的一些算法不一样 但是后来这个坑也补的差不多了 具体可以参考 http://www.cnblogs. ...

  4. AES加密

    package com.edu.hpu; import java.math.BigInteger; import java.security.MessageDigest; import java.se ...

  5. Android数据加密之MD5加密

    前言: 项目中无论是密码的存储或者说判断文件是否是同一文件,都会用到MD5算法,今天来总结一下MD5加密算法. 什么是MD5加密? MD5英文全称“Message-Digest Algorithm 5 ...

  6. PHP的学习--RSA加密解密

    PHP服务端与客户端交互或者提供开放API时,通常需要对敏感的数据进行加密,这时候rsa非对称加密就能派上用处了. 举个通俗易懂的例子,假设我们再登录一个网站,发送账号和密码,请求被拦截了. 密码没加 ...

  7. ASP.NET加密和解密数据库连接字符串

    大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...

  8. GPG终极指南(加密/签名)

    我们平时都听过非对称加密,公钥和私钥,签名验证,但这些证书都是怎么得到的呢?本篇文章会解答这些问题. 背景介绍 加密的一个简单但又实用的任务就是发送加密电子邮件.多年来,为电子邮件进行加密的标准一直是 ...

  9. RSA非对称加密,使用OpenSSL生成证书,iOS加密,java解密

    最近换了一份工作,工作了大概一个多月了吧.差不多得有两个月没有更新博客了吧.在新公司自己写了一个iOS的比较通用的可以架构一个中型应用的不算是框架的一个结构,并已经投入使用.哈哈 说说文章标题的相关的 ...

  10. C# salt+hash 加密

    一.先明确几个基本概念 1.伪随机数:pseudo-random number generators ,简称为:PRNGs,是计算机利用一定的算法来产生的.伪随机数并不是假随机 数,这里的" ...

随机推荐

  1. vue 使用 axios 时 post 请求方法传参无法发送至后台

    axios 时 post 请求方法传参无法发送至后台报错如下 Response to preflight request doesn't pass access control check: No ' ...

  2. Luogu P5468 [NOI2019]回家路线 (斜率优化、DP)

    题目链接: (luogu) https://www.luogu.org/problemnew/show/P5468 题解: 爆long long毁一生 我太菜了,这题这么简单考场上居然没想到正解-- ...

  3. 简单记录一下vue生命周期及 父组件和子组件生命周期钩子执行顺序

    首先,vue生命周期可以用下图来简单理解 当然这也是官方文档的图片,详细的vue周期详解请参考这里 然而当同时存在父子组件的时候生命周期钩子是如何执行的呢? 请看下文: 加载渲染过程父beforeCr ...

  4. 函数式接口和Lambda表达式

    函数式接口(一般标有@FunctionalInterface)就是只定义一个抽象方法的接口. 一个接口,如果满足函数式接口的定义,那么即使不标注为 @FunctionalInterface, 编译器依 ...

  5. 当遇到npm ERR! Unexpected end of JSON input while parsing near……时的解决办法

    运行npm install时有时会遇到以下错误: npm ERR! Unexpected end of JSON input while parsing near ... 这时可以先执行下面的命令: ...

  6. HDU6623 思维题(n分解成质因子的形式,问最小的幂是多少)

    题目大意:给你一个数n,把它分解为素数的幂次的乘积的形式:n=p1^e1 * p2^e2 * .......pk^ek  求最小的幂次是多少 n=le18 分析: 首先我们肯定是不可以枚举1e18的因 ...

  7. ACM ICPC 2011-2012 Northeastern European Regional Contest(NEERC)A ASCII Area

    A: 给你一个矩阵求'/' 和 '\' 围成的图形,简单签到题,有一些细节要考虑. 题解:一行一行的跑,遇到'/'和'\' 就加0.5, 在面积里面的'.' 就加1.用一个flag来判断是否在围住的图 ...

  8. $_SERVER 中HTTP_HOST 和 SERVER_NAME

    本来打算获取当前页面的url的   拼接时发现 $_SERVER['SERVER_NAME'] 并不是当前的url链接 打印整个$_SERVER  发现 [SERVER_NAME] => lvs ...

  9. 一、基础篇--1.1Java基础-String、StringBuilder、StringBuffer

    String.StringBuilder.StringBuffer 主要区别在两点上: 速度效率上对比:StringBuilder>StringBuffer>String 线程安全上来说: ...

  10. 三十八、python中反射介绍

    一.反射:根据字符串的形式去对象(某个模块)中去操作成员通过字符串的形式,导入模块通过字符串的形式,去模块中寻找指定的函数,并执行 1.__import__:用于字符串的形似执行导入模块 inp=in ...