private void SetUp(long length) { this.transmission = new Transmission(TransmissionType.DOWNLOAD_NEW_FILE, "testfile"); this.transmission.AddDefaultConstraints(); if (this.localFileStream != null) { this.localFileStream.Dispose(); } this.localFileStream = new MemoryStream(); if (this.hashAlg != null) { this.hashAlg.Dispose(); } this.hashAlg = new SHA1Managed(); this.remoteLength = length; this.remoteContent = new byte[this.remoteLength]; if (this.random != null) { this.random.Dispose(); } this.random = RandomNumberGenerator.Create(); this.random.GetBytes(this.remoteContent); this.mockedMemStream = new Mock<MemoryStream>(this.remoteContent) { CallBase = true }; this.mockedStream = new Mock<IContentStream>(); this.mockedStream.Setup(stream => stream.Length).Returns(this.remoteLength); this.mockedStream.Setup(stream => stream.Stream).Returns(this.mockedMemStream.Object); this.mockedDocument = new Mock<IDocument>(); this.mockedDocument.Setup(doc => doc.ContentStreamLength).Returns(this.remoteLength); this.mockedDocument.Setup(doc => doc.GetContentStream()).Returns(this.mockedStream.Object); }
public Hasher(string hashType, string valueToHash) { _hashType = GetHashAlgorithm(hashType); if (!String.IsNullOrEmpty(valueToHash) && valueToHash != _valueToHash) _valueToHash = valueToHash; }
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 VartotojaiController(IAuthenticationProvider authenticationProvider, ISessionFactory sessionFactory, [LoggedIn] UserInformation loggedInUser, HashAlgorithm hashAlgorithm) { _authenticationProvider = authenticationProvider; _sessionFactory = sessionFactory; _loggedInUser = loggedInUser; _hashAlgorithm = hashAlgorithm; }
public HashcodeGenerator (String key, HashAlgorithm algorithm, String format, Guid guid, bool returnBase64, params object[] hashArray) { _returnBase64 = returnBase64; _hashArray = hashArray; _algorithm = algorithm; _format = format; _key = FormatKey(key, _format); }
public static string Hash(this string plaintext, HashAlgorithm algorithm) { if (string.IsNullOrEmpty(plaintext)) throw new ArgumentNullException("plaintext", "Cannot hash an empty string."); var clearBuffer = UTF8Encoding.Default.GetBytes(plaintext); return Hash(clearBuffer, algorithm); }
public HashingStreamEx(Stream sBaseStream, bool bWriting, HashAlgorithm hashAlgorithm) { if(sBaseStream == null) throw new ArgumentNullException("sBaseStream"); m_sBaseStream = sBaseStream; m_bWriting = bWriting; #if !KeePassLibSD m_hash = (hashAlgorithm ?? new SHA256Managed()); #else // KeePassLibSD m_hash = null; try { m_hash = HashAlgorithm.Create("SHA256"); } catch(Exception) { } try { if(m_hash == null) m_hash = HashAlgorithm.Create(); } catch(Exception) { } #endif if(m_hash == null) { Debug.Assert(false); return; } // Validate hash algorithm if((!m_hash.CanReuseTransform) || (!m_hash.CanTransformMultipleBlocks) || (m_hash.InputBlockSize != 1) || (m_hash.OutputBlockSize != 1)) { #if DEBUG MessageService.ShowWarning("Broken HashAlgorithm object in HashingStreamEx."); #endif m_hash = null; } }
public void ComputeHash(HashAlgorithm hash) { byte[] tmp = Encoding.UTF8.GetBytes (_name); hash.TransformBlock (tmp, 0, tmp.Length, null, 0); tmp = Encoding.UTF8.GetBytes (_body); hash.TransformBlock (tmp, 0, tmp.Length, null, 0); }
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; }
public static string HashWith(this string input, HashAlgorithm algorithm) { byte[] data = Encoding.UTF8.GetBytes(input); byte[] hash = algorithm.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; }
/// <summary> /// Creates a message digest using the specified name to set Algorithm property. /// </summary> /// <param name="algorithm">The name of the algorithm to use</param> public MD5Support(string algorithm) { var algorithmName = algorithm.Equals("SHA-1") ? "SHA" : algorithm; _algorithm = (HashAlgorithm) CryptoConfig.CreateFromName(algorithmName); data = new byte[0]; _position = 0; }
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 static string GenerateStringHash(string stringForHashing, HashAlgorithm hashAlgorithm) { if (hashAlgorithm is KeyedHashAlgorithm) throw new NotSupportedException("It is impossible to create Hash with KeyedHashAlgorithm and empty Salt"); return GenerateStringHash(stringForHashing, string.Empty, hashAlgorithm); }
private static string Hash(byte[] clearBuffer, HashAlgorithm algorithm) { System.Security.Cryptography.HashAlgorithm hashAlgorithm; switch (algorithm) { case HashAlgorithm.MD5: hashAlgorithm = new MD5CryptoServiceProvider(); break; case HashAlgorithm.SHA1: default: hashAlgorithm = new SHA1CryptoServiceProvider(); break; case HashAlgorithm.SHA256: hashAlgorithm = new SHA256CryptoServiceProvider(); break; case HashAlgorithm.SHA384: hashAlgorithm = new SHA384CryptoServiceProvider(); break; case HashAlgorithm.SHA512: hashAlgorithm = new SHA512CryptoServiceProvider(); break; } var encryptedBuffer = hashAlgorithm.ComputeHash(clearBuffer); return Convert.ToBase64String(encryptedBuffer); }
/// <summary> /// Initializes a new instance of the <see cref="SaltedHash"/> class. /// </summary> /// <param name="hashAlgorithm">A <see cref="HashAlgorithm"/> HashAlgorihm which is derived from HashAlgorithm. C# provides /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider</param> /// <param name="saltLength">Length of the salt.</param> public SaltedHash(HashAlgorithm hashAlgorithm, int saltLength) { Check.NotNull(hashAlgorithm, nameof(hashAlgorithm)); Check.Positive(saltLength, nameof(saltLength)); this.hashAlgorithm = hashAlgorithm; this.saltLength = saltLength; }
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); }
/// <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 ) ); }
/// <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); }
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; }
public static string computeHash(string password, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(password); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); }
/// <summary> /// Initializes a new StringEncryption instance. /// </summary> /// <param name="bulkCipher">The bulk cipher algorithm to use.</param> /// <param name="hash">The hash algorithm to use.</param> /// <exception cref="ArgumentNullException">One of the parameters is a null reference.</exception> public StringEncryption(SymmetricAlgorithm bulkCipher, HashAlgorithm hash) { if (bulkCipher == null) throw new ArgumentNullException("bulkCipher", ResourceController.GetString("Error_ParamNull")); if (hash == null) throw new ArgumentNullException("hash", ResourceController.GetString("Error_ParamNull")); Init(bulkCipher, hash); }
public RSASigner(RSACryptoServiceProvider provider) { _rsaCrypto = provider; _blockLength = _rsaCrypto.ExportParameters(false).Modulus.Length; _maxBlockLengthWithPadding = _blockLength - Padding; _algorithm = SHA1.Create(); }
internal static int GetCode( HashAlgorithm algorithm, string secret, long counter, int digits) { Contract.Requires<ArgumentOutOfRangeException>(Enum.IsDefined(typeof(HashAlgorithm), algorithm)); Contract.Requires<ArgumentOutOfRangeException>(algorithm != HashAlgorithm.Unknown); Contract.Requires<ArgumentNullException>(secret != null); Contract.Requires<ArgumentOutOfRangeException>(counter >= 0); Contract.Requires<ArgumentOutOfRangeException>(digits > 0); Contract.Ensures(Contract.Result<int>() > 0); Contract.Ensures(Contract.Result<int>() < Math.Pow(10, digits)); var generator = HMAC.Create(algorithm.ToAlgorithmName()); generator.Key = Encoding.ASCII.GetBytes(secret); generator.ComputeHash(CounterToBytes(counter)); var hmac = generator .Hash .Select(b => Convert.ToInt32(b)) .ToArray(); var offset = hmac[19] & 0xF; var code = (hmac[offset + 0] & 0x7F) << 24 | (hmac[offset + 1] & 0xFF) << 16 | (hmac[offset + 2] & 0xFF) << 8 | (hmac[offset + 3] & 0xFF); return code % (int) Math.Pow(10, digits); }
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()); }
public HashingStreamEx(Stream sBaseStream, bool bWriting, HashAlgorithm hashAlgorithm) { if(sBaseStream == null) throw new ArgumentNullException("sBaseStream"); m_sBaseStream = sBaseStream; m_bWriting = bWriting; #if !KeePassLibSD m_hash = (hashAlgorithm ?? new SHA256Managed()); #else // KeePassLibSD m_hash = null; try { m_hash = HashAlgorithm.Create("SHA256"); } catch(Exception) { } try { if(m_hash == null) m_hash = HashAlgorithm.Create(); } catch(Exception) { } #endif if(m_hash == null) { Debug.Assert(false); return; } // Validate hash algorithm if(!m_hash.CanReuseTransform || !m_hash.CanTransformMultipleBlocks) { Debug.Assert(false); m_hash = null; } }
/// <summary>Compute hash on input string</summary> /// <param name="file">The file to get hash from.</param> /// <param name="algorithm"> </param> /// <returns>The hash as a hexadecimal String.</returns> public static string ComputeHash(this FileInfo file, HashAlgorithm algorithm) { using (var stream = new BufferedStream(file.OpenRead(), 1024 * 8)) { return ComputeHash(stream, algorithm); } }
/// <summary> /// Constructor for HashStream. The HashAlgorithm instance is owned by the caller. /// </summary> public HashStream(HashAlgorithm hash) { if (hash == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("hash"); Reset(hash); }
public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (this.IsInNodeSet) { byte[] bytes; UTF8Encoding encoding = new UTF8Encoding(false); if (docPos == DocPosition.AfterRootElement) { bytes = encoding.GetBytes("(char) 10"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } bytes = encoding.GetBytes("<?"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = encoding.GetBytes(this.Name); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); if ((this.Value != null) && (this.Value.Length > 0)) { bytes = encoding.GetBytes(" " + this.Value); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } bytes = encoding.GetBytes("?>"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); if (docPos == DocPosition.BeforeRootElement) { bytes = encoding.GetBytes("(char) 10"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } }
/// <summary> /// Constructor /// </summary> /// <remarks>If <paramref name="hashAlgo"/> is an unsupported hash algorithm, then /// <see cref="AssemblyHashAlgorithm.SHA1"/> will be used as the hash algorithm.</remarks> /// <param name="hashAlgo">The algorithm to use</param> public AssemblyHash(AssemblyHashAlgorithm hashAlgo) { switch (hashAlgo) { case AssemblyHashAlgorithm.MD5: hasher = MD5.Create(); break; case AssemblyHashAlgorithm.None: case AssemblyHashAlgorithm.MD2: case AssemblyHashAlgorithm.MD4: case AssemblyHashAlgorithm.SHA1: case AssemblyHashAlgorithm.MAC: case AssemblyHashAlgorithm.SSL3_SHAMD5: case AssemblyHashAlgorithm.HMAC: case AssemblyHashAlgorithm.TLS1PRF: case AssemblyHashAlgorithm.HASH_REPLACE_OWF: default: hasher = SHA1.Create(); break; case AssemblyHashAlgorithm.SHA_256: hasher = SHA256.Create(); break; case AssemblyHashAlgorithm.SHA_384: hasher = SHA384.Create(); break; case AssemblyHashAlgorithm.SHA_512: hasher = SHA512.Create(); break; } }
public ColumnsSettingsProvider(string docPath) { _algorithm = new RijndaelManaged(); _hashAlgorithm = new SHA384Managed(); SetDocument(docPath); }
//获取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); }
//获取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); }
/// <summary> compute the file's MD5 value </summary> /// <param name="fileName">file's name</param> /// <returns> the file's MD5 value</returns> public static string GetMD5Hash(string fileName) { if (!File.Exists(fileName)) { return(string.Empty); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { System.Security.Cryptography.HashAlgorithm md5 = System.Security.Cryptography.MD5.Create(); return(BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "")); } }
public static byte[] BaseHash(this string source, System.Security.Cryptography.HashAlgorithm algorithm, string encoding) { byte[] inputBytes = Encoding.GetEncoding(encoding).GetBytes(source); if (algorithm == null) { return(inputBytes); } using (algorithm) { return(algorithm.ComputeHash(inputBytes)); } }
internal string GetFileSha512(string fileSavePath) { Utils utils = new Utils(); System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.SHA512.Create(); FileStream fs = new FileStream(fileSavePath, FileMode.Open, FileAccess.Read); byte[] hash = ha.ComputeHash(fs); fs.Close(); string h2 = utils.HexDump(hash); return(h2.Replace(" ", "").Replace("\r\n", "")); }
public byte[] Sign(byte[] securedInput, object key) { byte[] numArray; RSA rSA = Ensure.Type <RSA>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.", new object[0]); using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = this.HashAlgorithm) { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(rSA); rSAPKCS1SignatureFormatter.SetHashAlgorithm(this.hashMethod); numArray = rSAPKCS1SignatureFormatter.CreateSignature(hashAlgorithm.ComputeHash(securedInput)); } return(numArray); }
public string HashMD5(string strToHash, string provider) { try { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); System.Security.Cryptography.HashAlgorithm alg = System.Security.Cryptography.HashAlgorithm.Create(provider); return(ByteArrayToUrlString(alg.ComputeHash(encoding.GetBytes(strToHash)))); } catch (Exception ex) { return(ex.Message); } }
/// <summary> 哈希密码加密(不可还原) </summary> /// <param name="s">原始字符串</param> /// <param name="saltKey">Salt加密字符串</param> /// <param name="hashName">加密格式(MD5, SHA1, SHA256, SHA384, SHA512.)</param> /// <returns>加密过的密码</returns> static public string EncryptToHashString(string s, string saltKey, string hashName) { byte[] src = System.Text.Encoding.Unicode.GetBytes(s); byte[] saltbuf = Convert.FromBase64String(saltKey); byte[] dst = new byte[saltbuf.Length + src.Length]; byte[] inArray = null; System.Buffer.BlockCopy(saltbuf, 0, dst, 0, saltbuf.Length); System.Buffer.BlockCopy(src, 0, dst, saltbuf.Length, src.Length); System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName); inArray = algorithm.ComputeHash(dst); return(Convert.ToBase64String(inArray)); }
private HashMembershipCondition(SerializationInfo info, StreamingContext context) { this.m_value = (byte[])info.GetValue("HashValue", typeof(byte[])); string hashName = (string)info.GetValue("HashAlgorithm", typeof(string)); if (hashName != null) { this.m_hashAlg = System.Security.Cryptography.HashAlgorithm.Create(hashName); } else { this.m_hashAlg = new SHA1Managed(); } }
public HashMembershipCondition(System.Security.Cryptography.HashAlgorithm hashAlg, byte[] value) { if (value == null) { throw new ArgumentNullException("value"); } if (hashAlg == null) { throw new ArgumentNullException("hashAlg"); } this.m_value = new byte[value.Length]; Array.Copy(value, this.m_value, value.Length); this.m_hashAlg = hashAlg; }
public bool Verify(byte[] signature, byte[] securedInput, object key) { bool flag; using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = this.HashAlgorithm) { AsymmetricAlgorithm asymmetricAlgorithm = Ensure.Type <AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.", new object[0]); byte[] numArray = hashAlgorithm.ComputeHash(securedInput); RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new RSAPKCS1SignatureDeformatter(asymmetricAlgorithm); rSAPKCS1SignatureDeformatter.SetHashAlgorithm(this.hashMethod); flag = rSAPKCS1SignatureDeformatter.VerifySignature(numArray, signature); } return(flag); }
//获取Hash描述表 public bool GetHash(string mStrSource, ref string strHashData) { if (strHashData == null) { throw new ArgumentNullException(nameof(strHashData)); } //从字符串中取得Hash描述 System.Security.Cryptography.HashAlgorithm md5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); var buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(mStrSource); var hashData = md5.ComputeHash(buffer); strHashData = Convert.ToBase64String(hashData); return(true); }
private string _HashStandard(string file, System.Security.Cryptography.HashAlgorithm algorithm) { string ret; using (var fs = new FileStream(file, FileMode.Open)) { using (algorithm) { var hash = algorithm.ComputeHash(fs); ret = _FormatBytes(hash); } } return(ret); }
/// <summary> /// 获取Hash描述表 /// </summary> /// <param name="objFile">待签名的文件</param> /// <param name="HashData">Hash描述</param> /// <returns></returns> public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData) { try { //从文件中取得Hash描述 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); return(true); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取Hash描述表 /// </summary> /// <param name="strSource">待签名的字符串</param> /// <param name="HashData">Hash描述</param> /// <returns></returns> public bool GetHash(string strSource, ref byte[] HashData) { try { byte[] Buffer; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strSource); HashData = MD5.ComputeHash(Buffer); return(true); } catch (Exception ex) { throw ex; } }
private string GenerateNonUdon(string input, System.Security.Cryptography.HashAlgorithm algorithm) { using (var hash = algorithm) { var bytes = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)); string output = ""; foreach (byte x in bytes) { output += string.Format("{0:x2}", x); } return(output); } }
//获取Hash描述表 public static bool GetHash(string m_strSource, ref byte[] HashData) { try { //从字符串中取得Hash描述 byte[] Buffer; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.Default.GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); return(true); } catch (Exception ex) { throw ex; } }
private static bool getHashData(string strSource, ref byte[] HashData) { try { byte[] Buffer; System.Security.Cryptography.HashAlgorithm SHA1 = System.Security.Cryptography.HashAlgorithm.Create(SIGN_ALGORITHMS); System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create(); Buffer = System.Text.Encoding.GetEncoding(CHAR_SET).GetBytes(strSource); HashData = sha1.ComputeHash(Buffer); return(true); } catch (System.Exception ex) { throw ex; } }
/// <summary> /// 获取Hash描述表 /// </summary> /// <param name="objFile">待签名的文件</param> /// <param name="strHashData">Hash描述</param> /// <returns></returns> public static bool GetHash(System.IO.FileStream objFile, out 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; } }
public void FromXml(SecurityElement e, PolicyLevel level) { if (e == null) { throw new ArgumentNullException("e"); } if (!e.Tag.Equals("IMembershipCondition")) { throw new ArgumentException(Environment.GetResourceString("Argument_MembershipConditionElement")); } lock (this.InternalSyncObject) { this.m_element = e; this.m_value = null; this.m_hashAlg = null; } }
/// <summary> /// Encrypt original string to MD5 string. /// </summary> /// <param name="value">The original string.</param> /// <returns>Returns encrypt string.</returns> public static string Encrypt(string value) { string ret = string.Empty; // byte array representation of that string byte[] encodedPassword = new UTF8Encoding().GetBytes(value); // need MD5 to calculate the hash cypt.HashAlgorithm algo = (cypt.HashAlgorithm)cypt.CryptoConfig.CreateFromName("MD5"); byte[] hash = algo.ComputeHash(encodedPassword); // string representation (similar to UNIX format) ret = BitConverter.ToString(hash) // without dashes .Replace("-", string.Empty) // make lowercase .ToLower(); return(ret); }
/// <summary> /// 获取Hash描述表 /// </summary> /// <param name="strSource">待签名的字符串</param> /// <param name="strHashData">Hash描述</param> /// <returns></returns> public static bool GetHash(string strSource, out 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); }
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(""); }
private void ParseHashAlgorithm() { lock (this.InternalSyncObject) { if (this.m_element != null) { string hashName = this.m_element.Attribute("HashAlgorithm"); if (hashName != null) { this.m_hashAlg = System.Security.Cryptography.HashAlgorithm.Create(hashName); } else { this.m_hashAlg = new SHA1Managed(); } if ((this.m_value != null) && (this.m_hashAlg != null)) { this.m_element = null; } } } }
/// <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> /// 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