public static byte[] ToSHA1Cng(this string s, Encoding encoding) { using (var sha1 = new SHA1Cng()) { return(sha1.ComputeHash(s.GetBytes(encoding))); } }
public void BasicSyncLocalToB2() { if (!GlobalTestSettings.RunNetworkTests) { Assert.Inconclusive(GlobalTestSettings.NetworkTestsDisabledMessage); } byte[] data = Encoding.UTF8.GetBytes("Hello World!"); string hashString; using (SHA1Cng sha1 = new SHA1Cng()) { byte[] hashData = sha1.ComputeHash(data); hashString = BitConverter.ToString(hashData).Replace("-", ""); } BackblazeB2FileUploadResponse uploadResponse; string filename = Guid.NewGuid().ToString("N") + ".txt"; using (MemoryStream ms = new MemoryStream(data)) using (BackblazeB2Client client = CreateClient()) { uploadResponse = client.UploadFile( filename, hashString, data.Length, accountInfo.BucketId, ms).Result; } Assert.AreEqual(accountInfo.BucketId, uploadResponse.BucketId); Assert.AreEqual(data.Length, uploadResponse.ContentLength); Assert.AreEqual(hashString.ToUpperInvariant(), uploadResponse.ContentSha1.ToUpperInvariant()); Assert.AreEqual(filename, uploadResponse.FileName); }
public byte[] ComputeHash(byte[] abData, HashAlgorithmName HashAlgorithm) { byte[] abReturn = null; if (HashAlgorithm == HashAlgorithmName.MD5) { abReturn = _MD5Services.ComputeHash(abData); } else if (HashAlgorithm == HashAlgorithmName.SHA1) { abReturn = _SHA1Services.ComputeHash(abData); } else if (HashAlgorithm == HashAlgorithmName.SHA256) { abReturn = _SHA256Services.ComputeHash(abData); } else if (HashAlgorithm == HashAlgorithmName.SHA384) { abReturn = _SHA384Services.ComputeHash(abData); } else if (HashAlgorithm == HashAlgorithmName.SHA512) { abReturn = _SHA512Services.ComputeHash(abData); } return(abReturn); }
/// <summary> /// 对密码做 Hash运算 /// </summary> /// <param name="password">密码</param> /// <param name="hashFromat">哈希算法</param> /// <returns></returns> private static string HashPassword(string password, HashFromat hashFromat) { if (password == null) { throw new ArgumentNullException(nameof(password)); } if (password == null) { throw new ArgumentNullException("密码不能为空"); } HashAlgorithm hashAlgorithm = new MD5Cng(); switch (hashFromat) { case HashFromat.Md5: hashAlgorithm = new MD5Cng(); break; case HashFromat.Sha1: hashAlgorithm = new SHA1Cng(); break; } using (hashAlgorithm) { return(BinaryToHex(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(password)))); } }
/// <summary> /// Hash the data passed using the hash size specified defaulting to 256 if nothing is specified. /// </summary> /// <param name="data">The data to get a hash value (signature).</param> /// <param name="hashSize">The hash size to use (1, 256, 384 or 512)</param> /// <returns>A Byte[] the is a unique signature of the data passed.</returns> public static Byte[] SHACngHash(Byte[] data, Int32 hashSize) { Byte[] lHash = null; if (data != null) { if (hashSize == 512) { using (SHA512Cng sha = new SHA512Cng()) { lHash = sha.ComputeHash(data); } } else if (hashSize == 384) { using (SHA384Cng sha = new SHA384Cng()) { lHash = sha.ComputeHash(data); } } else if (hashSize == 256) { using (SHA256Cng sha = new SHA256Cng()) { lHash = sha.ComputeHash(data); } } else { using (SHA1Cng sha = new SHA1Cng()) { lHash = sha.ComputeHash(data); } } } return(lHash); }
private static bool GetRandomPINFromPasswd(string passwd, int len, out string pin) { pin = null; int num = Math.Max(len, 10); if (passwd == null) { return(false); } byte[] bytes; using (SHA1Cng sha1Cng = new SHA1Cng()) { bytes = sha1Cng.ComputeHash(Encoding.ASCII.GetBytes(passwd)); } StringBuilder stringBuilder = new StringBuilder(Encoding.ASCII.GetString(bytes)); int length = stringBuilder.Length; if (num > length) { stringBuilder.Append('0', num - length); } string temp = stringBuilder.ToString().Substring(0, num); pin = UmConnectivityCredentialsHelper.GetNumericPinFromString(temp); UmConnectivityCredentialsHelper.DebugTrace("Inside GetRandomPINFromPasswd(): pin = {0}", new object[] { pin }); return(true); }
public static void ComputeHashes(string fileName, out string md5, out string sha1, out string sha256) { sha1 = sha256 = md5 = null; try { using (FileStream stream = File.OpenRead(fileName)) { using (var bufferedStream = new BufferedStream(stream, 1024 * 32)) { var md5Cng = new MD5Cng(); byte[] checksum = md5Cng.ComputeHash(bufferedStream); md5 = BitConverter.ToString(checksum).Replace("-", String.Empty); stream.Seek(0, SeekOrigin.Begin); bufferedStream.Seek(0, SeekOrigin.Begin); var sha1Cng = new SHA1Cng(); checksum = sha1Cng.ComputeHash(bufferedStream); sha1 = BitConverter.ToString(checksum).Replace("-", String.Empty); stream.Seek(0, SeekOrigin.Begin); bufferedStream.Seek(0, SeekOrigin.Begin); var sha256Cng = new SHA256Cng(); checksum = sha256Cng.ComputeHash(bufferedStream); sha256 = BitConverter.ToString(checksum).Replace("-", String.Empty); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } }
static async Task getAccessToken() { string toHash = reqtoken + privateKey; using (SHA1Cng sha = new SHA1Cng()) { var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(toHash)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { sb.Append(b.ToString("x2")); } password = sb.ToString(); }; TokenAccess acc = null; HttpResponseMessage response = await client.GetAsync( $"oauth/accesstoken?oauth_token={reqtoken}&grant_type=api&username={username}&password={password}"); if (response.IsSuccessStatusCode) { acc = await response.Content.ReadAsAsync <TokenAccess>(); acctoken = acc.AccessToken; } }
public void RunCached(string proj, string key, Action action) { string keyHash; using (var sha1 = new SHA1Cng()) { var arr = Encoding.UTF8.GetBytes(proj + "\n" + key); var hash = sha1.ComputeHash(arr); keyHash = Convert.ToBase64String(hash) .Replace("/", "-") .Replace("+", "_") .Replace("=", string.Empty); } lock (_runLock) { using (var info = JsonFile.Open <ExecutionSummary>(Path.Combine("C:\\BuildFs\\Cache", keyHash + ".pb"))) { if (!ForceRun && info.Content.Available && IsStatusStillValid(proj, keyHash, info.Content)) { Console.WriteLine("No need to run " + keyHash); info.DiscardAll(); } else { ClearStatus(proj); action(); var changes = CaptureChanges(proj); info.Content.Inputs = changes.Inputs; info.Content.Outputs = changes.Outputs; info.Content.Available = true; } } } }
public override void Flush() { if (this.memoryStream.Length < this.Session.FileSize) { return; } try { this.flushInProgress = true; // Reset the position of the stream. We will first calculate the SHA1 hash for the stream // content, then reset the stream again so that it can be read by the client during upload. this.memoryStream.Position = 0; byte[] hash; using (SHA1Cng sha1 = new SHA1Cng()) { hash = sha1.ComputeHash(this.memoryStream); } // Reset the position of the stream again since we are going to reading it during upload. this.memoryStream.Position = 0; // Upload the content this.Session.UploadResponse = this.adapter.UploadFileDirect(this.Session.Entry, this.memoryStream, hash).Result; } finally { this.flushInProgress = false; } }
protected override void UploadPart(byte[] partBuffer, long partOffset, long partIndex) { // A sha1 hash needs to be sent for each part that is uploaded. Because the part size is small (less // than 100MB) and the entire payload is loaded into memory (in the partBuffer array), computing the // hash should be quick operation (compared the to uploading delay). string sha1Hash; using (var sha1 = new SHA1Cng()) { byte[] hashData = sha1.ComputeHash(partBuffer); sha1Hash = BitConverter.ToString(hashData).Replace("-", "").ToLowerInvariant(); } using (MemoryStream memoryStream = new MemoryStream(partBuffer)) { this.adapter.UploadPart( this.Session, this.Session.CurrentPartNumber, sha1Hash, partBuffer.LongLength, memoryStream).Wait(); this.Session.PartHashes.Add( this.Session.CurrentPartNumber, sha1Hash); this.Session.CurrentPartNumber++; this.Session.BytesUploaded += partBuffer.Length; } }
public static byte[] ToSHA1(this byte[] s) { using (var sha1 = new SHA1Cng()) { return(sha1.ComputeHash(s)); } }
private void BtnValider_Click(object sender, RoutedEventArgs e) { string pseudo, password; pseudo = txtPseudo.Text; password = txtPassword.Password; byte[] B = Encoding.UTF8.GetBytes(password); SHA1Cng sha1 = new SHA1Cng(); byte[] result = sha1.ComputeHash(B); var toStringResult = Hex.ToHexString(result); if (!Utilisateur.Connecte(pseudo, toStringResult)) { MessageBox.Show("Pseudo ou mot de passe incorrect!", "mTransport", MessageBoxButton.OK, MessageBoxImage.Error); return; } else { try { User = Utilisateur.GetIdUserAfterLogin(pseudo, toStringResult); MainWindow F = new MainWindow(); F.Show(); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Checks if password has been compromised using PwnedPasswords API. /// </summary> /// <param name="password">Password to check</param> /// <returns>True if strong password, false if weak password</returns> public async Task <ResponseDto <bool> > IsPasswordValidAsync(string password) { var passwordHash = ""; // Hash password with SHA1. using (var hasher = new SHA1Cng()) { passwordHash = BitConverter.ToString(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))); passwordHash = passwordHash.Replace("-", ""); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Get first 5 characters of hash and send it as part of the url for a get request. var prefixHash = passwordHash.Substring(0, 5); var request = new GetRequestService($"{ApiConstants.PWNED_PASSWORD_URL}{prefixHash}"); var response = await new BackoffRequest(request).TryExecute(); var responseBody = await response.Content.ReadAsStringAsync(); // Separate response by lines into an array of strings var splitResponse = responseBody.Split(new[] { Environment.NewLine }, StringSplitOptions.None); // Iterate through every line of response and check if hash matches and, if so, if the count // falls within valid range. foreach (var line in splitResponse) { // Splits the line by the hash suffix and the breach count. // An example line would be: // 1E4C9B93F3F0682250B6CF8331B7EE68FD8:3303003 var splitLine = line.Split(':'); var suffixHash = splitLine[0]; // If password hash does not match, continue to next iteration. if (!passwordHash.Equals(prefixHash + suffixHash.ToUpper())) { continue; } var breachCount = int.Parse(splitLine[1]); var isPasswordValid = true; // flag password as invalid if the breach count is greater than the limit if (breachCount > _maxValidCount) { isPasswordValid = false; } return(new ResponseDto <bool>() { Data = isPasswordValid }); } // If password has has no matches, it is valid. return(new ResponseDto <bool>() { Data = true }); }
private byte[] CaptureHash(string fileName) { using (var stream = File.Open(GetPathAware(fileName), FileMode.Open, System.IO.FileAccess.Read, FileShare.Delete | FileShare.Read)) using (var sha1 = new SHA1Cng()) { return(sha1.ComputeHash(stream)); } }
public static Guid ComputeGuidSHA1(byte[] bytes) { using (var hashAlgorithmImpl = new SHA1Cng()) { var hashBytes = hashAlgorithmImpl.ComputeHash(bytes); return(new Guid(hashBytes)); } }
private static String computeSha1(String path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] hash = sha1Calculation.ComputeHash(fs); return(BitConverter.ToString(hash).Replace("-", "").ToLower()); } }
public static uint OneWayFunction32Bit(byte[] input) { //SHA1 sha1 = SHA1.Create(); //SHA1Managed sha1mng = new SHA1Managed(); SHA1Cng sha1cng = new SHA1Cng(); return(sha1cng.ComputeHash(input).ReduceSHA1to32bit()); }
/// <summary> /// Takes 32-bit unsigned integer and gives the LSB 32-bit of SHA1 hash result as UInt32. /// </summary> /// <param name="input">32-bit unsigned integer</param> /// <returns>LSB 32-bit of SHA1 Hash result.</returns> public static uint SHA1_LSB32bit(uint input) { //SHA1 sha1 = SHA1.Create(); //SHA1Managed sha1mng = new SHA1Managed(); SHA1Cng sha1cng = new SHA1Cng(); return(sha1cng.ComputeHash(input.ToByteArray()).ToUInt32()); }
public static String ComputeSHA1(byte[] bytes) { using (var hashAlgorithmImpl = new SHA1Cng()) { var hashBytes = hashAlgorithmImpl.ComputeHash(bytes); return(String.Concat(hashBytes.Select(b => b.ToString("x2")))); } }
/// <summary> /// Calculate the SHA1 hash of a file /// </summary> /// <param name="filePath">Path to file to examine</param> /// <returns> /// SHA1 hash, in all-caps hexadecimal format /// </returns> public static string GetFileHashSha1(string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (BufferedStream bs = new BufferedStream(fs)) using (SHA1Cng sha1 = new SHA1Cng()) { return(BitConverter.ToString(sha1.ComputeHash(bs)).Replace("-", "")); } }
public static byte[] GetSha1Hash(byte[] inputBytes) { byte[] result; using (SHA1Cng sha1Cng = new SHA1Cng()) { result = sha1Cng.ComputeHash(inputBytes); } return(result); }
// returns the 8-byte hash for a given url public static string CreateURLHash(Uri url) { using (var sha1 = new SHA1Cng()) { byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(url.ToString())); return(BitConverter.ToString(hash).Replace("-", "").Substring(0, 8)); } }
private static Int64 SHA1HashWorker(Byte[] input) { Byte[] hashCode = null; using (SHA1Cng sha = new SHA1Cng()) { hashCode = sha.ComputeHash(input); } return(BitConverter.ToInt64(hashCode, 0)); }
/// <summary> /// Returns the given pending change if it should be undone, otherwise null. /// </summary> private Task <PendingChange> ShouldUndoPendingChangeAsync(PendingChange pendingChange) { return(Task.Run(() => { if (pendingChange.IsAdd || pendingChange.IsDelete || pendingChange.IsLocalItemDelete || pendingChange.IsUndelete) { return null; } byte[] baseItemHashCode; try { using (var baseFileStream = pendingChange.DownloadBaseFile()) { using (var hashAlgorithem = new SHA1Cng()) { baseItemHashCode = hashAlgorithem.ComputeHash(baseFileStream); } } } catch (Exception ex) { const string ErrorMessageFormat = "Error occurred during computing hash for the base item of {0}: {1}"; LoggerUtilities.LogError(string.Format(CultureInfo.CurrentCulture, ErrorMessageFormat, pendingChange.ServerItem, ex.ToString())); return null; } byte[] localItemHashCode; try { using (var localFileStream = new FileStream(Path.GetFullPath(pendingChange.LocalItem), FileMode.Open, FileAccess.Read)) { using (var hashAlgorithem = new SHA1Cng()) { localItemHashCode = hashAlgorithem.ComputeHash(localFileStream); } } } catch (Exception ex) { const string ErrorMessageFormat = "Error occurred during computing hash for the local item of {0}: {1}"; LoggerUtilities.LogError(string.Format(CultureInfo.CurrentCulture, ErrorMessageFormat, pendingChange.ServerItem, ex.ToString())); return null; } return Enumerable.SequenceEqual(baseItemHashCode, localItemHashCode) ? pendingChange : null; })); }
public string GetFileHashSha1(string filePath) { using (FileStream fs = new FileStream(@filePath, FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (var sha1 = new SHA1Cng()) { byte[] hash = sha1.ComputeHash(bs); return(BitConverter.ToString(hash).Replace("-", "")); } }
/// <summary> /// The get sha 1 hash hex string. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The <see cref="string"/> . /// </returns> public static string GetSha1HashHexString(this string value) { if (string.IsNullOrEmpty(value)) { return(string.Empty); } var cng = new SHA1Cng(); var buffer = cng.ComputeHash(value.GetBytes(Encoding.GetEncoding(0x4e3))); cng.Dispose(); return(BitConverter.ToString(buffer).Replace("-", string.Empty)); }
/// <summary> /// sha1 hash /// </summary> /// <param name="input"></param> /// <param name="lowerCase"></param> /// <returns></returns> public static string SHA1(string input, bool lowerCase = true) { if (string.IsNullOrEmpty(input)) { return(string.Empty); } using (var hashAlgorithm = new SHA1Cng()) { var hexString = BinaryUtil.ToHex(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input))); return(lowerCase ? hexString.ToLowerInvariant() : hexString); } }
public static string GetSha1HashString(string str) { try { using (var sha1Cng = new SHA1Cng()) { return(Hex(sha1Cng.ComputeHash(Encoding.UTF8.GetBytes(str)))); } } catch { return(null); } }
public string ComputeHash(string filepath) { byte[] hashedBytes; using (var sha1 = new SHA1Cng()) { var fileStream = File.ReadAllBytes(filepath); hashedBytes = sha1.ComputeHash(fileStream); } var hashCode = ConvertBytesToHexString(hashedBytes); return(hashCode); }