예제 #1
20
파일: MD5SHAHelper.cs 프로젝트: kLeZ/Gecko
 public static HashAlgorithm GetHashProvider(HashType type)
 {
     HashAlgorithm hash = null;
     switch (type)
     {
         case HashType.MD5:
             {
                 hash = new MD5CryptoServiceProvider();
                 break;
             }
         case HashType.SHA1:
             {
                 hash = new SHA1CryptoServiceProvider();
                 break;
             }
         case HashType.SHA256:
             {
                 hash = new SHA256CryptoServiceProvider();
                 break;
             }
         case HashType.SHA384:
             {
                 hash = new SHA384CryptoServiceProvider();
                 break;
             }
         case HashType.SHA512:
             {
                 hash = new SHA512CryptoServiceProvider();
                 break;
             }
     }
     return hash;
 }
예제 #2
0
 /// <summary>Generates the hash of a text.</summary>
 /// <param name="strPlain">The text of which to generate a hash of.</param>
 /// <param name="hshType">The hash function to use.</param>
 /// <returns>The hash as a hexadecimal string.</returns>
 public static string GetHash(string strPlain, HashType hshType)
 {
     string strRet;
     switch (hshType)
     {
         case HashType.MD5:
             strRet = GetMD5(strPlain);
             break;
         case HashType.SHA1:
             strRet = GetSHA1(strPlain);
             break;
         case HashType.SHA256:
             strRet = GetSHA256(strPlain);
             break;
         case HashType.SHA384:
             strRet = GetSHA384(strPlain);
             break;
         case HashType.SHA512:
             strRet = GetSHA512(strPlain);
             break;
         default:
             strRet = "Invalid HashType";
             break;
     }
     return strRet;
 }
        internal static string HashString(string IN_STRING, HashType algo)
        {
            byte[] inStringBytes = null, hashBytes = null;

            inStringBytes = Encoding.ASCII.GetBytes(IN_STRING);

            switch (algo)
            {
                case HashType.MD5:
                    hashBytes = MD5.Create().ComputeHash(inStringBytes);
                    break;
                case HashType.SHA1:
                    hashBytes = SHA1.Create().ComputeHash(inStringBytes);
                    break;
                case HashType.SHA256:
                    hashBytes = SHA256.Create().ComputeHash(inStringBytes);
                    break;
                case HashType.SHA384:
                    hashBytes = SHA384.Create().ComputeHash(inStringBytes);
                    break;
                case HashType.SHA512:
                    hashBytes = SHA512.Create().ComputeHash(inStringBytes);
                    break;
            }

            return MakeHashString(hashBytes);
        }
 public byte[] AddFile(ulong streamId, Stream file, HashType type = HashType.None)
 {
     EnsureMaximumState(ArchiveState.PushingFiles);
     if (_state == ArchiveState.Initial)
     {
         _outputFilter = DoOutputFiltering(_hashedStream);
         _state = ArchiveState.PushingFiles;
     }
     byte[] ret = null;
     _streamIds.Add(streamId);
     _streamSizes.Add(file.Length);
     Stream stream = file;
     HashAlgorithm hash = null;
     if (type != HashType.None)
     {
         hash = Hash.New(type);
         stream = new HashCalculatorInputFilter(stream, hash);
     }
     stream.CopyTo(_outputFilter);
     if (type != HashType.None)
     {
         stream.Dispose();
         hash.FinishHashing();
         ret = hash.Hash;
     }
     AnyFile = true;
     return ret;
 }
예제 #5
0
파일: Utils.cs 프로젝트: xuanloc/Projects
 public static string GetHash(string text, HashType hashType)
 {
     HashAlgorithm _algorithm;
     switch (hashType)
     {
         case HashType.MD5:
             _algorithm = MD5.Create();
             break;
         case HashType.SHA1:
             _algorithm = SHA1.Create();
             break;
         case HashType.SHA256:
             _algorithm = SHA256.Create();
             break;
         case HashType.SHA512:
             _algorithm = SHA512.Create();
             break;
         default:
             throw new ArgumentException("Invalid hash type", "hashType");
     }
     byte[] bytes = Encoding.Unicode.GetBytes(text);
     byte[] hash = _algorithm.ComputeHash(bytes);
     string hashString = string.Empty;
     foreach (byte x in hash)
     {
         hashString += String.Format("{0:x2}", x);
     }
     return hashString;
 }
예제 #6
0
 internal byte[] GetHashForVerification(HashType hashType, uint index, byte[] scriptPubKey)
 {
     using (MemoryStream ms = new MemoryStream())
     using (BinaryWriter writer = new BinaryWriter(ms))
     {
         writer.Write(Version);
         writer.WriteVarInt(Inputs.Length);
         for (uint i = 0; i < Inputs.Length; i++)
         {
             writer.Write(Inputs[i].PrevHash);
             writer.Write(Inputs[i].PrevIndex);
             if (i == index)
             {
                 writer.WriteVarInt(scriptPubKey.Length);
                 writer.Write(scriptPubKey);
             }
             else
             {
                 writer.WriteVarInt(0);
             }
             writer.Write(uint.MaxValue);
         }
         writer.Write(Outputs);
         writer.Write(LockTime);
         writer.Write((int)hashType);
         writer.Flush();
         return ms.ToArray().Sha256().Sha256();
     }
 }
예제 #7
0
        public static HashAlgorithm Create(HashType hash)
        {
            switch (hash)
            {
                case HashType.CRC32:
                    return CRC32.Create();

                case HashType.MD5:
                    return MD5.Create();

                case HashType.SHA256:
                    return SHA256.Create();

                case HashType.SHA384:
                    return SHA384.Create();

                case HashType.SHA512:
                    return SHA512.Create();

                case HashType.SHA1:
                    return SHA1.Create();

                default:
                    throw new NotSupportedException("not support hash algorithm :" + hash.ToString());
            }
        }
예제 #8
0
        /// <summary>
        /// Get SHA Hash
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public virtual string GetHash(string plainText, HashType hashType, bool returnHex)
        {
            string hashText = string.Empty;

            switch (hashType)
            {
                case HashType.SHA1:
                    hashText = GetSHA1(plainText, returnHex);
                    break;

                case HashType.SHA256:
                    hashText = GetSHA256(plainText, returnHex);
                    break;

                case HashType.SHA384:
                    hashText = GetSHA384(plainText, returnHex);
                    break;

                case HashType.SHA512:
                    hashText = GetSHA512(plainText, returnHex);
                    break;
            }

            return hashText;
        }
예제 #9
0
        public static string Compute(HashType type, bool format, string data, string salt)
        {
            HashAlgorithm hash;
            string prefix;
            switch (type)
            {
                case HashType.MD5:
                    prefix = "MD5";
                    hash = new MD5Cng();
                    break;
                case HashType.SHA1:
                    prefix = "SHA1";
                    hash = new SHA1Cng();
                    break;
                case HashType.SHA256:
                    prefix = "SHA256";
                    hash = new SHA256Cng();
                    break;
                case HashType.SHA384:
                    prefix = "SHA384";
                    hash = new SHA384Cng();
                    break;
                case HashType.SHA512:
                    prefix = "SHA512";
                    hash = new SHA512Cng();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(salt+data);
            byte[] hashed = hash.ComputeHash(inputBytes);
            return format ? $"{{{prefix}:{GetHashHex(hashed)}}}" : GetHashHex(hashed);
        }
예제 #10
0
        public static string GetHash(string text, HashType hashType = HashType.SHA512)
        {
            HashAlgorithm hashAlgorithm = null;

            switch (hashType)
            {
                case HashType.MD5:
                    hashAlgorithm = new MD5CryptoServiceProvider();
                    break;

                case HashType.SHA1:
                    hashAlgorithm = new SHA1Managed();
                    break;

                case HashType.SHA256:
                    hashAlgorithm = new SHA256Managed();
                    break;

                case HashType.SHA512:
                    hashAlgorithm = new SHA512Managed();
                    break;
            }

            return ComputeHash(text, hashAlgorithm);
        }
        internal static string HashFile(string IN_FILE, HashType algo)
        {
            byte[] hashBytes = null;

            switch (algo)
            {
                case HashType.MD5:
                    hashBytes = MD5.Create().ComputeHash(new FileStream(IN_FILE, FileMode.Open));
                    break;
                case HashType.SHA1:
                    hashBytes = SHA1.Create().ComputeHash(new FileStream(IN_FILE, FileMode.Open));
                    break;
                case HashType.SHA256:
                    hashBytes = SHA256.Create().ComputeHash(new FileStream(IN_FILE, FileMode.Open));
                    break;
                case HashType.SHA384:
                    hashBytes = SHA384.Create().ComputeHash(new FileStream(IN_FILE, FileMode.Open));
                    break;
                case HashType.SHA512:
                    hashBytes = SHA512.Create().ComputeHash(new FileStream(IN_FILE, FileMode.Open));
                    break;
            }

            return MakeHashString(hashBytes);
        }
예제 #12
0
        internal static string HashFile(string filePath, HashType algo)
        {
            string hexStr;

            FileStream fstream = new FileStream(filePath, FileMode.Open);

            switch (algo)
            {
                case HashType.MD5:
                    hexStr = MD5.Create().ComputeHash(fstream).ToHex(true);
                    break;
                case HashType.SHA1:
                    hexStr = SHA1.Create().ComputeHash(fstream).ToHex(true);
                    break;
                case HashType.SHA512:
                    hexStr = SHA512.Create().ComputeHash(fstream).ToHex(true);
                    break;

                default:
                    hexStr = "";
                    break;
            }

            fstream.Close();

            return hexStr;
        }
예제 #13
0
        /// <summary>
        /// Computes the hash of given text using given hash algorithm
        /// </summary>
        public static string ComputeHash(HashType type, string text)
        {
            // Encode the text into byte array
            var data = (new UTF8Encoding()).GetBytes(text);
            // Create hash provider
            HashAlgorithm algorithm = null;
            switch (type)
            {
                case HashType.Sha1:
                    algorithm = new SHA1Managed();
                    break;

                case HashType.Sha256:
                    algorithm = new SHA1Managed();
                    break;

                case HashType.Sha512:
                    algorithm = new SHA1Managed();
                    break;

                default:
                    algorithm = new MD5CryptoServiceProvider();
                    break;
            }
            // Compute hash value
            var hash = algorithm.ComputeHash(data);
            // Decodes to string
            return Convert.ToBase64String(hash);
        }
예제 #14
0
파일: Program.cs 프로젝트: rmcgrail/hash
        internal static void ProcessSetting(string arg) {
            switch (arg.ToLower()) {
                case "/?":
                case "-h":
                case "--help":
                    ShowHelp = true;
                    break;
                    
                case "-ff":
                case "--filefirst":
                    FileFirst = true;
                    break;

                case "--md5":
                    HashType = HashType.Md5;
                    break;
                case "--sha1":
                    HashType = HashType.Sha1;
                    break;
                case "--sha256":
                    HashType = HashType.Sha256;
                    break;

                default:
                    if (arg.StartsWith("--") || arg.StartsWith("-") || arg.StartsWith("/"))
                        throw new ApplicationException("Unknown parameter.");
                    FilePath = arg;
                    break;
            }
        }
예제 #15
0
        public string GenerateHash( HashType HashType, string PlainText, string SaltText )
        {
            if (string.IsNullOrEmpty(PlainText)) {
                throw new ArgumentNullException( "PlainText", "Can't hash blank text" );
            }
            byte[] saltBytes = Encoding.UTF8.GetBytes( SaltText );
            if ( string.IsNullOrEmpty( SaltText ) || saltBytes.IsNullOrEmpty() ) {
                throw new ArgumentNullException( "Salt", "Salt can't be blank" );
            }

            byte[] plainTextBytes = Encoding.UTF8.GetBytes( PlainText );

            // Concatinate text and salt bytes
            byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

            for ( int i = 0; i < plainTextBytes.Length; i++ ) {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }
            for ( int i = 0; i < saltBytes.Length; i++ ) {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            HashAlgorithm hashAlgorithm = this.GetAlgorithm( HashType );
            byte[] hashBytes = hashAlgorithm.ComputeHash( plainTextWithSaltBytes );

            string hashValue = Convert.ToBase64String( hashBytes );
            return hashValue;
        }
예제 #16
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be hashed. The function does not check whether
        /// this parameter is null.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
        /// MD5 hashing algorithm will be used). This value is case-insensitive.
        /// </param>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string ComputeHash(string plainText,
                                         HashType hashType)
        {
            // Convert plain text into a byte array.
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text.
            var plainTextWithSaltBytes =
                new byte[plainTextBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
                plainTextWithSaltBytes[i] = plainTextBytes[i];

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Initialize appropriate hashing algorithm class.
            switch (hashType.ToString())
            {
                case "SHA1":
                    hash = new SHA1Managed();
                    break;

                case "SHA256":
                    hash = new SHA256Managed();
                    break;

                case "SHA384":
                    hash = new SHA384Managed();
                    break;

                case "SHA512":
                    hash = new SHA512Managed();
                    break;

                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
            }

            // Compute hash value of our plain text with appended salt.
            var hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            var hashWithSaltBytes = new byte[hashBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
                hashWithSaltBytes[i] = hashBytes[i];

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return hashValue;
        }
예제 #17
0
		public CloneableHash(int hash, HashType type, int size) {
			m_Provider = CAPIProvider.Handle;
			m_Type = type;
			m_Size = size;
			m_Disposed = false;
			if (SspiProvider.CryptDuplicateHash(hash, IntPtr.Zero, 0, out  m_Hash) == 0)
				throw new CryptographicException("Couldn't duplicate hash.");
		}
예제 #18
0
 public QueueItem(FileInfo file, QueueItemAction requestedAction, HashType type)
 {
     _File = file;
     _Type = type;
     _TestHash = String.Empty;
     _Action = requestedAction;
     _Results = QueueItemResult.NotTested; // this is wrong... do it different
 }
예제 #19
0
 public QueueItem(FileInfo file, string testHash, QueueItemAction requestedAction, HashType type)
 {
     _File = file;
     _Type = type;
     _TestHash = testHash;
     _Action = requestedAction;
     _Results = QueueItemResult.NotTested;
 }
예제 #20
0
        private static IHashAlgorithm CreateHasher(HashType hashType)
        {
            #if NETSTANDARD || NETFULL || NETCORE
             return new FullHashAlgorithm(hashType);
            #endif

             throw new NotImplementedException();
        }
예제 #21
0
파일: MD5SHAHelper.cs 프로젝트: kLeZ/Gecko
 public static string Encrypt(string toEncrypt, HashType hashType, Encoding enc)
 {
     string ret = "";
     byte[] rawBytes = enc.GetBytes(toEncrypt);
     HashAlgorithm hash = GetHashProvider(hashType);
     byte[] result = hash.ComputeHash(rawBytes);
     ret = enc.GetString(result);
     return ret;
 }
예제 #22
0
        public static byte[] GetHash(Stream input, HashType hashType)
        {
            if (input == null) return null;

             lock(Hashers)
             {
            return GetHasher(hashType).ComputeHash(input);
             }
        }
예제 #23
0
파일: Hashing.cs 프로젝트: kenegozi/d9
 /// <summary>
 /// Hashing a given string with any of the supported hash algorithms.
 /// </summary>
 /// <param name="data">Data to hash</param>
 /// <param name="hashType">Hashing algorithm to use</param>
 /// <returns>Hashed data</returns>
 public static string HashData(string data, HashType hashType)
 {
     var bytes = (new UnicodeEncoding()).GetBytes(data);
     var hashed = HashData(bytes, hashType);
     var sb = new StringBuilder(64);
     foreach (var b in hashed)
         sb.AppendFormat("{0:x2}", b);
     return sb.ToString();
 }
예제 #24
0
        private static IHashAlgorithm GetHasher(HashType hashType)
        {
            IHashAlgorithm result;
             if (!Hashers.TryGetValue(hashType, out result))
             {
            result = Hashers[hashType] = CreateHasher(hashType);
             }

             return result;
        }
예제 #25
0
        public static byte[] GetHash(byte[] input, HashType hashType)
        {
            if (input == null) return null;
             if (input.Length == 0) return input;

             lock (Hashers)
             {
            return GetHasher(hashType).ComputeHash(input);
             }
        }
 public static string EncryptString(HashType ht, string str, string salt = null)
 {
     switch (ht)
     {
         case HashType.Md5:
             var md5 = SaltMd5.Init(str, salt);
             return md5.ToBfFormat();
     }
     throw new PostfixEncryptorException("This hash type doesn't implemented.");
 }
예제 #27
0
 public static string TextToHash(string text, HashType hashType, bool uppercase = false)
 {
     using (HashAlgorithm hash = HashCheck.GetHashAlgorithm(hashType))
     {
         byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text));
         string[] hex = BytesToHexadecimal(bytes);
         string result = string.Concat(hex);
         if (uppercase) result = result.ToUpperInvariant();
         return result;
     }
 }
예제 #28
0
        /// <summary>
        /// Compute the hash of a given file
        /// </summary>
        /// <param name="hashType">
        /// Defines the type of hash algorithm to use
        /// </param>
        /// <param name="filename">
        /// A <see cref="System.String"/> with the filename
        /// </param>
        /// <returns>
        /// A <see cref="System.String"/> with the hash. The string is in lowercase HEX and
        /// all "-" are removed.
        /// </returns>
        public static string FromFile(HashType hashType, string filename)
        {
            HashAlgorithm provider = HashFactory.CreateInstance(hashType);

            FileStream file = new FileStream(filename, FileMode.Open);
            byte[] retVal = provider.ComputeHash(file);
            file.Close();
            file = null;
            provider = null;
            return BitConverter.ToString(retVal).ToLower().Replace("-", String.Empty);
        }
예제 #29
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hType">Hashing Algorithm used (SHA1 or MD5)</param>
        /// <param name="keyLength">Size of encryption key in bits. Allowed values are: 128, 192, and 256.</param>
        /// <param name="iterations">Number of iterations used to generate password.</param>
        /// <param name="initVector">16 ASCII character Initialization Vector</param>
        /// <param name="passPhrase">Unicode phrase used to generate encryption string</param>
        /// <param name="saltValue">Unicode value to salt data with (secondary key)</param>
        public Crypto(HashType hType, int keyLength, int iterations, string initVector, string passPhrase, string saltValue)
        {
            m_hType = hType.ToString();

            m_keyLength = keyLength;
            m_iterations = iterations;
            m_initVector = initVector;

            m_passPhrase = passPhrase;
            m_saltValue = saltValue;
        }
예제 #30
0
        public static string FromString(string input, HashType hashtype)
        {
            Byte[] clearBytes;
            Byte[] hashedBytes;
            string output = String.Empty;

            switch (hashtype)
            {
                case HashType.RIPEMD160:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.MD5:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA1:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    sha1.ComputeHash(clearBytes);
                    hashedBytes = sha1.Hash;
                    sha1.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA256:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA256 sha256 = new SHA256Managed();
                    sha256.ComputeHash(clearBytes);
                    hashedBytes = sha256.Hash;
                    sha256.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA384:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA384 sha384 = new SHA384Managed();
                    sha384.ComputeHash(clearBytes);
                    hashedBytes = sha384.Hash;
                    sha384.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA512:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA512 sha512 = new SHA512Managed();
                    sha512.ComputeHash(clearBytes);
                    hashedBytes = sha512.Hash;
                    sha512.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
            }
            return output;
        }
예제 #31
0
        /// <summary>
        ///     Deserialize from string.
        /// </summary>
        public static bool Deserialize(this string value, out HashType hashType)
        {
            Contract.Requires(value != null);

            return(NameToValue.TryGetValue(value, out hashType));
        }
예제 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssuredStreamCreateArgs"/> class.
 /// </summary>
 public AssuredStreamCreateArgs()
 {
     _hashType = QQnCryptoHelpers.DefaultHashType;
 }
예제 #33
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TaggedHashInfo" /> class.
 /// </summary>
 protected TaggedHashInfo(HashType hashType, int length)
     : base(hashType, length)
 {
 }
예제 #34
0
 /// <inheritdoc />
 protected override Task <PutResult> PutStreamCoreAsync(OperationContext operationContext, HashType hashType, Stream stream, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new PutResult(new BoolResult(ErrorMessage)));
예제 #35
0
 /// <inheritdoc />
 public Task <PutResult> PutStreamAsync(Context context, HashType hashType, Stream stream, CancellationToken cts, UrgencyHint urgencyHint)
 {
     return(_innerCacheSession.PutStreamAsync(context, hashType, stream, cts, urgencyHint));
 }
예제 #36
0
        public static byte[] TransformFinalBlock(byte[] buffer, int offset, int count,
                                                 ref HashAlgorithm ha, HashType htype = HashType.MD5)
        {
            byte[] hash = null;

            switch (htype)
            {
            case HashType.MD5:
                MD5 md5;

                if (ha == null)
                {
                    md5 = MD5.Create();
                    ha  = md5;
                }
                else
                {
                    md5 = (MD5)ha;
                }

                md5.TransformFinalBlock(buffer, offset, count);
                hash = md5.Hash;
                md5.Dispose();
                break;

            case HashType.SHA1:
                SHA1 sha1;

                if (ha == null)
                {
                    sha1 = SHA1.Create();
                    ha   = sha1;
                }
                else
                {
                    sha1 = (SHA1)ha;
                }

                sha1.TransformFinalBlock(buffer, offset, count);
                hash = sha1.Hash;
                sha1.Dispose();
                break;

            case HashType.SHA256:
                SHA256 sha256;

                if (ha == null)
                {
                    sha256 = SHA256.Create();
                    ha     = sha256;
                }
                else
                {
                    sha256 = (SHA256)ha;
                }

                sha256.TransformFinalBlock(buffer, offset, count);
                hash = sha256.Hash;
                sha256.Dispose();
                break;

            case HashType.SHA384:
                SHA384 sha384;

                if (ha == null)
                {
                    sha384 = SHA384.Create();
                    ha     = sha384;
                }
                else
                {
                    sha384 = (SHA384)ha;
                }

                sha384.TransformFinalBlock(buffer, offset, count);
                hash = sha384.Hash;
                sha384.Dispose();
                break;

            case HashType.SHA512:
                SHA512 sha512;

                if (ha == null)
                {
                    sha512 = SHA512.Create();
                    ha     = sha512;
                }
                else
                {
                    sha512 = (SHA512)ha;
                }

                sha512.TransformFinalBlock(buffer, offset, count);
                hash = sha512.Hash;
                sha512.Dispose();
                break;

            default:
                throw new HashException("invalid hash algorithm");
            }

            return(hash);
        }
예제 #37
0
 /// <summary>
 ///     Uninitialized content hash used with errors.
 /// </summary>
 public ContentHash(HashType hashType)
     : this()
 {
     _hashType = hashType;
 }
예제 #38
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ContentHash" /> struct from bytes
 /// </summary>
 private ContentHash(HashType hashType, ReadOnlyFixedBytes bytes)
 {
     _hashType = hashType;
     _bytes    = bytes;
 }
예제 #39
0
 /// <summary>
 ///     Attempt to create from a known type and string (without type).
 /// </summary>
 public static bool TryParse(HashType hashType, string serialized, out ContentHash contentHash)
 {
     return(TryParse(hashType, serialized, out contentHash, null));
 }
예제 #40
0
 public static bool Compare(string original, string salt, string hashString, HashType hashType = DefaultHashType, Encoding encoding = null)
 {
     return(Compare(original + salt, hashString, hashType, encoding));
 }
예제 #41
0
 public MultihashAlgorithmExportAttribute(HashType code, string name, int defaultLength)
 {
     Code          = code;
     Name          = name;
     DefaultLength = defaultLength;
 }
예제 #42
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="PutStreamCall{TTracer}"/> class.
 /// </summary>
 private PutStreamCall(TTracer tracer, OperationContext context, HashType hashType)
     : this(tracer, context, new ContentHash(hashType))
 {
 }
 // hash(master_secret + pad2 + hash(handshake_messages +
 //      Sender + master_secret + pad1));
 public Ssl3HandshakeMac(HashType hash) : this(hash, null)
 {
 }
예제 #44
0
 public HashAvGeneratorBase()
 {
     HashType = HashType.Sha512;
 }
예제 #45
0
 /// <inheritdoc />
 public Task <PutResult> PutFileAsync(Context context, HashType hashType, AbsolutePath path, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint)
 {
     return(_innerCacheSession.PutFileAsync(context, hashType, path, realizationMode, cts, urgencyHint));
 }
예제 #46
0
파일: Selector.cs 프로젝트: socat/BuildXL
 /// <summary>
 ///     Create a random value.
 /// </summary>
 public static Selector Random(HashType hashType = HashType.Vso0, int outputLength = 2)
 {
     byte[] output = outputLength == 0 ? null : ThreadSafeRandom.GetBytes(outputLength);
     return(new Selector(ContentHash.Random(hashType), output));
 }
예제 #47
0
 /// <summary>
 ///     Create a random value.
 /// </summary>
 public static StrongFingerprint Random(
     int weakFingerprintLength = Fingerprint.MaxLength, HashType selectorHashType = HashType.SHA1)
 {
     return(new StrongFingerprint(Fingerprint.Random(weakFingerprintLength), Selector.Random(selectorHashType)));
 }
예제 #48
0
        /// <inheritdoc />
        protected override async Task <PutResult> PutStreamCoreAsync(OperationContext context, HashType hashType, Stream stream, UrgencyHint urgencyHint, Counter retryCounter)
        {
            if (hashType != RequiredHashType)
            {
                return(new PutResult(
                           new ContentHash(hashType),
                           $"DedupStore client requires {RequiredHashType}. Cannot take HashType '{hashType}'."));
            }

            try
            {
                var tempFile = TempDirectory.CreateRandomFileName().Path;
                using (Stream writer = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
                {
                    await stream.CopyToAsync(writer);
                }

                // Cast is necessary because ContentSessionBase implements IContentSession explicitly
                return(await(this as IContentSession).PutFileAsync(context, hashType, new AbsolutePath(tempFile), FileRealizationMode.None, context.Token, urgencyHint));
            }
            catch (Exception e)
            {
                return(new PutResult(e, new ContentHash(hashType)));
            }
        }
예제 #49
0
 /// <inheritdoc />
 protected override Task <PutResult> PutFileCoreAsync(OperationContext operationContext, HashType hashType, AbsolutePath path, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new PutResult(new BoolResult(ErrorMessage)));
예제 #50
0
 public static byte[] GenerateSalt(HashType hashType = HashType.Scrypt)
 {
     //Note: the default hash type is Scrypt for now: to keep backward compatibility
     return(hashType == HashType.Argon ? ArgonGenerateSalt() : ScryptGenerateSalt());
 }
 /// <inheritdoc />
 protected override Task <PutResult> PutFileCoreAsync(OperationContext operationContext, HashType hashType, AbsolutePath path, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter)
 {
     return(MultiLevelWriteAsync(session => session.PutFileAsync(
                                     operationContext,
                                     hashType,
                                     path,
                                     CoerceRealizationMode(realizationMode, session),
                                     operationContext.Token,
                                     urgencyHint)));
 }
예제 #52
0
 public virtual void PutFileStart(Context context, AbsolutePath path, FileRealizationMode mode, HashType hashType, bool trusted)
 {
     // Don't trace starts to reduce the amount of traces.
     _putFileCallCounter.Started();
 }
예제 #53
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="HashInfo" /> class.
 /// </summary>
 protected HashInfo(HashType hashType, int length)
 {
     HashType   = hashType;
     ByteLength = length;
 }
 /// <inheritdoc />
 protected override Task <PutResult> PutStreamCoreAsync(OperationContext operationContext, HashType hashType, Stream stream, UrgencyHint urgencyHint, Counter retryCounter)
 {
     return(MultiLevelWriteAsync(session => session.PutStreamAsync(operationContext, hashType, stream, operationContext.Token, urgencyHint)));
 }
예제 #55
0
 internal AssuredStreamCreateArgs(StrongNameKey strongName, string fileType, HashType hashType)
 {
     StrongNameKey = strongName;
     FileType      = fileType;
     HashType      = hashType;
 }
예제 #56
0
//		hash(MAC_write_secret + pad_2 +
//			hash (MAC_write_secret + pad_1 + seq_num + length + content));
        public Ssl3RecordMAC(HashType hash) : this(hash, null)
        {
        }
예제 #57
0
        public static bool Compare(string original, string hashString, HashType hashType = DefaultHashType, Encoding encoding = null)
        {
            string originalHash = Get(original, hashType, encoding);

            return(originalHash == hashString);
        }
예제 #58
0
 public static string Get(string text, string salt, HashType hashType = DefaultHashType, Encoding encoding = null)
 {
     return(Get(text + salt, hashType, encoding));
 }
예제 #59
0
 /// <nodoc />
 public static ContentHash FromFixedBytes(HashType hashType, ReadOnlyFixedBytes bytes)
 {
     return(new ContentHash(hashType, bytes));
 }
예제 #60
0
 public virtual void PutStreamStart(Context context, HashType hashType)
 {
     // Don't trace starts to reduce the amount of traces.
     _putStreamCallCounter.Started();
 }