public static String MD5(String text) { UTF8Encoding encoder = new UTF8Encoding(); var md5 = new MD5CryptoServiceProvider(); byte[] hashedDataBytes = md5.ComputeHash(encoder.GetBytes(text)); return System.Convert.ToBase64String(hashedDataBytes); }
// Create an md5 sum string of this string public static string GetMd5Sum(this string str) { // First we need to convert the string into bytes, which // means using a text encoder. Encoder enc = System.Text.Encoding.Unicode.GetEncoder(); // Create a buffer large enough to hold the string byte[] unicodeText = new byte[str.Length * 2]; enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true); // Now that we have a byte array we can ask the CSP to hash it MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(unicodeText); // Build the final string by converting each byte // into hex and appending it to a StringBuilder var sb = new StringBuilder(); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } // And return it return sb.ToString(); }
public void GuardarAdministrativo(String username, String password) { MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.ASCII.GetBytes(password); data = provider.ComputeHash(data); string md5 = string.Empty; for (int i = 0; i < data.Length; i++) { md5 += data[i].ToString("x2").ToLower(); } password = md5; var sql = new StringBuilder(); sql.AppendLine("insert into administradores (admin_username,admin_password) values (@username,@password)"); var parametros = new List<SqlParameter> { new SqlParameter { ParameterName = "username", SqlDbType =SqlDbType.VarChar, SqlValue = username }, new SqlParameter { ParameterName = "password", SqlDbType = SqlDbType.VarChar, SqlValue = password }, }; AccesoDatosSQL.Instance.Accesar.EjecutarConsultaSQL(sql.ToString(), parametros); if (AccesoDatosSQL.Instance.Accesar.HayError) { this.IsError = AccesoDatosSQL.Instance.Accesar.HayError; this.ErrorDescripcion = AccesoDatosSQL.Instance.Accesar.ErrorDescripcion; } }
/// <summary> /// 创建签名 /// </summary> /// <param name="text">明文</param> /// <param name="merchantKey">商户密钥</param> /// <returns>签名</returns> public static string CreateSign(string text, string merchantKey) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(text + "&Key=" + merchantKey)); return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { WxConfig = EasyWeixin.CommonAPIs.CommonApi.GetWxConfigResult(appid, appsecert, Request.Url.ToString()); QRCodeEncoder encoder = new QRCodeEncoder(); Bitmap bt = encoder.Encode(Request.Url.ToString()); var md5 = new MD5CryptoServiceProvider(); var start = Encoding.Default.GetBytes(Request.Url.ToString()); byte[] output = md5.ComputeHash(start); var result = BitConverter.ToString(output).Replace("-", ""); var direName = "~/tmpQrImg/"; var filename = direName + result + ".png"; var filepath = Server.MapPath(filename); if (!Directory.Exists(direName)) { Directory.CreateDirectory(direName); } if (!File.Exists(filename)) { bt.Save(filename, ImageFormat.Png); } ImgSrc = filename; } }
/// <summary> /// Gets the hash. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public static string GetHash(byte[] data) { // This is one implementation of the abstract class MD5. MD5 md5 = new MD5CryptoServiceProvider(); return BitConverter.ToString(md5.ComputeHash(data)).Replace("-", String.Empty); }
public static string EncryptString(string Message) { byte[] results; var hashProvider = new MD5CryptoServiceProvider(); var tripleDESAlgorithm = new TripleDESCryptoServiceProvider() { Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; tripleDESAlgorithm.Key = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(customPassPhrase)); byte[] dataToEncrypt = Encoding.UTF8.GetBytes(Message); try { ICryptoTransform encryptor = tripleDESAlgorithm.CreateEncryptor(); results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length); encryptor.Dispose(); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information tripleDESAlgorithm.Clear(); hashProvider.Clear(); } return Convert.ToBase64String(results); }
/// <summary> /// /// </summary> /// <param name="strToEncrypt"></param> /// <param name="key"></param> /// <returns></returns> /// <exception cref="Exception"></exception> public static string Encrypt(string strToEncrypt, string key) { try { TripleDESCryptoServiceProvider crypto = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider(); byte[] byteHash, byteBuff; string strTempKey = key; byteHash = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey)); hash = null; crypto.Key = byteHash; crypto.Mode = CipherMode.ECB; //CBC, CFB byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt); return Convert.ToBase64String(crypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length)); } catch (Exception ex) { throw new Exception("Error: " + ex.Message + ".\n Encryption Failed. Please try again."); } }
internal string Decrypt(string value) { MD5CryptoServiceProvider hashProvider = null; TripleDESCryptoServiceProvider provider = null; try { hashProvider = new MD5CryptoServiceProvider(); var hashPassPhrase = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(passPhrase)); provider = new TripleDESCryptoServiceProvider(); provider.Key = hashPassPhrase; provider.Mode = CipherMode.ECB; provider.Padding = PaddingMode.PKCS7; var dataToEncrypt = Convert.FromBase64String(value); var decryptor = provider.CreateDecryptor(); var results = decryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length); return Encoding.UTF8.GetString(results); } finally { if (provider != null) provider.Clear(); if (hashProvider != null) hashProvider.Clear(); } }
/// <summary> /// Returnes the string as MD5 hashing /// </summary> /// <param name="datastr"></param> /// <returns></returns> public static string EncryptString(string datastr) { HashAlgorithm mhash = new MD5CryptoServiceProvider(); string res = string.Empty; // the returning result // Convert the original string to array of Bytes byte[] bytValue = Encoding.UTF8.GetBytes(datastr); // Compute the Hash, returns an array of Bytes byte[] bytHash = mhash.ComputeHash(bytValue); mhash.Clear(); // convert the byte data to hex string values for (int i = 0; i < bytHash.Length; i++) { if (bytHash[i] < 16) { res += "0" + bytHash[i].ToString("x"); } else { res += bytHash[i].ToString("x"); } } return res; }
public static string Decrypt(string cipherText, string passPhrase) { try { TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider(); byte[] byteHash, byteBuff; string strTempKey = passPhrase; byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey)); objHashMD5 = null; objDESCrypto.Key = byteHash; objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB byteBuff = Convert.FromBase64String(cipherText); string strDecrypted = ASCIIEncoding.ASCII.GetString (objDESCrypto.CreateDecryptor().TransformFinalBlock (byteBuff, 0, byteBuff.Length)); objDESCrypto = null; return strDecrypted; } catch (Exception ex) { return null; } }
static public string MD5Encoding(string Data) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bdrr = System.Text.Encoding.UTF8.GetBytes(Data); byte[] barr = md5.ComputeHash(bdrr); return Convert.ToBase64String(barr); }
public static string GenerateIdentifier(string prefix, params string[] args) { string stringData = String.Join("|", args); byte[] data = Encoding.Unicode.GetBytes(stringData); // hash the data byte[] hash; using (MD5 md5 = new MD5CryptoServiceProvider()) { hash = md5.ComputeHash(data); } // build up the identifier StringBuilder identifier = new StringBuilder(35, 35); identifier.Append(prefix); // hard coded to 16 as that is the most bytes that can be used to meet the length requirements. SHA1 is 20 bytes. for (int i = 0; i < 16; i++) { identifier.Append(hash[i].ToString("X2", CultureInfo.InvariantCulture.NumberFormat)); } return identifier.ToString(); }
private byte[] xorData; // This table is used for encrypting the server->client stream #endregion Fields #region Constructors public GameEncryption(uint seed) { cipherTable = new byte[0x100]; // Set up the crypt key byte[] key = new byte[16]; key[0] = key[4] = key[8] = key[12] = (byte)((seed >> 24) & 0xff); key[1] = key[5] = key[9] = key[13] = (byte)((seed >> 16) & 0xff); key[2] = key[6] = key[10] = key[14] = (byte)((seed >> 8) & 0xff); key[3] = key[7] = key[11] = key[15] = (byte)(seed & 0xff); byte[] iv = new byte[0]; engine = new TwofishEncryption(128, ref key, ref iv, CipherMode.ECB, TwofishBase.EncryptionDirection.Decrypting); // Initialize table for ( int i = 0; i < 256; ++i ) cipherTable[i] = (byte)i; sendPos = 0; // We need to fill the table initially to calculate the MD5 hash of it refreshCipherTable(); // Create a MD5 hash of the twofish crypt data and use it as a 16-byte xor table // for encrypting the server->client stream. MD5 md5 = new MD5CryptoServiceProvider(); xorData = md5.ComputeHash(cipherTable); }
public static FilePiece parse_packet(byte[] packet) { if (packet.Length < 28){ // header isn't long enough return null; } Int32 data_length = System.BitConverter.ToInt32(packet, 0); if (data_length < 0){ // no data return null; } Int64 piece_number = System.BitConverter.ToInt64(packet, 4); if (piece_number < 0){ // can't have less than 0 piece number return null; } byte[] checksum = new byte[16]; for(int i = 12; i < 28; i++){ checksum[i] = packet[i]; } System.ArraySegment<byte> data_segment = new System.ArraySegment<byte>(packet, 28, packet.Length-28); byte[] data = data_segment.Array; // do a checksum MD5 check = new MD5CryptoServiceProvider(); byte[] sum = check.ComputeHash(data); if (sum.Equals(checksum)){ return null; // data checksum doesn't match } FilePiece piece = new FilePiece(piece_number, data); return piece; }
public JsonResult AdminRegister() { if (user.getAll().Count() == 0) { if (Request["Password"] == null) { return Json(new { info = false, message = "密码不能为空" }); } if (Request["UserName"] == null) { return Json(new { info = false, message = "用户名不能为空" }); } User u = new User(); MD5 md5 = new MD5CryptoServiceProvider(); byte[] mdpass = md5.ComputeHash(System.Text.Encoding.Default.GetBytes("password" + Request["Password"])); u.Password = System.Text.Encoding.Default.GetString(mdpass); u.UserName = Request["UserName"]; u.IsUse = true; u.Role_Id = 1; u.CreateTime = DateTime.Now; try { user.addUser(u); user.save(); } catch { return Json(new { info = false, message = "出错了" }); } return Json(new { info = true, message = "管理员账户创建成功" }); } else return Json(new { info = false, message = "出错了" }); }
public static string Md5StringFromString(string value) { MD5CryptoServiceProvider x = new MD5CryptoServiceProvider(); byte[] data = GeneralUtilities.HexAscii.ConvertToBytes(value); data = x.ComputeHash(data); return GeneralUtilities.HexAscii.ConvertToHexAscii(data); }
/// <summary> /// 16位加密 /// </summary> /// <param name="ConvertString"></param> /// <returns></returns> public static string GetMd5_16(string ConvertString) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); t2 = t2.Replace("-", ""); return t2; }
/// <summary> /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string /// </summary> /// <param name="cipherString">encrypted string</param> /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param> /// <returns></returns> public static string Decrypt(string cipherString, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherString); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); //Get your key from config file to open the lock! string key = SecurityKey; if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); }
public static string GetListHash(IEnumerable<string> hashes) { if (hashes == null) throw new ArgumentNullException("hashes"); string result; try { using (var s = new StreamWriter(new MemoryStream())) { foreach (var hash in hashes) s.Write(hash); s.Flush(); var bs = s.BaseStream; bs.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { md5.ComputeHash(bs); result = string.Join("", md5.Hash.Select(x => string.Format("{0:X2}", x)).ToArray()); } } } catch (Exception x) { throw new ApplicationException(string.Format("Could not hash the list of {0} strings: {1}", hashes.Count(), x.Message), x); } return result; }
/// <summary> /// Encrypt a string using dual encryption method. Return a encrypted cipher Text /// </summary> /// <param name="toEncrypt">string to be encrypted</param> /// <param name="useHashing">use hashing? send to for extra secirity</param> /// <returns></returns> public static string Encrypt(string toEncrypt, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); // Get the key from config file string key = SecurityKey; //System.Windows.Forms.MessageBox.Show(key); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); }
public static string Encrypt(String plainText ) { string encrypted = null; try { byte[] inputBytes = ASCIIEncoding.ASCII.GetBytes(plainText); byte[] pwdhash = null; MD5CryptoServiceProvider hashmd5; //generate an MD5 hash from the password. //a hash is a one way encryption meaning once you generate //the hash, you cant derive the password back from it. hashmd5 = new MD5CryptoServiceProvider(); pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key)); hashmd5 = null; // Create a new TripleDES service provider TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); tdesProvider.Key = pwdhash; tdesProvider.Mode = CipherMode.ECB; encrypted = Convert.ToBase64String( tdesProvider.CreateEncryptor().TransformFinalBlock(inputBytes, 0, inputBytes.Length)); } catch(Exception e) { string str = e.Message; throw ; } return encrypted; }
// Creates an MD5 hash of input public static string GetMD5(string s) { MD5 md5 = new MD5CryptoServiceProvider (); Byte[] bytes = ASCIIEncoding.Default.GetBytes (s); Byte[] encodedBytes = md5.ComputeHash (bytes); return BitConverter.ToString (encodedBytes).ToLower ().Replace ("-", ""); }
/// <summary> /// Decrypt the given string using the specified key. /// </summary> /// <param name="strEncrypted">The string to be decrypted.</param> /// <param name="key">The decryption key.</param> /// <returns>The decrypted string.</returns> /// <exception cref="Exception">Unexpected Exception</exception> public static string Decrypt(string strEncrypted, string key) { try { TripleDESCryptoServiceProvider decrypto = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider(); byte[] byteHash, byteBuff; string tempKey = key; byteHash = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(tempKey)); hash = null; decrypto.Key = byteHash; decrypto.Mode = CipherMode.ECB; //CBC, CFB byteBuff = Convert.FromBase64String(strEncrypted); string strDecrypted = ASCIIEncoding.ASCII.GetString(decrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length)); decrypto = null; return strDecrypted; } catch (Exception ex) { throw new Exception("Error: " + ex.Message + ".\n Decryption Failed. Please start over..!"); } }
public static string DecryptString(string message) { byte[] results; // Step 1. We hash the customPassPhrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below var hashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(customPassPhrase)); // Step 3. Setup the decoder var tripleDESAlgorithm = new TripleDESCryptoServiceProvider() { Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; tripleDESAlgorithm.Key = TDESKey; // Step 4. Convert the input string to a byte[] byte[] dataToDecrypt = Convert.FromBase64String(message); // Step 5. Attempt to decrypt the string try { ICryptoTransform decryptor = tripleDESAlgorithm.CreateDecryptor(); results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length); decryptor.Dispose(); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information tripleDESAlgorithm.Clear(); hashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return Encoding.UTF8.GetString(results); }
public static string Decrypt(string cypherString, bool useHasing) { byte[] keyArray; byte[] toDecryptArray = Convert.FromBase64String(cypherString); string key = "uzma"; if (useHasing) { MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider(); keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd.Clear(); } else { keyArray = UTF8Encoding.UTF8.GetBytes(key); } TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); tDes.Key = keyArray; tDes.Mode = CipherMode.ECB; tDes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tDes.CreateDecryptor(); try { byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); tDes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length); } catch (Exception ex) { throw ex; } }
/// <summary> /// MD5加密 返回纯字节 /// </summary> /// <param name="k"></param> /// <returns></returns> public static byte[] MD5Bytes(string sourceString) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] keyBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString)); md5.Clear(); return keyBytes; }
/// <summary> 从路径获取文件的MD5 </summary> public static string GetMD5FromFile(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); Security.Cryptography.MD5CryptoServiceProvider md5 = new Security.Cryptography.MD5CryptoServiceProvider(); byte[] md5byte = md5.ComputeHash(fs); int i, j; string md5Str = string.Empty; foreach (byte b in md5byte) { i = Convert.ToInt32(b); j = i >> 4; md5Str += Convert.ToString(j, 16); j = ((i << 4) & 0x00ff) >> 4; md5Str += Convert.ToString(j, 16); } fs.Close(); fs.Dispose(); return(md5Str); }
/// <summary> /// 用MD5算法对字符串加密 /// </summary> /// <param name="strOriginal"></param> /// <returns></returns> public static byte[] Md5Encrypt(string strOriginal) { var encoder = new UTF8Encoding(); var md5Hasher = new MD5CryptoServiceProvider(); byte[] bytePassword = md5Hasher.ComputeHash(encoder.GetBytes(strOriginal)); return bytePassword; }
/// <summary> /// Encrypts to provided string parameter. /// </summary> public static string Encrypt(string s) { if (s == null || s.Length == 0) return string.Empty; string result = string.Empty; try { byte[] buffer = Encoding.ASCII.GetBytes(s); TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey)); des.IV = IV; result = Convert.ToBase64String( des.CreateEncryptor().TransformFinalBlock( buffer, 0, buffer.Length)); } catch { throw; } return result; }
private void button1_Click(object sender, EventArgs e) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] palindata = Encoding.Default.GetBytes(txtyuan.Text); byte[] encryptdata = md5.ComputeHash(palindata); txtjiami.Text = Convert.ToBase64String(encryptdata); }
/// <summary> 获取字节流的md5值 </summary> public static string GetMD5FromFileStream(byte[] buffer) { Security.Cryptography.MD5CryptoServiceProvider md5 = new Security.Cryptography.MD5CryptoServiceProvider(); byte[] md5byte = md5.ComputeHash(buffer); int i, j; string md5Str = string.Empty; foreach (byte b in md5byte) { i = Convert.ToInt32(b); j = i >> 4; md5Str += Convert.ToString(j, 16); j = ((i << 4) & 0x00ff) >> 4; md5Str += Convert.ToString(j, 16); } return(md5Str); }
/// <summary> /// Giải mã chuỗi mã hóa /// </summary> /// <param name="toDecrypt">Chuỗi cần giải mã</param> /// <param name="key">khóa giải mã</param> /// <param name="useHashing">Giải mã chuỗi mã hóa MD5 hay mã hóa UTF8 bình thường</param> /// <returns>Chuỗi giải mã</returns> public static string _mDecrypt(string toDecrypt, string key, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); if (useHashing) { System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else { keyArray = UTF8Encoding.UTF8.GetBytes(key); } System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = System.Security.Cryptography.CipherMode.ECB; tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(UTF8Encoding.UTF8.GetString(resultArray)); }
public static string MD5(string password, bool campatiblePhp = false) { byte[] textBytes = System.Text.Encoding.Default.GetBytes(password); System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler; cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = cryptHandler.ComputeHash(textBytes); string ret = ""; foreach (byte a in hash) { if (campatiblePhp && a < 16) { ret += "0" + a.ToString("x"); } else { ret += a.ToString("x"); } } return(ret); }
/// <summary> /// 32位标准MD5 /// </summary> /// <param name="data">要加密的数据</param> /// <returns>32位 MD5字符串</returns> public static string MD5(string data) { byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(data); System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler; cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = cryptHandler.ComputeHash(textBytes); string ret = ""; foreach (byte a in hash) { if (a < 16) { ret += "0" + a.ToString("x"); } else { ret += a.ToString("x"); } } return(ret); }
public static string MD5_File_Enconding(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch (Exception ex) { throw new Exception("MD5_File_Enconding() fail,error:" + ex.Message); } }
private string Encript(string sPassword) { try { System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(sPassword); bs = x.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } return(s.ToString()); } catch (Exception ex) { throw ex; // } }
/// <summary> /// 计算文件的MD5值 https://blog.csdn.net/ToToTofu/article/details/88220337 /// </summary> public static string md5file(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } }
/// <summary> /// File MD5 /// </summary> /// <param name="filepath"></param> /// <returns></returns> public static string FileMD5(string filepath) { byte[] retVal = null; using (FileStream file = new FileStream(filepath, FileMode.Open)) { using (System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider()) { retVal = md5.ComputeHash(file); } file.Close(); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); }
public byte[] HashByte(byte[] bytes, int Algorithm) { byte[] hashBytes = null; if (Algorithm == 0) //MD5 { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); hashBytes = md5.ComputeHash(bytes); } else if (Algorithm == 1) //SHA-1 { //SHA-1 // Convert the encrypted bytes back to a string (base 16) var shs = new SHA1CryptoServiceProvider(); hashBytes = shs.ComputeHash(bytes); } else { return(null); } return(hashBytes); }
private string MD5Stream(System.IO.Stream stream) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = null; string resule = string.Empty; try { md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(stream); resule = System.BitConverter.ToString(hash); resule = resule.Replace("-", ""); } finally { if (md5 != null) { md5.Dispose(); } } return(resule); }
public string md5(string sifre) { try { System.Security.Cryptography.MD5CryptoServiceProvider sifreleme = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sifre); byte[] hash = sifreleme.ComputeHash(bytes); int kapasite = (hash.Length * 2 + (hash.Length / 8)); System.Text.StringBuilder sb = new System.Text.StringBuilder(kapasite); int I = 0; for (I = 0; I <= hash.Length - 1; I++) { sb.Append(BitConverter.ToString(hash, I, 1)); } return(sb.ToString()); } catch (Exception ex) { return("0"); } }
public static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch (Exception ex) { return(""); } }
/// <summary> /// 获取文件MD5值(32位大写) /// </summary> /// <param name="strFilePath">文件路径</param> /// <returns>文件MD5值(32位大写)</returns> public static string FileMD5Encrypt_32Upper(string strFilePath) { try { FileStream fileStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] byteHash = md5.ComputeHash(fileStream); fileStream.Close(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < byteHash.Length; i++) { stringBuilder.Append(byteHash[i].ToString("X2")); } return(stringBuilder.ToString()); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); return(string.Empty); } }
/// <summary> /// 获取文件MD5值 /// </summary> /// <param name="fileName">文件绝对路径</param> /// <returns>MD5值</returns> public static string GetMD5HashFromFile(Stream InputStream) { try { //FileStream file = new FileStream(fileName, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(InputStream); //file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } }
//文件md5 public static string MD5File(string filePath) { if (!File.Exists(filePath)) { return(""); } // MD5 md5 = new MD5CryptoServiceProvider(); // byte[] data = System.Text.Encoding.Default.GetBytes(filePath);//将字符编码为一个字节序列 // byte[] md5data = md5.ComputeHash(data);//计算data字节数组的哈希值 // md5.Clear(); // string str = ""; // for (int i = 0; i < md5data.Length; i++) // { // str += md5data[i].ToString("x2"); // } // return str; try { FileStream file = new FileStream(filePath, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch (Exception ex) { UpdateLog.ERROR_LOG("calc md5 fail : " + ex.Message + "\n" + ex.StackTrace); UpdateLog.EXCEPTION_LOG(ex); } return(""); }
/// <summary> /// Untuk mengenkripsi string menggunakan algoritma MD5 /// </summary> /// <param name="plainText">String yang ingin dienkripsi</param> /// <returns></returns> public static string GetMD5Hash(string plainText, string key = "") { if (key.Length > 0) { plainText += key; } var x = new System.Security.Cryptography.MD5CryptoServiceProvider(); var bs = System.Text.Encoding.UTF8.GetBytes(plainText); bs = x.ComputeHash(bs); var s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } string password = s.ToString(); return(password); }
public static string PHPMd5Encode(string input) { string Hashpass = input; // UTF7 Version (probably won't work across languages) System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); UTF7Encoding encoder = new UTF7Encoding(); Byte[] bytes; bytes = encoder.GetBytes(Hashpass); bytes = md5.ComputeHash(bytes); string strHex = string.Empty; foreach (byte b in bytes) { strHex = string.Concat(strHex, String.Format("{0:x2}", b)); } return(strHex); }
public static string EncryptMD5(string txt) { if (string.IsNullOrEmpty(txt)) { return(null); } var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var encoder = new UTF8Encoding(); var originalBytes = encoder.GetBytes(txt); var encodedBytes = md5.ComputeHash(originalBytes); //return encodedBytes // .Select(x => x.ToString("X2")) // .ToString(); return(BitConverter .ToString(encodedBytes) .Replace("-", "") .ToLower()); }
public static string Md5Sum(string strToEncrypt) { Debug.Log(">>> before MD5 string " + strToEncrypt); System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); // encrypt bytes System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string hashString = ""; for (int i = 0; i < hashBytes.Length; i++) { hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } Debug.Log(">>> after MD5 " + hashString); return(hashString.PadLeft(32, '0')); }
public static string GetFileMD5(string fileName) { try { using (FileStream file = new FileStream(fileName, FileMode.Open)) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } } catch (Exception ex) { throw new Exception($"Get {fileName} md5 fail {ex.Message}"); } }
public ActionResult Register(UserAccount userAccount) { using (OurDbContext db = new OurDbContext()) { System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(userAccount.Password); bs = x.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } userAccount.Password = s.ToString(); db.userAccount.Add(userAccount); db.SaveChanges(); } ModelState.Clear(); ViewBag.Message = userAccount.Email + " succesfully registered."; return(View()); }
public static string Decrypt(string cipherString) { try { byte[] keyArray; //get the byte code of the string byte[] toEncryptArray = Convert.FromBase64String(cipherString); string key = MD5Salt(); //if hashing was used get the hash code with regards to your key System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); //release any resource held by the MD5CryptoServiceProvider hashmd5.Clear(); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. //We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock( toEncryptArray, 0, toEncryptArray.Length); //Release resources held by TripleDes Encryptor tdes.Clear(); //return the Clear decrypted TEXT return(UTF8Encoding.UTF8.GetString(resultArray)); } catch { return(""); } }
/// <summary> /// MD5X编码 /// </summary> /// <param name="password"></param> /// <returns></returns> public static string MD5XEncode(string password) { string result; if (string.IsNullOrEmpty(password) || string.IsNullOrWhiteSpace(password)) { result = string.Empty; } else { UnicodeEncoding unicodeEncoding = new UnicodeEncoding(); byte[] bytes = unicodeEncoding.GetBytes(password); System.Security.Cryptography.MD5CryptoServiceProvider mD5CryptoServiceProvider = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] value = mD5CryptoServiceProvider.ComputeHash(bytes); string text = BitConverter.ToString(value); text += "ZX"; System.Security.Cryptography.SHA1 sHA = new System.Security.Cryptography.SHA1CryptoServiceProvider(); value = sHA.ComputeHash(unicodeEncoding.GetBytes(text)); result = BitConverter.ToString(value).Replace("-", string.Empty); } return(result); }
/// <summary> /// Takes a string and generates a hash value of 16 bytes. /// </summary> /// <param name="str">The string to be hashed</param> /// <param name="passwordFormat">Selects the hashing algorithm used. Accepted values are "sha1" and "md5".</param> /// <returns>A hex string of the hashed password.</returns> public static string EncodeString(string str, string passwordFormat) { if (str == null) { return(null); } ASCIIEncoding AE = new ASCIIEncoding(); byte[] result; switch (passwordFormat) { case "sha1": SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); result = sha1.ComputeHash(AE.GetBytes(str)); break; case "md5": MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); result = md5.ComputeHash(AE.GetBytes(str)); break; default: throw new ArgumentException("Invalid format value. Accepted values are 'sha1' and 'md5'.", "passwordFormat"); } // Loop through each byte of the hashed data // and format each one as a hexadecimal string. StringBuilder sb = new StringBuilder(16); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("x2")); } return(sb.ToString()); }
/// <summary> /// 获取文件MD5值 /// </summary> /// <param name="fileName">文件</param> /// <returns>文件MD5值</returns> public static string GetMD5HashFromFile(string fileName) { if (!File.Exists(fileName)) { return(""); } try { FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb.ToString()); } catch { } return(""); }
// 计算文件的MD5值 public static string Md5File(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); string size = fs.Length / 1024 + ""; //Debug.Log("当前文件的大小: " + file + "===>" + (fs.Length / 1024) + "KB"); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return(sb + "|" + size); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } }
public static string MD5(string password) { byte[] textBytes = System.Text.Encoding.Default.GetBytes(password); try { System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler; cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = cryptHandler.ComputeHash(textBytes); string ret = ""; foreach (byte a in hash) { if (a < 16) ret += "0" + a.ToString("x"); else ret += a.ToString("x"); } return ret; } catch { throw; } }
/// <summary> /// 获取加密后的字符串 /// </summary> /// <param name="password">密码明文</param> /// <returns>加密后的密文</returns> public static String getEncryptedPwd(String password) { //声明加密后的口令数组变量 byte[] pwd = null; //随机数生成器 Random random = new Random(); //声明盐数组变量 byte[] salt = new byte[SALT_LENGTH]; //将随机数放入盐变量中 random.NextBytes(salt); //声明消息摘要对象 System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); pwd = System.Text.Encoding.UTF8.GetBytes(password); var bb = salt.Concat(pwd); byte[] resultEncrypt = md5CSP.ComputeHash(salt.Concat(pwd).ToArray()); return(byteToHexString(resultEncrypt.Concat(salt).ToArray())); }
/// <summary> /// MD5加密(32位小写) /// </summary> /// <param name="strSource">需要加密的明文</param> /// <returns>返回32位加密结果</returns> public static string Get32_MD5Lower(string strSource, Encoding sEncode) { if (sEncode == null) { sEncode = Encoding.UTF8; } //new System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //获取密文字节数组 byte[] bytResult = md5.ComputeHash(sEncode.GetBytes(strSource)); //转换成字符串,并取9到25位 //string strResult = BitConverter.ToString(bytResult, 4, 8); //转换成字符串,32位 string strResult = BitConverter.ToString(bytResult); //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉 strResult = strResult.Replace("-", ""); return(strResult.ToLower()); }