public static byte[] DoubleDigest(byte[] input, int offset, int length) { _digest.Dispose(); _digest = new SHA256CryptoServiceProvider(); byte[] first = _digest.ComputeHash(input, offset, length); return _digest.ComputeHash(first); }
private bool TestSha(HashAlgorithm alg1, HashAlgorithm alg2) { string tstStr = "This is a string that I will be getting the hash of!"; byte[] testHash = System.Text.UTF8Encoding.UTF8.GetBytes(tstStr); byte[] hash1 = alg1.ComputeHash(testHash, 0, testHash.Length); byte[] hash2 = alg1.ComputeHash(testHash, 0, testHash.Length); byte[] hash3 = alg1.ComputeHash(testHash, 0, testHash.Length - 1); byte[] hash4 = alg2.ComputeHash(testHash); byte[] hash5 = alg2.ComputeHash(testHash, 0, testHash.Length - 1); if (hash1.Length != (alg1.HashSize/8)) throw new Exception(); bool res1 = true, res2 = true, res3 = true, res4 = true; for (int i = 0; i < hash1.Length; i++) { res1 &= (hash1[i] == hash2[i]); res2 &= (hash1[i] == hash3[i]); res3 &= (hash1[i] == hash4[i]); res4 &= (hash3[i] == hash5[i]); } return res1 && !res2 && res3 && res4; }
public List<RdcSignature> Chunk(Stream stream, int averagChunkBitLength, int minChunk, int maxChunk, int window) { hashAlg = MD5.Create(); hashBuffer = new byte[maxChunk]; hashLength = 0; int mask = (1 << averagChunkBitLength) - 1; List<RdcSignature> signatures = new List<RdcSignature>(); long length = stream.Length; long lastStart = 0; // get the initial hash window // int hash = inithash(window, stream); long position = window; //position starts at window size Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (position < length) { // chunk boundry is found and chunk is sufficiently large if ((hash & mask) == 0 && hashLength >= minChunk) { lastStart = position; signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength))); hashLength = 0; } else if (position - lastStart + 1 >= maxChunk) // force a break if the chunk is large enough { lastStart = position; signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength))); hashLength = 0; } // next window's hash // hash = nexthash(hash, stream); ///////////////////////// position++; //if (position % REPORT_BOUNDRY == 0) { // Console.WriteLine("{0}ms", stopwatch.ElapsedMilliseconds); // stopwatch.Restart(); //} } //If we didn't have a break on the last position of the file if (hashLength > 0) { lastStart = position; signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength))); hashLength = 0; } return signatures; }
/// <summary>Compute hash on input stream</summary> /// <param name="input">The stream to compute hash on.</param> /// <param name="algorithm"> </param> /// <returns>The hash as a hexadecimal String.</returns> public static string ComputeHash(this Stream input, HashAlgorithm algorithm) { if (input == null) throw new ArgumentNullException("input"); #if !SILVERLIGHT var stream = new BufferedStream(input, 1024 * 8); byte[] data = algorithm.ComputeHash(stream); return ToHex(data); #else byte[] data = algorithm.ComputeHash(input); return ToHex(data); #endif }
private static string CalculateHash(string salt, string password, HashAlgorithm hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes(salt + password); byte[] hash = hashAlgorithm.ComputeHash(data); return Convert.ToBase64String(hash); }
public static bool ValidateChecksum(HashAlgorithm hashAlgorithm, Stream checksumFile, string filenameToCheck, Stream fileToCheck) { // Find the checksum... string checksum = null; using (var checksumFileReader = new StreamReader(checksumFile, Encoding.ASCII, false, 256, true)) { while (checksum == null) { var line = checksumFileReader.ReadLine(); if (line == null) break; line = line.Trim(); var parts = line.Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) throw new ArgumentException("Invalid format of input file"); if (parts[1] == filenameToCheck) checksum = parts[0]; } } if (checksum == null) throw new ArgumentException($"Could not find checksum for file {filenameToCheck} in checksumFile"); byte[] hash = hashAlgorithm.ComputeHash(fileToCheck); var formattedHash = FormatHash(hash); return formattedHash == checksum; }
public static Tuple<byte[], string> HashFile(HashAlgorithm ha, string file) { using (var fs = File.OpenRead(file)) { return new Tuple<byte[], string>(ha.ComputeHash(fs), file); } }
public static string HashWith(this string input, HashAlgorithm algorithm) { byte[] data = Encoding.UTF8.GetBytes(input); byte[] hash = algorithm.ComputeHash(data); return Convert.ToBase64String(hash); }
/// <summary> /// File content hash calculation /// </summary> /// <example> /// <code> /// // Implementation of <see cref="CalculateSha256Hash"/> /// public static QuickIOHashResult CalculateSha256Hash( QuickIOPathInfo pathInfo ) /// { /// using ( var fs = OpenRead( pathInfo ) ) /// using ( var hashAlgorithm = SHA256.Create( ) ) /// { /// return CalculateHash( hashAlgorithm, fs ); /// } /// } /// </code> /// </example> /// <returns><see cref="QuickIOHashResult"/></returns> public static QuickIOHashResult CalculateHash( HashAlgorithm hashAlgorithm, Stream stream ) { Contract.Requires( hashAlgorithm != null ); Contract.Requires( stream != null ); return new QuickIOHashResult( hashAlgorithm.ComputeHash( stream ) ); }
private static string Hash(string str, HashAlgorithm hashAlgorithm) { if (string.IsNullOrEmpty(str)) return str; byte[] s = hashAlgorithm.ComputeHash(UnicodeEncoding.UTF8.GetBytes(str)); return BitConverter.ToString(s); }
public static string HashString(string inputString, string salt, HashAlgorithm algorithm) { if (inputString == null) { throw new ArgumentException("inputString cannot be null."); } if (algorithm == null) { throw new ArgumentException("algorithm cannot be null."); } if (salt == null) { throw new ArgumentException("saltString cannot be null."); } //Mix password with salt. byte[] stringWithSalt = System.Text.Encoding.UTF8.GetBytes(inputString + salt); //Compute hash. byte[] hashedBytes = algorithm.ComputeHash(stringWithSalt); // Convert hashed password bytes to string and remove "-". string hashedString = BitConverter.ToString(hashedBytes).Replace("-", string.Empty); // Return hashed password string in lowercase. return hashedString.ToLower(); }
protected int StartTests(HashAlgorithm hash, byte[] input, byte[] result) { try { byte[] ch = hash.ComputeHash(input, 0, input.Length); if (!ArrayEquals(ch, result)) AddError("HB-ST1"); } catch { AddError("HB-ST2"); } try { // feed input byte-by-byte for(int i = 0; i < input.Length - 1; i++) { hash.TransformBlock(input, i, 1, input, i); } if (input.Length > 0) hash.TransformFinalBlock(input, input.Length - 1, 1); else hash.TransformFinalBlock(input, 0, 0); if (!ArrayEquals(hash.Hash, result)) { AddError("HB-ST3"); Console.WriteLine(Encoding.ASCII.GetString(input)); } } catch { AddError("HB-ST4"); } finally { hash.Initialize(); } return 4; }
private static string CreateHash( HashAlgorithm algo, byte[] value) { return HexDigest( algo.ComputeHash(value)); }
public static string computeHash(string password, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(password); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); }
internal void CalculateHa1(string realm, HashAlgorithm hashAlgorithm) { Ha1 = Helpers.HexEncode( hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(string.Format("{0}:{1}:{2}", Username, realm, _password)))); _password = null; }
private static String GetHashFile(String filename, HashAlgorithm hash) { FileStream fs = null; try { fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); Int64 currentPos = fs.Position; fs.Seek(0, SeekOrigin.Begin); StringBuilder sb = new StringBuilder(); foreach (Byte b in hash.ComputeHash(fs)) { sb.Append(b.ToString("X2")); } fs.Close(); return sb.ToString(); } catch (Exception ex) { if (fs != null) { fs.Close(); } string error = ex.Message; return ""; } }
public static string GetHashFromFile(string fileName, HashAlgorithm algorithm) { using (var stream = new BufferedStream(File.OpenRead(fileName), 100000)) { return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty); } }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. /// </summary> /// <param name="text">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="hashAlgorithm">Hash algorithm to be used.</param> /// <returns>Hash value formatted as a base64-encoded string.</returns> /// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.Text.EncoderFallbackException"></exception> /// <exception cref="System.ObjectDisposedException"></exception> /// <exception cref="System.ArgumentException"></exception> public static string ComputeHash(string text, HashAlgorithm hashAlgorithm) { Refresh(); if (hashAlgorithm == null) throw new ArgumentNullException("hashAlgorithm"); return Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(text))); }
public static string ToBase64Hash(this string inputString, Encoding encoding, HashAlgorithm algo) { var inputBuffer = encoding.GetBytes(inputString); var outputBuffer = algo.ComputeHash(inputBuffer, 0, inputBuffer.Length); return Convert.ToBase64String(outputBuffer); }
public static string GetHashString(string filePath) { FileInfo file = new FileInfo(filePath); if (!file.Exists) { return(""); } byte[] bytes1 = System.Text.Encoding.ASCII.GetBytes("blob " + file.Length.ToString() + '\0'.ToString()); byte[] bytes2 = File.ReadAllBytes(file.FullName); List <byte> temp = new List <byte>(); temp.AddRange(bytes1); temp.AddRange(bytes2); byte[] bytes = temp.ToArray(); System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.SHA1.Create(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (byte b in algorithm.ComputeHash(bytes)) { sb.Append(b.ToString("X2")); } return(sb.ToString().ToLower()); }
/// <summary> /// Encodes the hash. The resulting string is a simple 2-char hex encoded string. /// If you like base64 just use Convert.ToBase64String(); instead of ByteArrayToString(); /// </summary> /// <param name="message">The message to encode.</param> /// <param name="algorithm">The Hashing algorithm.</param> /// <returns>Hex encoded hash value.</returns> private static string EncodeHash(string message, HashAlgorithm algorithm) { string saltedMessage = string.Format(CultureInfo.CurrentCulture, "ChocolateSaltyBalls{0}AreSoSalty!", message); byte[] saltedBytes = new UTF8Encoding().GetBytes(saltedMessage); return BitConverter.ToString(algorithm.ComputeHash(saltedBytes)).Replace("-", string.Empty); }
private static string GetFileHash(HashAlgorithm algorithm, string fileName) { var stream = File.OpenRead(fileName); var hashResult = algorithm.ComputeHash(stream); stream.Close(); return BitConverter.ToString(hashResult).Replace("-", ""); }
private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier) { byte[] bytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber)); byte[] buffer2 = hashAlgorithm.ComputeHash(ApplyModifier(bytes, modifier)); int index = buffer2[buffer2.Length - 1] & 15; int num2 = ((((buffer2[index] & 127) << 24) | ((buffer2[index + 1] & 255) << 16)) | ((buffer2[index + 2] & 255) << 8)) | (buffer2[index + 3] & 255); return (num2 % 1000000); }
public void ComputeHash(HashAlgorithm hasher) { var hashBytes = hasher.ComputeHash(FilePath, progress: this); if (hashBytes == null) Result = "Canceled"; else Result = String.Concat(hashBytes.Select(b => b.ToString("X2"))); }
public string ComputeHash(string input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); }
protected byte[] ComputeHashInternal(HashAlgorithm algorithm, byte[] bytes, int offset, int count, int? size = null) { var hash = algorithm.ComputeHash(bytes, offset, count); if (size.HasValue) Array.Resize(ref hash, size.Value); return hash; }
public static string FileHash(FileInfo fileInfo, HashAlgorithm hash) { using (FileStream file = new FileStream(fileInfo.FullName, FileMode.Open)) { byte[] retVal = hash.ComputeHash(file); return BitConverter.ToString(retVal).Replace("-", ""); // hex string } }
/// <summary> /// /// </summary> /// <param name="content">加密的方法</param> /// <param name="getBytesFunc">把content转换为byte的方法</param> /// <param name="hashAlgorithm">加密的方式</param> /// <returns></returns> public static byte[] Encrypt(string content, Encoding getBytesFunc, HashAlgorithm hashAlgorithm) { if (content == null) throw new ArgumentNullException("content"); if (getBytesFunc == null) throw new ArgumentNullException("getBytesFunc"); if (hashAlgorithm == null) throw new ArgumentNullException("hashAlgorithm"); byte[] iput = getBytesFunc.GetBytes(content); return hashAlgorithm.ComputeHash(iput); }
public void FIPS186_b(string testName, HashAlgorithm hash, byte[] input, byte[] result) { byte[] output = hash.ComputeHash (input, 0, input.Length); Assert.AreEqual (result, output, testName + ".b.1"); Assert.AreEqual (result, hash.Hash, testName + ".b.2"); // required or next operation will still return old hash hash.Initialize (); }
/// <summary> /// Универсальный метод для вычисления хеш-строки, в зависимости от алгоритма. /// </summary> /// <param name="input">Входная строка.</param> /// <param name="algorithm">Алгоритм вычисления хеш-функции.</param> /// <returns>SHA512 хеш.</returns> public static String ComputeHash(String input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return ConvertersHelper.ByteArrayToHex(hashedBytes); }
public static byte[] ComputeHash(string fileName, HashAlgorithm hashAlgorithm) { if (hashAlgorithm == null) throw new ArgumentNullException("hashAlgorithm"); using (var stream = File.OpenRead(fileName)) return hashAlgorithm.ComputeHash(stream); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="encodeMode"></param> /// <returns></returns> public static byte[]? Encode(this byte[] input, EncodeType encodeMode) { using HashAlgorithm encoder = encodeMode switch { EncodeType.MD5 => MD5.Create(), EncodeType.SHA1 => SHA1.Create(), EncodeType.SHA256 => SHA256.Create(), EncodeType.SHA384 => SHA384.Create(), EncodeType.SHA512 => SHA512.Create(), _ => throw new ArgumentOutOfRangeException(nameof(encodeMode)), }; return(encoder?.ComputeHash(input)); }
/// <summary> /// 获取Hash描述表 /// </summary> /// <param name="strSource">待签名的字符串</param> /// <param name="strHashData">Hash描述</param> /// <returns></returns> public bool GetHash(string strSource, ref string strHashData) { try { //从字符串中取得Hash描述 byte[] Buffer; byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strSource); HashData = MD5.ComputeHash(Buffer); strHashData = Convert.ToBase64String(HashData); return(true); } catch (Exception ex) { throw ex; } }
/// <summary> /// Generate hashed string of the string to according to hash algorithm. /// </summary> /// <param name="source"></param> /// <param name="hashAlgorithm"></param> /// <returns></returns> public static string GenerateHashString(this string source, HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256) { if (string.IsNullOrEmpty(source)) { throw new ArgumentException(nameof(source)); } var sourceData = Encoding.UTF8.GetBytes(source); byte[] hashedData = null; System.Security.Cryptography.HashAlgorithm hash = null; try { switch (hashAlgorithm) { case HashAlgorithm.SHA1: hash = SHA1.Create(); break; case HashAlgorithm.SHA512: { hash = SHA512.Create(); break; } case HashAlgorithm.SHA256: default: { hash = SHA256.Create(); break; } } hashedData = hash.ComputeHash(sourceData); } finally { hash?.Dispose(); } var result = BitConverter.ToString(hashedData).ToLower().Replace("-", ""); return(result); }
//获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref string strHashData) { try { //从文件中取得Hash描述 byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); strHashData = Convert.ToBase64String(HashData); return(true); } catch (Exception ex) { throw ex; } }
static string Hash_Internal(string p_string, System.Security.Cryptography.HashAlgorithm p_hashAlgorithm) { if (p_hashAlgorithm != null && !string.IsNullOrEmpty(p_string)) { var bytes = System.Text.Encoding.UTF8.GetBytes(p_string); var hashedInputBytes = p_hashAlgorithm.ComputeHash(bytes); // Convert to text // StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte var hashedInputStringBuilder = new System.Text.StringBuilder(128); foreach (var b in hashedInputBytes) { hashedInputStringBuilder.Append(b.ToString("X2")); } var v_hash = hashedInputStringBuilder.ToString(); return(v_hash); } return(""); }
/// <summary> /// Calculates the hash of the filename using the specified HashAlgorithm and adds it to the MemoryStream /// </summary> /// <param name="memStream">MemoryStream containing hash bytes</param> /// <param name="algo">HashAlgorithm to compute hash (MD5, SHA1, SHA256, etc)</param> private void AddFilenameHash(Stream memStream, System.Security.Cryptography.HashAlgorithm algo) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(FilePath); if (fileNameWithoutExtension == null) { return; } var fileNameNoExt = Encoding.UTF8.GetBytes(fileNameWithoutExtension.ToLower()); if (fileNameNoExt.Length <= 0) { return; } var hashFileName = algo.ComputeHash(fileNameNoExt); if (hashFileName.Length > 0) { memStream.Write(hashFileName, 0, hashFileName.Length); } }
/// <summary> /// Calculate hash using SHA512 /// </summary> /// <param name="includeFilename">If true, the filename is including when computing the hash</param> /// <returns>A string representation of the computed hash</returns> private string CalculateHash(bool includeFilename, System.Security.Cryptography.HashAlgorithm algo) { var hash = string.Empty; using (var memStream = new MemoryStream()) { if (includeFilename) { AddFilenameHash(memStream, algo); } try { using (var fileStream = GetFileStream()) { if (fileStream == null) { return(hash); } var hashFile = algo.ComputeHash(fileStream); memStream.Write(hashFile, 0, hashFile.Length); } } catch (IOException ex) { Debug.WriteLine("The following error occurred trying to compute hash of file contents:" + ex.Message); return(hash); } memStream.Seek(0, SeekOrigin.Begin); return(CalculateHashString(algo, memStream)); } }
public ValidationError ValidationHandler2(XmlDocument xmlDoc, string xmlFileName) { ValidationError validationError = new ValidationError(xmlFileName, null); TimeStampToken token = XmlNodeHelper.GetTimeStampToken(xmlDoc); byte[] timesStampDigestArray = token.TimeStampInfo.GetMessageImprintDigest(); string hashAlgorithmId = token.TimeStampInfo.HashAlgorithm.Algorithm.Id; var signatureEle = xmlDoc.SelectXmlNode("//ds:Signature/ds:SignatureValue"); if (signatureEle == null) { return(validationError.AppendErrorMessage("Missing SignatureValue element.")); } byte[] signatureValueByteArray = Convert.FromBase64String(signatureEle.InnerText); var signatureMethodAlgorithm = xmlDoc.SelectXmlNode("//ds:SignedInfo/ds:SignatureMethod").AtrValue("Algorithm"); if (signatureMethodAlgorithm != "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") { return(validationError.AppendErrorMessage($"Unknown SignatureMethod Algorithm {signatureMethodAlgorithm}.")); } System.Security.Cryptography.HashAlgorithm hashAlgo = System.Security.Cryptography.SHA256Managed.Create(); var conputedSignatureByteArray = hashAlgo.ComputeHash(signatureValueByteArray); if (!StructuralComparisons.StructuralEqualityComparer.Equals(conputedSignatureByteArray, timesStampDigestArray)) { return(validationError.AppendErrorMessage("Missing SignatureValue element.")); } return(validationError); }
/// <summary> /// Calculates hash and returns it in string format /// </summary> /// <param name="algo">System.Security.Cryptography.HashAlgorithm to use</param> /// <param name="stream">Stream to read from</param> /// <returns>Hash in string format</returns> private static IEnumerable <byte> CalculateHashBytes(System.Security.Cryptography.HashAlgorithm algo, Stream stream) { return(algo.ComputeHash(stream)); }
/// <summary> /// RSA加密解密及RSA签名和验证 /// </summary> public class RSA { #region RSA 加密解密 #region RSA 的密钥产生 /// <summary> /// RSA 的密钥产生 产生私钥 和公钥 /// </summary> /// <param name="xmlKeys"></param> /// <param name="xmlPublicKey"></param> public Tuple<string,string> generateKey() { System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string xmlKeys = rsa.ToXmlString(true); string xmlPublicKey = rsa.ToXmlString(false); return Tuple.Create<string, string>(xmlKeys, xmlPublicKey); } #endregion #region RSA的加密函数 //############################################################################## //RSA 方式加密 //说明KEY必须是XML的行式,返回的是字符串 //在有一点需要说明!!该加密方式有 长度 限制的!! //############################################################################## //RSA的加密函数 string public string encrypt(string xmlPublicKey, string m_strEncryptString) { byte[] PlainTextBArray; byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString); CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } //RSA的加密函数 byte[] public string encrypt(string xmlPublicKey, byte[] EncryptString) { byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); CypherTextBArray = rsa.Encrypt(EncryptString, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } #endregion #region RSA的解密函数 //RSA的解密函数 string public string decrypt(string xmlPrivateKey, string m_strDecryptString) { byte[] PlainTextBArray; byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); PlainTextBArray = Convert.FromBase64String(m_strDecryptString); DypherTextBArray = rsa.Decrypt(PlainTextBArray, false); Result = (new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } //RSA的解密函数 byte public string decrypt(string xmlPrivateKey, byte[] DecryptString) { byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); DypherTextBArray = rsa.Decrypt(DecryptString, false); Result = (new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } #endregion #endregion #region RSA数字签名 #region 获取Hash描述表 //获取Hash描述表 public bool GetHash(string m_strSource, ref byte[] HashData) { //从字符串中取得Hash描述 byte[] Buffer; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); return true; } //获取Hash描述表 public bool GetHash(string m_strSource, ref string strHashData) { //从字符串中取得Hash描述 byte[] Buffer; byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); strHashData = Convert.ToBase64String(HashData); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData) { //从文件中取得Hash描述 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref string strHashData) { //从文件中取得Hash描述 byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); strHashData = Convert.ToBase64String(HashData); return true; } #endregion #region RSA签名 //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] EncryptedSignatureData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData) { byte[] HashbyteSignature; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] HashbyteSignature; byte[] EncryptedSignatureData; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } #endregion #region RSA 签名验证 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData) { byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(p_strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(p_strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } } #endregion #endregion
/// <summary> /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed. /// </summary> /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param> /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param> /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param> /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param> /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param> /// <returns></returns> public static Dictionary <string, object> GetFeed(string feedUrl, string detailPage, int cacheDuration, ref Dictionary <string, string> message, ref bool isError) { Dictionary <string, object> feedDictionary = new Dictionary <string, object>(); if (message == null) { message = new Dictionary <string, string>(); } if (String.IsNullOrEmpty(feedUrl)) { message.Add("Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings."); return(feedDictionary); } if (!System.Text.RegularExpressions.Regex.IsMatch(feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?")) { message.Add("Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings."); isError = false; return(feedDictionary); } ObjectCache feedCache = MemoryCache.Default; if (feedCache[GetFeedCacheKey(feedUrl)] != null) { feedDictionary = (Dictionary <string, object>)feedCache[GetFeedCacheKey(feedUrl)]; } else { XDocument feed = null; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(feedUrl); using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { if (resp.StatusCode == HttpStatusCode.OK) { XmlReader feedReader = XmlReader.Create(resp.GetResponseStream()); feed = XDocument.Load(feedReader); feedReader.Close(); } else { message.Add("Error loading feed.", string.Format("An error has occurred while loading the feed. Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription)); isError = true; } } if (feed != null) { string detailPageBaseUrl = string.Empty; int detailPageID = 0; if (!String.IsNullOrEmpty(detailPage)) { detailPageID = new Rock.Model.PageService(new Rock.Data.RockContext()).Get(new Guid(detailPage)).Id; detailPageBaseUrl = new PageReference(detailPageID).BuildUrl(); } if (detailPageID > 0) { detailPageBaseUrl = new PageReference(detailPageID).BuildUrl(); } Dictionary <string, XNamespace> namespaces = feed.Root.Attributes() .Where(a => a.IsNamespaceDeclaration) .GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)) .ToDictionary(g => g.Key, g => g.First()); feedDictionary = BuildElementDictionary(feed.Elements().First(), namespaces); if (feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary <string, object>)) { feedDictionary = (Dictionary <string, object>)feedDictionary.First().Value; } if (feedDictionary.ContainsKey("lastBuildDate")) { feedDictionary["lastBuildDate"] = DateTimeOffset.Parse(feedDictionary["lastBuildDate"].ToString()).LocalDateTime; } if (feedDictionary.ContainsKey("updated")) { feedDictionary["updated"] = DateTimeOffset.Parse(feedDictionary["updated"].ToString()).LocalDateTime; } if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry")) { List <Dictionary <string, object> > articles = (List <Dictionary <string, object> >)feedDictionary.Where(x => x.Key == "item" || x.Key == "entry").FirstOrDefault().Value; foreach (var article in articles) { string idEntry = String.Empty; string idEntryHashed = string.Empty; if (article.ContainsKey("id")) { idEntry = article["id"].ToString(); } if (article.ContainsKey("guid")) { if (article["guid"].GetType() == typeof(Dictionary <string, object>)) { idEntry = ((Dictionary <string, object>)article["guid"])["value"].ToString(); } else { idEntry = article["guid"].ToString(); } } if (!String.IsNullOrWhiteSpace(idEntry)) { System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (byte b in hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(idEntry))) { sb.Append(b.ToString("X2")); } idEntryHashed = sb.ToString(); Dictionary <string, string> queryString = new Dictionary <string, string>(); queryString.Add("feedItemId", idEntryHashed); if (detailPageID > 0) { article.Add("detailPageUrl", new PageReference(detailPageID, 0, queryString).BuildUrl()); } article.Add("articleHash", idEntryHashed); } if (article.ContainsKey("pubDate")) { article["pubDate"] = DateTimeOffset.Parse(article["pubDate"].ToString()).LocalDateTime; } if (article.ContainsKey("updated")) { article["updated"] = DateTimeOffset.Parse(article["updated"].ToString()).LocalDateTime; } } } if (!String.IsNullOrEmpty(detailPageBaseUrl)) { feedDictionary.Add("DetailPageBaseUrl", detailPageBaseUrl); } } if (feedDictionary != null) { feedCache.Set(GetFeedCacheKey(feedUrl), feedDictionary, DateTimeOffset.Now.AddMinutes(cacheDuration)); } } return(feedDictionary); }
public static byte[] GetMd5Byte(string inputString) { System.Security.Cryptography.HashAlgorithm algorithm = MD5.Create(); //or use SHA1.Create(); return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString))); }
public static string ComputeHashString(this HashAlgorithm hash, byte[] buffer) { return(hash.ComputeHash(buffer).ConverterToHexString()); }
public static string ComputeHashString(this HashAlgorithm hash, string text) { return(hash.ComputeHash(text.GetBytes()).ConverterToHexString()); }
public static string ComputeHashString(this HashAlgorithm hash, byte[] buffer, int offset, int count) { return(hash.ComputeHash(buffer, offset, count).ConverterToHexString()); }
public static string ComputeHashString(this HashAlgorithm hash, Stream inputStream) { return(hash.ComputeHash(inputStream).ConverterToHexString()); }
/// <summary>Process a block of data.</summary> /// <param name="inputBuffer">The block of data to process.</param> /// <param name="inputOffset">Where to start in the block.</param> override protected void ProcessBlock(byte[] inputBuffer, int inputOffset) { lock (syncLock) { workingNodes.Add(new HashNode(hashAlgorithm.ComputeHash(inputBuffer, inputOffset, BlockSize), Count, (Count + BlockSize - 1))); } }
/// <summary> /// 计算指定 <see cref="Stream"/> 对象的哈希值。 /// </summary> /// <param name="hashAlgorithm">要计算的哈希算法</param> /// <param name="inputStream">要计算其哈希代码的输入</param> /// <param name="streamReadAction">没次读流时调用,例如用来获取进度</param> /// <returns>计算所得的哈希代码</returns> public static byte[] ComputeHash(this HashAlgorithm hashAlgorithm, Stream inputStream, Action streamReadAction) { using (var readStream = new ReadStream(inputStream, streamReadAction)) return(hashAlgorithm.ComputeHash(readStream)); }
#pragma warning disable 809 public override byte[] GetBytes(int cb) { #pragma warning restore 809 if (cb < 1) { throw new IndexOutOfRangeException("cb"); } if (state == 0) { // it's now impossible to change the HashName, Salt // and IterationCount Reset(); state = 1; } byte[] result = new byte [cb]; int cpos = 0; // the initial hash (in reset) + at least one iteration int iter = Math.Max(1, IterationsValue - 1); // start with the PKCS5 key if (output == null) { // calculate the PKCS5 key output = initial; // generate new key material for (int i = 0; i < iter - 1; i++) { output = hash.ComputeHash(output); } } while (cpos < cb) { byte[] output2 = null; if (hashnumber == 0) { // last iteration on output output2 = hash.ComputeHash(output); } else if (hashnumber < 1000) { string n = Convert.ToString(hashnumber); output2 = new byte [output.Length + n.Length]; for (int j = 0; j < n.Length; j++) { output2 [j] = (byte)(n [j]); } Buffer.BlockCopy(output, 0, output2, n.Length, output.Length); // don't update output output2 = hash.ComputeHash(output2); } else { throw new CryptographicException( Locale.GetText("too long")); } int rem = output2.Length - position; int l = Math.Min(cb - cpos, rem); Buffer.BlockCopy(output2, position, result, cpos, l); cpos += l; position += l; while (position >= output2.Length) { position -= output2.Length; hashnumber++; } } return(result); }
private static string ComputeHash(string input, System.Security.Cryptography.HashAlgorithm algorithm) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input); byte[] value = algorithm.ComputeHash(bytes); return(System.BitConverter.ToString(value)); }
static public byte[] SHA1(byte[] message) { HashAlgorithm ha = new System.Security.Cryptography.HashAlgorithm(HashAlgorithmType.SHA1); return(ha.ComputeHash(message)); }
public static byte[] Hash(byte[] input, HashAlgorithm algorithm) { System.Security.Cryptography.HashAlgorithm hasher = GetAlgorithm(algorithm); byte[] hashByte = hasher.ComputeHash(input); return(hashByte); }
/// <summary> /// Calculates hash and returns as byte array /// </summary> /// <param name="algo">System.Security.Cryptography.HashAlgorithm to use</param> /// <param name="bytes">Bytes to generate hash from</param> /// <returns>Hash in byte array</returns> private static byte[] CalculateHashBytes(System.Security.Cryptography.HashAlgorithm algo, byte[] bytes) { return(algo.ComputeHash(bytes)); }