public String SHA1CheckSum(string input_file) { if (!File.Exists(@input_file)) { return(String.Empty); } SHA1 sha1 = SHA1.Create(); StringBuilder sb = new StringBuilder(); try { FileStream input_f = File.OpenRead(input_file); byte[] out_bytes = sha1.ComputeHash(input_f); foreach (byte o in out_bytes) { sb.Append(o.ToString("x2")); } sha1.Clear(); input_f.Close(); } catch { return(String.Empty); } return(sb.ToString()); }
private void closeChatLogWriter() { if (this.chatLogOut != null) { MD5 md5 = MD5.Create(); SHA1 sha1 = SHA1Managed.Create(); string md5Res; string sha1Res; string fileText; byte[] fileBytes; this.chatLogOut.WriteLine("End of chat log at {0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); this.chatLogOut.Close(); this.chatLogOut = null; //Write the checksum fileText = File.ReadAllText(this.chatLogFilename); fileBytes = Encoding.GetEncoding("UTF-8").GetBytes(fileText); md5Res = BitConverter.ToString(md5.ComputeHash(fileBytes)).Replace("-", "").ToLowerInvariant(); sha1Res = BitConverter.ToString(sha1.ComputeHash(fileBytes)).Replace("-", "").ToLowerInvariant(); this.chatLogOut = new StreamWriter(this.chatLogFilename, false, System.Text.Encoding.UTF8); this.chatLogOut.WriteLine("MD5 Hash: " + md5Res); this.chatLogOut.WriteLine("SHA-1 Hash: " + sha1Res); this.chatLogOut.Write(fileText); this.chatLogOut.Close(); this.chatLogOut = null; this.chatLogFilename = null; md5.Clear(); sha1.Clear(); } }
/// <summary> /// 基于Sha1的自定义加密字符串方法:输入一个字符串,返回一个由40个字符组成的十六进制的哈希散列(字符串)。 /// </summary> /// <param name="password">密码</param> /// <returns>加密密码</returns> public static string Sha1(string password) { var result = string.Empty; if (!string.IsNullOrEmpty(password)) { #region 方法3 //1.创建一个MD5对象 SHA1 sha1 = SHA1.Create(); //2.把字符串变一个byte[] byte[] buffer = Encoding.UTF8.GetBytes(password); //3.将一个byte[]通过SHA1计算到一个新的byte[],新的byte[]就是计算SHA1后的结果。 byte[] sha1Buffer = sha1.ComputeHash(buffer); //释放资源 sha1.Clear(); //sha1.Dispose();//释放当前实例使用的所有资源 //4.将计算后的结果直接显示为字符串 var sb = Pool.StringBuilder.Get(); foreach (var t in sha1Buffer) { //x2:把每个数字转换为16进制,并保留两位数字。 sb.Append(t.ToString("x2")); } result = sb.Put(); #endregion } return(result); }
//public static string Key2Base( string key) //{ // //System.Text.Encoder lvEncoder=; // byte[] buffChar = Encoding.Unicode.GetBytes(key); // return Convert.ToBase64String(buffChar); //} //public static string Base2Key( string b64) //{ // return Encoding.Unicode.GetString(Convert.FromBase64String(b64)); //} public static string TxdSHA1(string strSource, int versionStr) { if (String.IsNullOrEmpty(strSource)) { return(""); } string strResult = ""; if (versionStr < 2) { SHA1 lvsha1 = SHA1.Create(); byte[] bytResult = lvsha1.ComputeHash(System.Text.Encoding.Unicode.GetBytes(strSource)); lvsha1.Clear(); //转换成字符串,并取9到25位 strResult = BitConverter.ToString(bytResult); //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉 strResult = strResult.Replace("-", ""); } if (strResult == "") { throw new Exception("可能由于版本问题。口令无法传递。"); } return(strResult); }
private static void DecryptPrivateKey(ref FileData fileData) { switch (fileData.privateKeyAlgorithm) { case PrivateKeyAlgorithm.None: return; case PrivateKeyAlgorithm.AES256_CBC: /* create key from passphrase */ SHA1 sha = SHA1.Create(); sha.Initialize(); List <byte> key = new List <byte>(); using (PinnedArray <byte> hashData = new PinnedArray <byte>(cPrivateKeyDecryptSalt1.Length + fileData.passphrase.Length)) { Array.Copy(Encoding.UTF8.GetBytes(cPrivateKeyDecryptSalt1), hashData.Data, cPrivateKeyDecryptSalt1.Length); IntPtr passphrasePtr = Marshal.SecureStringToGlobalAllocUnicode(fileData.passphrase); for (int i = 0; i < fileData.passphrase.Length; i++) { int unicodeChar = Marshal.ReadInt16(passphrasePtr + i * 2); byte ansiChar = Util.UnicodeToAnsi(unicodeChar); hashData.Data[cPrivateKeyDecryptSalt1.Length + i] = ansiChar; Marshal.WriteByte(passphrasePtr, i, 0); } Marshal.ZeroFreeGlobalAllocUnicode(passphrasePtr); sha.ComputeHash(hashData.Data); key.AddRange(sha.Hash); Array.Copy(Encoding.UTF8.GetBytes(cPrivateKeyDecryptSalt2), hashData.Data, cPrivateKeyDecryptSalt2.Length); sha.ComputeHash(hashData.Data); key.AddRange(sha.Hash); } sha.Clear(); /* decrypt private key */ Aes aes = Aes.Create(); aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; int keySize = aes.KeySize / 8; // convert bits to bytes key.RemoveRange(keySize, key.Count - keySize); // remove extra bytes aes.Key = key.ToArray(); Util.ClearByteList(key); aes.IV = new byte[aes.IV.Length]; ICryptoTransform decryptor = aes.CreateDecryptor(); fileData.privateKeyBlob.Data = Util.GenericTransform(decryptor, fileData.privateKeyBlob.Data); decryptor.Dispose(); aes.Clear(); break; default: throw new PpkFormatterException(PpkFormatterException.PpkErrorType.PrivateKeyEncryption); } }
public static string SHA1Bytes(byte[] buffer) { SHA1 sha = SHA1.Create(); buffer = sha.ComputeHash(buffer); sha.Clear(); return(BitConverter.ToString(buffer).Replace("-", "")); }
internal static string ComputeAcceptKey(string sSecWebSocketKeyFromClient) { SHA1 sHA = SHA1.Create(); string result = Convert.ToBase64String(sHA.ComputeHash(Encoding.ASCII.GetBytes(sSecWebSocketKeyFromClient + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); sHA.Clear(); return(result); }
public static byte[] StringToByte(string texto) { byte[] clearBytes = Encoding.UTF8.GetBytes(texto); SHA1 hasher = SHA1.Create(); byte[] hashBytes = hasher.ComputeHash(clearBytes); hasher.Clear(); return(hashBytes); }
public static string HashBytes(byte[] clearBytes) { SHA1 hasher = SHA1.Create(); byte[] hashBytes = hasher.ComputeHash(clearBytes); string hash = System.Convert.ToBase64String(hashBytes); hasher.Clear(); return(hash); }
/// <summary> /// 对字符串SHA1加密 /// </summary> /// <param name="source">源字符串</param> /// <param name="encoding">编码类型</param> /// <returns>加密后的十六进制字符串</returns> public static string Sha1Encrypt(string source, Encoding encoding = null) { if (encoding == null) { encoding = Encoding.UTF8; } // 第一种方式 SHA1 algorithm = SHA1.Create(); byte[] byteArray = encoding.GetBytes(source); byte[] data = algorithm.ComputeHash(byteArray); StringBuilder stringBuilder = new StringBuilder(256); foreach (byte item in data) { stringBuilder.AppendFormat("{0:x2}", item); } algorithm.Clear(); return(stringBuilder.ToString()); //string sh1 = ""; //for (int i = 0; i < data.Length; i++) //{ // sh1 += data[i].ToString("x2").ToUpperInvariant(); //} //hashcode = sh1; //hashcode = hashcode.ToLower(); //// 第二种方式 //byte[] byteArray = encoding.GetBytes(source); //using (HashAlgorithm hashAlgorithm = new SHA1CryptoServiceProvider()) //{ // byteArray = hashAlgorithm.ComputeHash(byteArray); // StringBuilder stringBuilder = new StringBuilder(256); // foreach (byte item in byteArray) // { // stringBuilder.AppendFormat("{0:x2}", item); // } // hashAlgorithm.Clear(); // return stringBuilder.ToString(); //} //// 第三种方式 //using (SHA1 sha1 = SHA1.Create()) //{ // byte[] hash = sha1.ComputeHash(encoding.GetBytes(source)); // StringBuilder stringBuilder = new StringBuilder(); // for (int index = 0; index < hash.Length; ++index) // stringBuilder.Append(hash[index].ToString("x2")); // sha1.Clear(); // return stringBuilder.ToString(); //} }
public static string FromStream(Stream contentStream) { string result = null; using (SHA1 sha = SHA1.Create()) using (BytesConverter bc = new BytesConverter()) { result = bc.ToHexString(sha.ComputeHash(contentStream)); sha.Clear(); } return(result); }
static public string SHA1_Hash(byte[] bytes_sha1_in) { byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in); sha1.Clear(); string hashedValue = ""; for (int i = 0; i < bytes_sha1_out.Length; i++) { hashedValue += bytes_sha1_out[i].ToString("x2"); } return(hashedValue.ToUpper()); }
public static string FromContent(byte[] content, int offset, int count) { string result = null; using (SHA1 sha = SHA1.Create()) using (BytesConverter bc = new BytesConverter()) { result = bc.ToHexString(sha.ComputeHash(content, offset, count)); sha.Clear(); } return(result); }
public static string FromString(string content) { string result = null; using (SHA1 sha = SHA1.Create()) using (BytesConverter bc = new BytesConverter()) { result = bc.ToHexString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(content))); sha.Clear(); } return(result); }
private void updateContents(byte[][] conts) { SHA1 s = SHA1.Create(); for (int i = 0; i < contents.Count; i++) { contents[i].Size = (ulong)conts[i].Length; contents[i].Hash = s.ComputeHash(conts[i]); } s.Clear(); }
/// <summary> /// SHA1 /// </summary> /// <param name="password"></param> /// <returns></returns> public static string SHA1EncryptPassword(string password) { if (password == null) { throw new ArgumentNullException(nameof(password)); } using SHA1 sHA1 = SHA1.Create();//SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider(); string text = BitConverter.ToString(sHA1.ComputeHash(Encoding.UTF8.GetBytes(password))); sHA1.Clear(); return(text.Replace("-", null)); }
private byte[] DeriveKey(byte[] salt, string password) { byte[] pwd = Encoding.ASCII.GetBytes(password); SHA1 sha1 = (SHA1)SHA1.Create(); sha1.TransformBlock(salt, 0, salt.Length, salt, 0); sha1.TransformFinalBlock(pwd, 0, pwd.Length); byte[] key = new byte [16]; Buffer.BlockCopy(sha1.Hash, 0, key, 0, 16); sha1.Clear(); Array.Clear(pwd, 0, pwd.Length); return(key); }
public static string FromFile(string path, int buffersize) { string result = null; using (SHA1 sha = SHA1.Create()) using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, buffersize)) using (BytesConverter bc = new BytesConverter()) { result = bc.ToHexString(sha.ComputeHash(fs)); sha.Clear(); } return(result); }
private byte[] DeriveKey(byte[] salt, string password) { byte[] bytes = Encoding.ASCII.GetBytes(password); SHA1 shA1 = SHA1.Create(); shA1.TransformBlock(salt, 0, salt.Length, salt, 0); shA1.TransformFinalBlock(bytes, 0, bytes.Length); byte[] numArray = new byte[16]; Buffer.BlockCopy((Array)shA1.Hash, 0, (Array)numArray, 0, 16); shA1.Clear(); Array.Clear((Array)bytes, 0, bytes.Length); return(numArray); }
protected virtual void Dispose(bool disposing) { if (disposing && !isDisposed) { sha.Clear(); sha = null; certsComplete = null; certCa = null; certCp = null; certXs = null; } isDisposed = true; }
/// <summary> /// SHA1加密 /// </summary> /// <param name="content"></param> /// <param name="encoding"></param> /// <returns></returns> public static string SHA1Encrypt(string content, string encoding = "utf-8") { SHA1 sha1 = SHA1.Create(); //SHA1 sha1 = System.Security.Cryptography.SHA1.Create(); byte[] bytesIn = System.Text.Encoding.GetEncoding(encoding).GetBytes(content); byte[] bytesOut = sha1.ComputeHash(bytesIn); sha1.Clear(); sha1.Dispose(); string result = BitConverter.ToString(bytesOut); result = result.Replace("-", ""); return(result); }
public static string hash(string Text, string salt) { SHA1 haser = SHA1.Create(); byte[] hashedBytes = haser.ComputeHash(Encoding.Default.GetBytes(string.Concat(Text, salt))); haser.Clear(); string hashedPassword = ""; for (int i = 0; i < hashedBytes.Length - 1; i++) { hashedPassword += hashedBytes[i].ToString("x2"); } return(hashedPassword); }
public static string Sha1Signature(string str) { using (SHA1 sha1 = SHA1.Create()) { byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(str)); StringBuilder stringBuilder = new StringBuilder(); for (int index = 0; index < hash.Length; ++index) { stringBuilder.Append(hash[index].ToString("x2")); } sha1.Clear(); return(stringBuilder.ToString().ToLower()); } }
/// <summary> /// Gets a hash from data /// </summary> /// <param name="Data">binary data</param> /// <returns>SHA1 hash</returns> public static string getHash(byte[] Data) { SHA1 HA = SHA1.Create(); byte[] Hash = HA.ComputeHash(Data); HA.Clear(); HA = null; StringBuilder retValue = new StringBuilder(Hash.Length * 2); foreach (byte b in Hash) { retValue.Append(b.ToString("X2")); } return(retValue.ToString()); }
/// <summary> /// Compute hash using authentication protocol. /// </summary> /// <param name="data">Data to hash</param> /// <param name="offset">Compute hash from the source buffer offset</param> /// <param name="count">Compute hash for source data length</param> /// <returns>Hash value</returns> public byte[] ComputeHash(byte[] data, int offset, int count) { #if !NETCOREAPP11 && !NETSTANDARD15 SHA1 sha = new SHA1CryptoServiceProvider(); #else SHA1 sha = SHA1.Create(); #endif byte[] res = sha.ComputeHash(data, offset, count); #if !NETCOREAPP11 && !NETSTANDARD15 sha.Clear(); #else sha.Dispose(); #endif return(res); }
/// <summary> /// Generates a handshake response key string based on the client's /// provided key to prove to the client that we're allowing the Websocket /// upgrade of our own free will and we were not coerced into doing it. /// </summary> /// <param name="key">Client provided security key</param> /// <returns></returns> private static string GenerateAcceptKey(string key) { if (string.IsNullOrEmpty(key)) { return(string.Empty); } string acceptkey = key + WebsocketHandshakeAcceptHashConstant; SHA1 hashobj = SHA1.Create(); string ret = Convert.ToBase64String(hashobj.ComputeHash(Encoding.UTF8.GetBytes(acceptkey))); hashobj.Clear(); return(ret); }
private string GetJSSDKSignature(string nonceStr, string timeStamp, string url) { string ticket = RequestJSApiTicket(); string[] array = { "noncestr=" + nonceStr, "jsapi_ticket=" + ticket, "timestamp=" + timeStamp, "url=" + url }; Array.Sort(array); string str = string.Join("&", array); SHA1 sha1 = SHA1.Create(); byte[] bytes = Encoding.UTF8.GetBytes(str); bytes = sha1.ComputeHash(bytes); sha1.Clear(); string signature = BitConverter.ToString(bytes).Replace("-", "").ToLower(); return(signature); }
/// <summary> /// Convert user password to acceptable authentication key. /// </summary> /// <param name="userPassword">User password</param> /// <param name="engineID">Authoritative engine id</param> /// <returns>Localized authentication key</returns> /// <exception cref="SnmpAuthenticationException">Thrown when key length is less then 8 bytes</exception> public byte[] PasswordToKey(byte[] userPassword, byte[] engineID) { // key length has to be at least 8 bytes long (RFC3414) if (userPassword == null || userPassword.Length < 8) { throw new SnmpAuthenticationException("Secret key is too short."); } int password_index = 0; int count = 0; #if !NETCOREAPP11 && !NETSTANDARD15 SHA1 sha = new SHA1CryptoServiceProvider(); #else SHA1 sha = SHA1.Create(); #endif /* Use while loop until we've done 1 Megabyte */ byte[] sourceBuffer = new byte[1048576]; byte[] buf = new byte[64]; while (count < 1048576) { for (int i = 0; i < 64; ++i) { // Take the next octet of the password, wrapping // to the beginning of the password as necessary. buf[i] = userPassword[password_index++ % userPassword.Length]; } Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length); count += 64; } byte[] digest = sha.ComputeHash(sourceBuffer); MutableByte tmpbuf = new MutableByte(); tmpbuf.Append(digest); tmpbuf.Append(engineID); tmpbuf.Append(digest); byte[] res = sha.ComputeHash(tmpbuf); #if !NETCOREAPP11 && !NETSTANDARD15 sha.Clear(); #else sha.Dispose(); #endif return(res); }
/// <summary> /// 加密信息 /// </summary> /// <param name="input">原始信息</param> /// <param name="flag">true加强加密;false普通加密</param> /// <returns>加密后的信息</returns> public static byte[] EncryptInfo(string input, bool flag) { byte[] sha1Pwd; SHA1 sha1 = SHA1.Create(); string highCode = "128167213105241091992541172169014025413312010521667211123"; if (flag) { sha1Pwd = sha1.ComputeHash(Encoding.Unicode.GetBytes(input + highCode)); } else { sha1Pwd = sha1.ComputeHash(Encoding.Unicode.GetBytes(input)); } sha1.Clear(); return(sha1Pwd); }
// Thx to 56 public override string GetVersion() { Assembly asm = Assembly.GetExecutingAssembly(); string ver = asm.GetName().Version.ToString(); SHA1 sha1 = SHA1.Create(); FileStream stream = File.OpenRead(asm.Location); byte[] hashBytes = sha1.ComputeHash(stream); string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); stream.Close(); sha1.Clear(); string ret = $"{ver}-{hash.Substring(0, 6)}"; return(ret); }