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; } }
/// <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); }
//============================================================ // STATIC METHODS //============================================================ #region GenerateHash(Stream stream, YahooMediaHashAlgorithm algorithm) /// <summary> /// Computes the hash value for the supplied <see cref="Stream"/> using the specified <see cref="YahooMediaHashAlgorithm"/>. /// </summary> /// <param name="stream">The input to compute the hash code for.</param> /// <param name="algorithm">A <see cref="YahooMediaHashAlgorithm"/> enumeration value that indicates the algorithm to use.</param> /// <returns>The <b>base64</b> encoded result of the computed hash code.</returns> /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException">The <paramref name="algorithm"/> is equal to <see cref="YahooMediaHashAlgorithm.None"/>.</exception> public static string GenerateHash(Stream stream, YahooMediaHashAlgorithm algorithm) { //------------------------------------------------------------ // Local members //------------------------------------------------------------ string base64EncodedHash = String.Empty; MD5 md5 = MD5Cng.Create(); SHA1 sha1 = SHA1Cng.Create(); //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(stream, "stream"); if (algorithm == YahooMediaHashAlgorithm.None) { throw new ArgumentException(String.Format(null, "Unable to generate a hash value for the {0} algorithm.", algorithm), "algorithm"); } if (algorithm == YahooMediaHashAlgorithm.MD5) { byte[] hash = md5.ComputeHash(stream); base64EncodedHash = Convert.ToBase64String(hash); } else if (algorithm == YahooMediaHashAlgorithm.Sha1) { byte[] hash = sha1.ComputeHash(stream); base64EncodedHash = Convert.ToBase64String(hash); } return(base64EncodedHash); }
private static byte[] ComputeHash(string hashAlgorithmName, string fileName) { HashAlgorithm hashAlgorithm = null; switch (hashAlgorithmName) { case StrMd5: hashAlgorithm = new MD5Cng(); break; case StrSha1: hashAlgorithm = new SHA1Cng(); break; case StrSha256: hashAlgorithm = new SHA256Cng(); break; } if (null != hashAlgorithm) { using (var stream = File.OpenRead(fileName)) { return(hashAlgorithm.ComputeHash(stream)); } } var message = String.Format("Invalid hash algorithm name: {0}", hashAlgorithmName); throw new ApplicationException(message); }
/// <summary> /// Given a file path, compute the file hashes. /// </summary> /// <param name="filePath"></param> /// <param name="md5Hash"></param> /// <param name="sha1Hash"></param> /// <param name="sha256Hash"></param> public static void ComputeHashes(string filePath, out byte[] md5Hash, out byte[] sha1Hash, out byte[] sha256Hash) { using (var md5 = MD5Cng.Create()) using (var sha1 = SHA1Cng.Create()) using (var sha256 = SHA256Cng.Create()) using (var input = File.OpenRead(filePath)) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { md5.TransformBlock(buffer, 0, bytesRead, buffer, 0); sha1.TransformBlock(buffer, 0, bytesRead, buffer, 0); sha256.TransformBlock(buffer, 0, bytesRead, buffer, 0); } // We have to call TransformFinalBlock, but we don't have any // more data - just provide 0 bytes. md5.TransformFinalBlock(buffer, 0, 0); sha1.TransformFinalBlock(buffer, 0, 0); sha256.TransformFinalBlock(buffer, 0, 0); md5Hash = md5.Hash; sha1Hash = sha1.Hash; sha256Hash = sha256.Hash; } }
public string GetHash(string input) { var sha1 = SHA1Cng.Create(); var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); return(Convert.ToBase64String(hash)); }
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; } }
/// <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)))); } }
public void DecryptColosseum(byte[] data, byte[] digest) { byte[] key = new byte[20]; byte[] k = new byte[20]; byte[] d = new byte[20]; ByteHelper.ReplaceBytes(key, 0, digest); ByteHelper.ReplaceBytes(k, 0, key); for (int i = 0; i < 20; i++) { k[i] = (byte)~k[i]; } ByteHelper.ReplaceBytes(key, 0, k); SHA1 sha1 = SHA1Cng.Create(); for (int i = 0x18; i < 0x1DFD8; i += 20) { key = sha1.ComputeHash(data, i, 20); ByteHelper.ReplaceBytes(d, 0, ByteHelper.SubByteArray(i, data, 20)); for (int j = 0; j < 20; j++) { d[j] ^= k[j]; } ByteHelper.ReplaceBytes(data, i, d); ByteHelper.ReplaceBytes(k, 0, key); } }
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); } } }
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); }
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) { } }
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; } } } }
/// <summary> /// MD5加密 /// </summary> /// <param name="password"></param> /// <param name="passwordFormat"></param> /// <returns></returns> public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat) { HashAlgorithm algorithm; if (password == null) { throw new ArgumentNullException("password"); } if (passwordFormat == null) { throw new ArgumentNullException("passwordFormat"); } if (EqualsIgnoreCase(passwordFormat, "sha1")) { algorithm = new SHA1Cng(); } else if (EqualsIgnoreCase(passwordFormat, "md5")) { algorithm = new MD5Cng(); } else { object[] args = new object[] { "passwordFormat" }; throw new ArgumentException("InvalidArgumentValue"); } using (algorithm) { return(BinaryToHex(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)))); } }
/// <summary> /// Create a new instance of the <see cref="EncryptionManager"/> class /// </summary> /// <param name="encryptionCertificate"> /// The certificate that contains the secrets used for encryption. Note that /// the private key must be present in this certificate in order for decryption /// to be performed. /// </param> /// <param name="mode">The mode (encryption/decryption) of the encryption manager</param> /// <param name="outputStream">The stream where the transformed content will be written</param> /// <param name="sourceFileSize"></param> public EncryptionManager( X509Certificate2 encryptionCertificate, EncryptionMode mode, Stream outputStream, long sourceFileSize) { Pre.ThrowIfArgumentNull(encryptionCertificate, nameof(encryptionCertificate)); Pre.ThrowIfArgumentNull(outputStream, nameof(outputStream)); Pre.ThrowIfTrue(mode == EncryptionMode.None, "Encryption mode cannot be None"); this.encryptionCertificate = encryptionCertificate; this.Mode = mode; this.sourceFileSize = sourceFileSize; this.outputStream = outputStream; this.sha1 = new SHA1Cng(); this.md5 = new MD5Cng(); // Any valid encrypted file will have a minimum size (to include the header and minimal // encrypted content). Ensure that the source file is at least this size. if (mode == EncryptionMode.Decrypt) { Pre.Assert(sourceFileSize >= MinimumEncryptedFileSize, "sourceFileSize >= minimumEncryptedFileSize"); } this.Initialize(); }
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; } }
public static byte[] ToSHA1Cng(this string s, Encoding encoding) { using (var sha1 = new SHA1Cng()) { return(sha1.ComputeHash(s.GetBytes(encoding))); } }
/// <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 }); }
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")))); } }
public void SHA1Cng() { #if NET472_OR_GREATER var bytes = new SHA1Cng().ComputeHash(stream); #else var bytes = SHA1.Create().ComputeHash(stream); #endif }
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 Guid ComputeGuidSHA1(byte[] bytes) { using (var hashAlgorithmImpl = new SHA1Cng()) { var hashBytes = hashAlgorithmImpl.ComputeHash(bytes); return(new Guid(hashBytes)); } }
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)); } }
//[Obsolete("The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.")] #region 加密方法 public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat) { string result = ""; if (password == null) { throw new ArgumentNullException("password"); } if (passwordFormat == null) { throw new ArgumentNullException("passwordFormat"); } HashAlgorithm hashAlgorithm; switch (passwordFormat) { case "sha1": hashAlgorithm = new SHA1Cng(); break; case "md5": hashAlgorithm = new MD5Cng(); break; case "sha256": hashAlgorithm = new HMACSHA256(); break; case "sha384": hashAlgorithm = new HMACSHA384(); break; case "sha512": hashAlgorithm = new HMACSHA512(); break; default: throw new ArgumentException("加解密类型不存在"); } using (hashAlgorithm) { byte[] bt = Encoding.UTF8.GetBytes(password); byte[] btp = hashAlgorithm.ComputeHash(bt); foreach (byte num in btp) { if (num < 0x10) { result = result + "0" + num.ToString("X"); } else { result = result + num.ToString("X"); } } } return(result); }
/// <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("-", "")); } }
// 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)); } }
/// <summary> /// CheckSum160 method implementation /// </summary> public static byte[] CheckSum160(string value) { byte[] hash = null; using (SHA1 sha1 = SHA1Cng.Create()) { hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value)); } return(hash); }