/// <summary> /// MD5加密 /// </summary> /// <param name="content">要加密的内容,如果是一个对象必须要实现<see cref="SerializableAttribute"/></param> /// <returns></returns> public static string EncryptMD5(object content) { if (StringUtil.IsNullOrEmpty(content)) { return(string.Empty); } MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); string result = string.Empty; try { byte[] resultBytes = provider.ComputeHash(SerializeUtil.ToBinary(content)); for (int i = 0; i < resultBytes.Length; i++) { result += resultBytes.ElementAt(i).ToString("x2"); } } catch (Exception ex) { throw ex; } finally { provider.Dispose(); } return(result); }
/// <summary> /// MD5加密 /// <para>将一个对象用MD5的方式进行加密</para> /// </summary> /// <param name="content">要加密的对象</param> /// <returns></returns> public static string EncryptMD5(object content) { //如果要加密的对象是空,就无法加密,直接返回空 if (StringUtil.IsEmpty(content)) { return(string.Empty); } //定义一个MD5加密器 MD5CryptoServiceProvider manager = new MD5CryptoServiceProvider(); //初始化返回值 string result = string.Empty; try { //进行加密 byte[] resultBytes = manager.ComputeHash(content.ToBytes()); //将加密后的字节转为二进制 for (int i = 0; i < resultBytes.Length; i++) { result += resultBytes[i].ToString("x2"); } } catch (Exception ex) { //如果发生异常则认为加密失败 LogUtil.WriteException(ex.ToString()); } finally { manager.Dispose(); } return(result); }
// 获取文件MD5 private string GetMd5(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); MD5 md5 = new MD5CryptoServiceProvider(); byte[] data = new byte[1]; try { data = md5.ComputeHash(fs); } finally { md5.Dispose(); fs.Close(); } StringBuilder sb = new StringBuilder(data.Length); for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString("x2")); } return(sb.ToString()); }
/// <summary> /// Do not use it /// </summary> /// <param name="originalPassword"></param> /// <returns></returns> public string EncodePassword(string originalPassword) { //Declarations Byte[] originalBytes; Byte[] encodedBytes; MD5 md5 = null; try { //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password) md5 = new MD5CryptoServiceProvider(); originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword); encodedBytes = md5.ComputeHash(originalBytes); //Convert encoded bytes back to a 'readable' string return(BitConverter.ToString(encodedBytes)); } catch (Exception ex) { Library.Classes.Logger.Error(ex);; } finally { md5.Dispose(); } return(""); }
public string GetFileChecksum() { if (string.IsNullOrWhiteSpace(FilePath)) { throw new ArgumentException("检验器校验目标文件路径为空"); } FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read); try { MD5 md5 = new MD5CryptoServiceProvider(); //创建SHA1对象 byte[] md5Bytes = md5.ComputeHash(file); //Hash运算 md5.Dispose(); //释放当前实例使用的所有资源 file.Dispose(); string result = BitConverter.ToString(md5Bytes); //将运算结果转为string类型 result = result.Replace("-", ""); return(result); } catch { throw new ArgumentException("校验器初始化失败,请尝试根据下面的步骤:\n" + "1、单击“开始,运行”键入“gpedit.msc”,然后单击“确定”。\n" + "2、依次展开“计算机配置”,展开“Windows设置”,展开“安全设置”,展开“本地策略”,然后单击“安全选项”\n" + "3、在右窗格中, 双击“系统加密:”使用“FIPS 兼容的算法来加密,散列,和签名”,单击“禁用”,然后单击“确定”。"); } }
/// <summary> /// Encrypts the string to a byte array using the MD5 Encryption Algorithm. /// <see cref="System.Security.Cryptography.MD5CryptoServiceProvider"/> /// </summary> /// <param name="toEncrypt">System.String. Usually a password.</param> /// <returns>System.Byte[]</returns> private static byte[] MD5Encryption(string toEncrypt) { // Create instance of the crypto provider. MD5CryptoServiceProvider mMD5CryptoServiceProvider = null; try { mMD5CryptoServiceProvider = new MD5CryptoServiceProvider(); // Create a Byte array to store the encryption to return. byte[] mRetBytes = null; // Required UTF8 Encoding used to encode the input value to a usable state. UTF8Encoding mTextEncoder = new UTF8Encoding(); // let the show begin. mRetBytes = mMD5CryptoServiceProvider.ComputeHash(mTextEncoder.GetBytes(toEncrypt)); // return the hased bytes to the calling method. return(mRetBytes); } catch (Exception) { throw; } finally { if (mMD5CryptoServiceProvider != null) { mMD5CryptoServiceProvider.Dispose(); } } }
/// <summary> /// Decrypt the given string using the specified key. /// </summary> /// <param name="textToDecrypt">The string to be encrypted</param> /// <param name="SecurePhrase">The Secure Phrase used to decryption</param> /// <returns>The Decrypted string.</returns> public static string Decrypt(string textToDecrypt, string SecurePhrase) { try { var oTripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider(); var oMD5CryptoServiceProvider = new MD5CryptoServiceProvider(); byte[] byteHash, byteBuff; byteHash = oMD5CryptoServiceProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(SecurePhrase)); oTripleDESCryptoServiceProvider.Key = byteHash; oTripleDESCryptoServiceProvider.Mode = CipherMode.ECB; //CBC, CFB byteBuff = Convert.FromBase64String(textToDecrypt); string Aux = ASCIIEncoding.ASCII.GetString(oTripleDESCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length)); oTripleDESCryptoServiceProvider.Dispose(); oMD5CryptoServiceProvider.Dispose(); return(Aux); } catch (Exception ex) { return("Framework.Cryptography: " + ex.Message); } }
private void BtnPwd_Click(object sender, EventArgs e) { if (txtBoxOriginalPwd.TextLength > 0 && txtBoxNewPwd1.TextLength > 0 && txtBoxNewPwd2.TextLength > 0) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] output = md5.ComputeHash(Encoding.Default.GetBytes(txtBoxOriginalPwd.Text.Trim())); string strValue = BitConverter.ToString(output).Replace("-", ""); if (strValue == m_db.GetPassWord()) { if (txtBoxNewPwd1.Text != txtBoxNewPwd2.Text) { MessageBox.Show("两次输入的新密码不一致!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { output = md5.ComputeHash(Encoding.Default.GetBytes(txtBoxNewPwd1.Text.Trim())); strValue = BitConverter.ToString(output).Replace("-", ""); if (m_db.SetPassWord(strValue) == 1) { MessageBox.Show("修改管理员密码成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("修改管理员密码失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } else { MessageBox.Show("原密码不正确!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } md5.Dispose(); } }
public static string Encrypt(string mString, string mKey) { if (mString == "") { return(mString); } TripleDESCryptoServiceProvider cryptdes3 = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider(); try { cryptdes3.Key = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(mKey)); cryptdes3.Mode = CipherMode.ECB; ICryptoTransform enc = cryptdes3.CreateEncryptor(); byte[] buff = ASCIIEncoding.ASCII.GetBytes(mString); return(Convert.ToBase64String(enc.TransformFinalBlock(buff, 0, buff.Length))); } catch (Exception ex) { throw new Exception("Bad Data", ex); } finally { cryptdes3.Dispose(); hash.Dispose(); } }
/// <summary> /// Encrypt a string using a static key and TripleDES /// </summary> /// <param name="data">The string that needs to be encrypted</param> /// <returns>Encrypted string</returns> public static string BBSEncrypt(string data) { if (Testing) { return(data); } else { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); byte[] keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes("bbspabx")); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider { Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, Key = keyArray }; try { ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length); tdes.Clear(); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); } catch (Exception ex) { MessageBox.Show(ex.Message); return(ex.Message); } finally { hashmd5.Dispose(); tdes.Dispose(); } } }
public static bool IsValidAccount(string UserID, string Password) { User User = GetBy(UserID); if (User == null) { return(false); } else { MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Password)); md5.Dispose(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t.Length; i++) { sb.Append(t[i].ToString("X2")); } string sql = "select loginid from [dbo].[HrmResource] where loginid = '" + UserID + "' and password = '******' "; object loginid = Common.SQLHelper.ExecuteScalarToObject(Common.SQLHelper.OA_strConn, CommandType.Text, sql, null); return(loginid == null ? false : true); } }
/// <summary> /// Computes the hash for the specified stream and compares /// it to the value in this object. CRC hashes are not supported /// because there is no built-in support in the .net framework and /// a CRC implementation exceeds the scope of this project. If you /// attempt to Verify() a CRC hash a NotImplemented() exception will /// be thrown. /// </summary> /// <param name="istream">The stream to compute the hash for</param> /// <returns>True if the computed hash matches what's stored in this object.</returns> public bool Verify(Stream istream) { if (IsValid) { HashAlgorithm hashAlg = null; switch (m_algorithm) { case FtpHashAlgorithm.SHA1: hashAlg = new SHA1CryptoServiceProvider(); break; #if !NET2 case FtpHashAlgorithm.SHA256: hashAlg = new SHA256CryptoServiceProvider(); break; case FtpHashAlgorithm.SHA512: hashAlg = new SHA512CryptoServiceProvider(); break; #endif case FtpHashAlgorithm.MD5: hashAlg = new MD5CryptoServiceProvider(); break; case FtpHashAlgorithm.CRC: throw new NotImplementedException("There is no built in support for computing CRC hashes."); default: throw new NotImplementedException("Unknown hash algorithm: " + m_algorithm.ToString()); } try { byte[] data = null; string hash = ""; data = hashAlg.ComputeHash(istream); if (data != null) { foreach (byte b in data) { hash += b.ToString("x2"); } return(hash.ToUpper() == m_value.ToUpper()); } } finally { #if !NET2 // .NET 2.0 doesn't provide access to Dispose() for HashAlgorithm if (hashAlg != null) { hashAlg.Dispose(); } #endif } } return(false); }
/// <summary> /// Returns the ICryptoTransform interface used to perform the encryption. /// </summary> /// <param name="keystring">This is the same as the "password" of the PBEWithMD5AndDES method.</param> /// <param name="salt">This is the salt used to provide extra security to the algorythim.</param> /// <param name="iterationsMD5">Fill out iterationsMd5 later.</param> /// <param name="segments">Fill out segments later.</param> /// <returns>ICryptoTransform interface used to perform the encryption.</returns> public ICryptoTransform Generate(string keystring, byte[] salt, int iterationsMD5, int segments) { // MD5 bytes int hashLength = 16; // to store contatenated Mi hashed results byte[] keyMaterial = new byte[hashLength * segments]; // --- get secret password bytes ---- byte[] passwordBytes; passwordBytes = Encoding.UTF8.GetBytes(keystring); // --- contatenate salt and pswd bytes into fixed data array --- byte[] data00 = new byte[passwordBytes.Length + salt.Length]; // copy the pswd bytes Array.Copy(passwordBytes, data00, passwordBytes.Length); // concatenate the salt bytes Array.Copy(salt, 0, data00, passwordBytes.Length, salt.Length); // ---- do multi-hashing and contatenate results D1, D2 ... into keymaterial bytes ---- MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = null; // fixed length initial hashtarget byte[] hashtarget = new byte[hashLength + data00.Length]; for (int j = 0; j < segments; j++) { // ---- Now hash consecutively for iterationsMd5 times ------ if (j == 0) { // initialize result = data00; } else { Array.Copy(result, hashtarget, result.Length); Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); result = hashtarget; } for (int i = 0; i < iterationsMD5; i++) { result = md5.ComputeHash(result); } // contatenate to keymaterial Array.Copy(result, 0, keyMaterial, j * hashLength, result.Length); } md5.Dispose(); Array.Copy(keyMaterial, 0, this.key, 0, 8); Array.Copy(keyMaterial, 8, this.iv, 0, 8); return(this.Encryptor); }
public static string GetMd5String(string str) { MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); byte[] buffer = provider.ComputeHash(Encoding.UTF8.GetBytes(str)); provider.Dispose(); return(BitConverter.ToString(buffer).Replace("-", "")); }
public static string GetMd5String(byte[] bs) { MD5 md = new MD5CryptoServiceProvider(); byte[] buffer = md.ComputeHash(bs); md.Dispose(); return(BitConverter.ToString(buffer).Replace("-", "")); }
public static byte[] GetMd5Bytes(string str) { MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); byte[] buffer = provider.ComputeHash(Encoding.UTF8.GetBytes(str)); provider.Dispose(); return(buffer); }
public static string GetMd5(string input) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input)); md5.Dispose(); return(BitConverter.ToString(bytes).ToUpper().Replace("-", "")); }
/// <summary> /// MD5加密(加密后转为大写) /// </summary> /// <param name="encryptString">原字符串</param> /// <returns>加密后的字符串</returns> public static string GetMD5(string encryptString) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] byteHash = md5Hasher.ComputeHash(Encoding.Default.GetBytes(encryptString)); md5Hasher.Dispose(); return(Convert.ToBase64String(byteHash)); }
public static byte[] GetMd5Bytes(byte[] bs) { MD5 md = new MD5CryptoServiceProvider(); byte[] buffer = md.ComputeHash(bs); md.Dispose(); return(buffer); }
/// <summary> /// Encodes a string with the MD5 hash function /// </summary> public static string ToMD5(this string input) { using (var cryptoProvider = new MD5CryptoServiceProvider()) { var hash = cryptoProvider.ComputeHash(Encoding.UTF8.GetBytes(input)); cryptoProvider.Dispose(); return(string.Join("", hash.Select(b => b.ToString("x2")).ToArray())); } }
/// <summary> /// 生成MD5摘要 /// </summary> /// <param name="realText">数据源</param> /// <returns>摘要</returns> public static byte[] MakeMD5(byte[] realText) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); byte[] keyhash = hashmd5.ComputeHash(realText); hashmd5.Dispose(); hashmd5 = null; return(keyhash); }
/// <summary> /// MD5算法加密 /// </summary> /// <param name="value">字符串</param> /// <returns>加密后的字符串</returns> public static string MD5Encrypt(this string value) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] fromData = Encoding.UTF8.GetBytes(value); byte[] toData = md5.ComputeHash(fromData); md5.Dispose(); return(Convert.ToBase64String(toData)); }
/// <summary> /// MD5加密 /// </summary> /// <param name="source"></param> /// <returns></returns> public static string MD5Encrypt(string source) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); UTF8Encoding encoding = new UTF8Encoding(); var hashedBytes = md5Hasher.ComputeHash(encoding.GetBytes(source)); md5Hasher.Dispose(); return(Convert.ToBase64String(hashedBytes)); }
/// <summary> /// MD5加密(返回16位加密串) /// </summary> /// <param name="input"></param> /// <param name="encode"></param> /// <returns></returns> public static string MD5Encrypt16(string input, Encoding encode) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string result = BitConverter.ToString(md5.ComputeHash(encode.GetBytes(input)), 4, 8); result = result.Replace("-", ""); md5.Dispose(); return(result); }
public static string GetFileMd5(FileInfo fileinfo) { FileStream inputStream = new FileStream(fileinfo.FullName, FileMode.Open, FileAccess.Read); MD5 md = new MD5CryptoServiceProvider(); byte[] buffer = md.ComputeHash(inputStream); md.Dispose(); inputStream.Close(); return(BitConverter.ToString(buffer).Replace("-", "")); }
public static string GetMD5PWD(string pwd) { //新建对象 MD5 mD5 = new MD5CryptoServiceProvider(); //字符转字节组,计算HASH值 byte[] date = mD5.ComputeHash(Encoding.Default.GetBytes(pwd)); mD5.Dispose(); return(Convert.ToBase64String(date)); }
// // Summary: // Releases the unmanaged resources used by the System.Security.Cryptography.HashAlgorithm // and optionally releases the managed resources. // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. protected override void Dispose(bool disposing) { _md5.Dispose(); _sha1.Dispose(); if (HashValue != null) { Array.Clear(HashValue, 0, 36); } HashValue = null; }
/// <summary> /// 获取由MD5加密的字符串 /// </summary> /// <param name="text"></param> /// <returns></returns> public static String EncryptToMD5(String text) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); Byte[] bytes = Encoding.UTF8.GetBytes(text); Byte[] result = md5.ComputeHash(bytes, 0, bytes.Length); md5.Clear(); md5.Dispose(); return(Convert.ToBase64String(result)); }
public string rawHash(ref string Input) { provider = new MD5CryptoServiceProvider(); byte[] workData = Configuration.charTable.GetBytes(Input); workData = provider.ComputeHash(workData); provider.Dispose(); return(Configuration.charTable.GetString(workData)); }
/// <summary> /// This method is used to convert the plain text to Encrypted/Un-Readable Text format. /// </summary> /// <param name="PlainText">Plain Text to Encrypt before transferring over the network.</param> /// <returns>Cipher Text</returns> public string EncryptPassword(string input) { string hash = string.Empty; MD5CryptoServiceProvider objMD5CryptoService = null; TripleDESCryptoServiceProvider objTripleDESCryptoService = null; try { objStringBuilder.AppendLine("Begin: Utility-Common-EncryptPassword using MD5"); //Getting the bytes of Input String. byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(input); objMD5CryptoService = new MD5CryptoServiceProvider(); //Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value. byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey)); //De-allocatinng the memory after doing the Job. objMD5CryptoService.Clear(); objTripleDESCryptoService = new TripleDESCryptoServiceProvider(); //Assigning the Security key to the TripleDES Service Provider. objTripleDESCryptoService.Key = securityKeyArray; //Mode of the Crypto service is Electronic Code Book. objTripleDESCryptoService.Mode = CipherMode.ECB; //Padding Mode is PKCS7 if there is any extra byte is added. objTripleDESCryptoService.Padding = PaddingMode.PKCS7; var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor(); //Transform the bytes array to resultArray byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length); //Releasing the Memory Occupied by TripleDES Service Provider for Encryption. objTripleDESCryptoService.Clear(); //Convert and return the encrypted data/byte into string format. hash = Convert.ToBase64String(resultArray, 0, resultArray.Length); } catch (Exception error) { LogManager.LogManagerInstance.WriteErrorLog(error); } finally { objMD5CryptoService.Dispose(); objTripleDESCryptoService.Dispose(); objStringBuilder.AppendLine("End: Utility-Common-EncryptDecrypt-EncryptString"); LogManager.LogManagerInstance.WriteTraceLog(objStringBuilder); } return(hash); }