public WinDbFiller(IFingerprintService fingerprintService, IWorkUnitBuilder workUnitBuilder, ITagService tagService)
        {
            this.fingerprintService = fingerprintService;
            this.workUnitBuilder = workUnitBuilder;
            this.tagService = tagService;
            InitializeComponent();
            Icon = Resources.Sound;
            foreach (object item in ConfigurationManager.ConnectionStrings)
            {
                _cmbDBFillerConnectionString.Items.Add(item.ToString());
            }

            if (_cmbDBFillerConnectionString.Items.Count > 0)
            {
                _cmbDBFillerConnectionString.SelectedIndex = 0;
            }

            _btnStart.Enabled = false;
            _btnStop.Enabled = false;
            _nudThreads.Value = MaxThreadToProcessFiles;
            _pbTotalSongs.Visible = false;
            hashAlgorithm = 0; /**/
            _lbAlgorithm.SelectedIndex = 0; /*Set default algorithm LSH*/

            if (hashAlgorithm == HashAlgorithm.LSH)
            {
                _nudHashKeys.ReadOnly = false;
                _nudHashTables.ReadOnly = false;
            }

            object[] items = Enum.GetNames(typeof (StrideType)); /*Add enumeration types in the combo box*/
            _cmbStrideType.Items.AddRange(items);
            _cmbStrideType.SelectedIndex = 0;
        }
Example #2
0
        /// <summary>Compute the one-time code for the given parameters.</summary>
        /// <param name="algorithm">The hashing algorithm for the HMAC computation.</param>
        /// <param name="secret">The ASCII-encoded base32-encoded shared secret.</param>
        /// <param name="datetime">The date with time for which the one-time code must be computed.</param>
        /// <param name="digits">The number of digits of the one-time codes.</param>
        /// <param name="period">The period step used for the HMAC counter computation.</param>
        /// <returns>The one-time code for the given date.</returns>
        public static int GetCode(
            HashAlgorithm algorithm,
            string secret,
            DateTime datetime,
            int digits = Otp.DefaultDigits,
            int period = Totp.DefaultPeriod)
        {
            Contract.Requires<ArgumentOutOfRangeException>(Enum.IsDefined(typeof(HashAlgorithm), algorithm));
            Contract.Requires<ArgumentOutOfRangeException>(algorithm != HashAlgorithm.Unknown);
            Contract.Requires<ArgumentNullException>(secret != null);
            Contract.Requires<ArgumentNullException>(datetime != null);
            Contract.Requires<ArgumentException>(Enum.IsDefined(typeof(DateTimeKind), datetime.Kind));
            Contract.Requires<ArgumentException>(datetime.Kind != DateTimeKind.Unspecified);
            Contract.Requires<ArgumentOutOfRangeException>(digits > 0);
            Contract.Requires<ArgumentOutOfRangeException>(period > 0);
            Contract.Ensures(Contract.Result<int>() > 0);
            Contract.Ensures(Contract.Result<int>() < Math.Pow(10, digits));

            datetime = datetime.Kind == DateTimeKind.Utc ? datetime : datetime.ToUniversalTime();

            var unixTime = datetime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            var counter = (long) (unixTime * 1000) / (period * 1000);

            return Otp.GetCode(algorithm, secret, counter, digits);
        }
Example #3
0
        /// <summary>
        ///   Constructor
        /// </summary>
        public WinDBFiller()
        {
            InitializeComponent();
            Icon = Resources.Sound;
            foreach (object item in ConfigurationManager.ConnectionStrings) /*Detect all the connection strings*/
                _cmbDBFillerConnectionString.Items.Add(item.ToString());

            if (_cmbDBFillerConnectionString.Items.Count > 0)
                _cmbDBFillerConnectionString.SelectedIndex = 0;

            _btnStart.Enabled = false;
            _btnStop.Enabled = false;
            _nudThreads.Value = THREADS;
            _pbTotalSongs.Visible = false;
            _hashAlgorithm = 0; /**/
            _lbAlgorithm.SelectedIndex = 0; /*Set default algorithm LSH*/

            if (_hashAlgorithm == HashAlgorithm.LSH)
            {
                _nudHashKeys.ReadOnly = false;
                _nudHashTables.ReadOnly = false;
            }

            string[] items = Enum.GetNames(typeof (StrideType)); /*Add enumeration types in the combo box*/
            _cmbStrideType.Items.AddRange(items);
            _cmbStrideType.SelectedIndex = 0;
        }
Example #4
0
 static void Main(string[] args)
 {
     if (args.Length == 0 || args.Length > 1) {
         Console.WriteLine("\r\nUsage: hash [filename]");
         return;
     }
     HashAlgorithm[] hashes = new HashAlgorithm[] {
             new MD2CryptoServiceProvider(), new MD5CryptoServiceProvider(),
             new SHA1CryptoServiceProvider(), new Org.Mentalis.Security.Cryptography.RIPEMD160Managed()
         };
     string[] names = new string[] {"MD2:       ", "MD5:       ", "SHA1:      ", "RIPEMD160: "};
     byte[] buffer = new byte[4096];
     FileStream fs = File.Open(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);
     int size = fs.Read(buffer, 0, buffer.Length);
     while(size > 0) {
         for(int i = 0;  i < hashes.Length; i++) {
             hashes[i].TransformBlock(buffer, 0, size, buffer, 0);
         }
         size = fs.Read(buffer, 0, buffer.Length);
     }
     for(int i = 0;  i < hashes.Length; i++) {
         hashes[i].TransformFinalBlock(buffer, 0, 0);
         Console.WriteLine(names[i] + BytesToHex(hashes[i].Hash));
         hashes[i].Clear();
     }
     fs.Close();
 }
Example #5
0
        /// <summary>Build a URI for secret key provisioning.</summary>
        /// <param name="algorithm">The hashing algorithm for the HMAC computation.</param>
        /// <param name="issuer">The name of the entity issuing and maintaining the key.</param>
        /// <param name="account">The account name for which the one-time codes will work.</param>
        /// <param name="secret">The ASCII-encoded base32-encoded shared secret.</param>
        /// <param name="period">The period step for the HMAC counter computation.</param>
        /// <param name="digits">The number of digits of the one-time codes.</param>
        /// <returns>The provisioning URI.</returns>
        public static string GetKeyUri(
            HashAlgorithm algorithm,
            string issuer,
            string account,
            byte[] secret,
            int digits = Otp.DefaultDigits,
            int period = Totp.DefaultPeriod)
        {
            Contract.Requires<ArgumentOutOfRangeException>(Enum.IsDefined(typeof(HashAlgorithm), algorithm));
            Contract.Requires<ArgumentOutOfRangeException>(algorithm != HashAlgorithm.Unknown);
            Contract.Requires<ArgumentNullException>(issuer != null);
            Contract.Requires<ArgumentOutOfRangeException>(!string.IsNullOrWhiteSpace(issuer));
            Contract.Requires<ArgumentNullException>(account != null);
            Contract.Requires<ArgumentOutOfRangeException>(!string.IsNullOrWhiteSpace(account));
            Contract.Requires<ArgumentNullException>(secret != null);
            Contract.Requires<ArgumentException>(secret.Length > 0);
            Contract.Requires<ArgumentOutOfRangeException>(digits > 0);
            Contract.Requires<ArgumentOutOfRangeException>(period > 0);
            Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result<string>()));

            return
                Otp.GetKeyUri(
                    OtpType.Totp,
                    issuer,
                    account,
                    secret,
                    algorithm,
                    digits,
                    0,
                    period);
        }
Example #6
0
        internal static int GetCode(
            HashAlgorithm algorithm,
            string secret,
            long counter,
            int digits)
        {
            MacAlgorithmProvider algorithmProvider = MacAlgorithmProvider.OpenAlgorithm(algorithm.ToAlgorithmName());

            var keyMaterial = CryptographicBuffer.ConvertStringToBinary(secret, BinaryStringEncoding.Utf8);
            var key = algorithmProvider.CreateKey(keyMaterial);

            var hash = CryptographicEngine.Sign(key, CounterToBytes(counter).AsBuffer());

            byte[] hashArray = new byte[hash.Length];
            CryptographicBuffer.CopyToByteArray(hash, out hashArray);

            var hmac = hashArray.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);
        }
Example #7
0
        private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash)
        {
            byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes);
            const int StepA = 13;
            const int StepB = 7;

            int position = 0;

            while (position < s_inputBytes.Length - StepA)
            {
                incrementalHash.AppendData(s_inputBytes, position, StepA);
                position += StepA;
            }

            incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position);

            byte[] incrementalA = incrementalHash.GetHashAndReset();
            Assert.Equal(referenceHash, incrementalA);

            // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets.
            position = 0;

            while (position < s_inputBytes.Length - StepB)
            {
                incrementalHash.AppendData(s_inputBytes, position, StepA);
                position += StepA;
            }

            incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position);

            byte[] incrementalB = incrementalHash.GetHashAndReset();
            Assert.Equal(referenceHash, incrementalB);
        }
Example #8
0
 public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
     if (node is ICanonicalizableNode) {
         ((ICanonicalizableNode) node).WriteHash(hash, docPos, anc);
     } else {
         WriteHashGenericNode(node, hash, docPos, anc);
     }
 }
Example #9
0
		public MD5SHA1() : base()
		{
			this.md5 = MD5.Create();
			this.sha = SHA1.Create();

			// Set HashSizeValue
			this.HashSizeValue = this.md5.HashSize + this.sha.HashSize;
		}
Example #10
0
	public static void Compute(HashAlgorithm hashAlgorithm, IUVStream<ArraySegment<byte>> stream, Action<byte[]> callback)
	{
		var hs = new HashStream(hashAlgorithm, stream);
		hs.Complete += () => {
			callback(hs.Hash);
			hs.Dispose();
		};
	}
        private static void VerifySignatureWithHashAlgorithm(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm)
        {
            byte[] signature = formatter.CreateSignature(hashAlgorithm);
            Assert.True(deformatter.VerifySignature(hashAlgorithm, signature));

            signature[signature.Length - 1] ^= 0xff;
            Assert.False(deformatter.VerifySignature(hashAlgorithm, signature));
        }
Example #12
0
 public static void ComputeString(HashAlgorithm hashAlgorithm, IUVStream stream, Action<string> callback)
 {
     var hs = new HashStream(hashAlgorithm, stream);
     hs.Complete += () => {
         callback(hs.HashString);
         hs.Dispose();
     };
 }
Example #13
0
 public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm)
 {
     using (referenceAlgorithm)
     using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm))
     {
         VerifyIncrementalResult(referenceAlgorithm, incrementalHash);
     }
 }
 internal byte[] GetDigestedBytes(HashAlgorithm hash) {
     m_c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, m_ancMgr);
     hash.TransformFinalBlock(new byte[0], 0, 0);
     byte[] res = (byte[]) hash.Hash.Clone();
     // reinitialize the hash so it is still usable after the call
     hash.Initialize();
     return res;
 }
 public static bool ValidateHashAlgorithm(HashAlgorithm value)
 {
     if ((((value != HashAlgorithm.None) && (value != HashAlgorithm.Md2)) && ((value != HashAlgorithm.Md4) && (value != HashAlgorithm.Md5))) && (value != HashAlgorithm.Sha))
     {
         return (value == HashAlgorithm.Mac);
     }
     return true;
 }
 public CacheManagerStreamWriter(out KeyCollection keys, int blockLength, HashAlgorithm hashAlgorithm, CacheManager cacheManager, BufferManager bufferManager)
 {
     keys = _keyList;
     _hashAlgorithm = hashAlgorithm;
     _cacheManager = cacheManager;
     _bufferManager = bufferManager;
     _blockBuffer = bufferManager.TakeBuffer(blockLength);
     _blockBufferLength = blockLength;
 }
Example #17
0
 // prints the hash of a specified input to the console
 public static void PrintHash(string name, HashAlgorithm algo, byte[] data)
 {
     // compute the hash of the input data..
     byte[] hash = algo.ComputeHash(data);
     // ..and write the hash to the console
     Console.WriteLine(name + BytesToHex(hash));
     // dispose of the hash algorithm; we do not need to hash more data with it
     algo.Clear();
 }
Example #18
0
 static void Perf(HashAlgorithm digest)
 {
     Console.WriteLine ("Performance tests for different block sizes, 30 seconds each");
     int block = 1;
     while (block <= 64 * 1024) {
         Speed (digest, block);
         block <<= 2;
     }
 }
Example #19
0
        public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (node == null)
                throw new ArgumentNullException("node");

            XmlNodeList childNodes = node.ChildNodes;
            foreach (XmlNode childNode in childNodes) {
                WriteHash(childNode, hash, docPos, anc);
            }
        }
        protected static void VerifySignature(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm, string hashAlgorithmName)
        {
            formatter.SetHashAlgorithm(hashAlgorithmName);
            deformatter.SetHashAlgorithm(hashAlgorithmName);

            byte[] hash = hashAlgorithm.ComputeHash(HelloBytes);

            VerifySignatureWithHashBytes(formatter, deformatter, hash);
            VerifySignatureWithHashAlgorithm(formatter, deformatter, hashAlgorithm);
        }
Example #21
0
		public MD5SHA1() : base()
		{
			#pragma warning disable 436
			this.md5 = new MD5CryptoServiceProvider ();
			this.sha = new SHA1CryptoServiceProvider ();
			#pragma warning restore 436

			// Set HashSizeValue
			this.HashSizeValue = this.md5.HashSize + this.sha.HashSize;
		}
 public static byte[] Hash(HashAlgorithm alg, byte[] message)
 {
     switch (alg)
     {
         case HashAlgorithm.SHA256:
             return SHA256.Hash(message);
         default:
             throw new Exception("Invalid HashAlgorithm");
     }
 }
Example #23
0
		public HashMembershipCondition (HashAlgorithm hashAlg, byte[] value)
		{
			if (hashAlg == null)
				throw new ArgumentNullException ("hashAlg");
			if (value == null)
				throw new ArgumentNullException ("value");
				
			this.hash_algorithm = hashAlg;
			this.hash_value = (byte[]) value.Clone ();
		}
    public HashTestCase(string name, HashAlgorithm hasher, byte[] input, byte[] output)
        : base(name)
    {
        SetImpl(new TestCaseImpl(RunTest));
        this.hasher = hasher;
        this.input = input;
        this.output = output;

        return;
    }
Example #25
0
    public static string GetHash(string input, HashAlgorithm hash)
    {
        byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
Example #26
0
        public void TestReusability(HashAlgorithm hashAlgorithm)
        {
            using (hashAlgorithm)
            {
                byte[] input = { 8, 6, 7, 5, 3, 0, 9, };
                byte[] hash1 = hashAlgorithm.ComputeHash(input);
                byte[] hash2 = hashAlgorithm.ComputeHash(input);

                Assert.Equal(hash1, hash2);
            }
        }
    public HashTestCaseTruncate(string name, HashAlgorithm hasher, byte[] input, byte[] output, int truncateBits)
        : base(name)
    {
        SetImpl(new TestCaseImpl(RunTest));
        this.hasher = hasher;
        this.input = input;
        this.output = output;
		this.truncateBits = truncateBits;

        return;
    }
Example #28
0
    static void Test(HashAlgorithm digest)
    {
        byte[] result1, result2, result3;

        if (digest is SHA1) {
            Console.WriteLine ("Testing results wrt FIPS 180-1 test vectors");
            result1 = new byte [] { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e,
                0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d };
            result2 = new byte [] { 0x84, 0x98, 0x3e, 0x44, 0x1c, 0x3b, 0xd2, 0x6e, 0xba, 0xae,
                0x4a, 0xa1, 0xf9, 0x51, 0x29, 0xe5, 0xe5, 0x46, 0x70, 0xf1 };
            result3 = new byte [] { 0x34, 0xaa, 0x97, 0x3c, 0xd4, 0xc4, 0xda, 0xa4, 0xf6, 0x1e,
                0xeb, 0x2b, 0xdb, 0xad, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6f };
        } else if (digest is SHA256) {
            Console.WriteLine ("Testing results wrt FIPS 180-2 test vectors");
            result1 = new byte [] { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
                0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
                0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
                0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad };
            result2 = new byte [] { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
                0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
                0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
                0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 };
            result3 = new byte [] { 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92,
                0x81, 0xa1, 0xc7, 0xe2, 0x84, 0xd7, 0x3e, 0x67,
                0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, 0x20, 0x0e,
                0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0 };
        } else {
            Console.WriteLine ("No test vectors were found.");
            return;
        }
        string input1 = "abc";
        string input2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";

        byte[] input = Encoding.Default.GetBytes (input1);
        byte[] output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 1: {0}",
            BitConverter.ToString (result1) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");

        input = Encoding.Default.GetBytes (input2);
        output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 2: {0}",
            BitConverter.ToString (result2) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");

        input = new byte [1000000];
        for (int i = 0; i < 1000000; i++)
            input[i] = 0x61; // a
        output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 3: {0}",
            BitConverter.ToString (result3) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");
    }
Example #29
0
 public static bool ValidateHashAlgorithm(HashAlgorithm value)
 {
     //
     // note that HashAlgorithm has disjoined values
     //
     return (value == HashAlgorithm.None) ||
            (value == HashAlgorithm.Md2) ||
            (value == HashAlgorithm.Md4) ||
            (value == HashAlgorithm.Md5) ||
            (value == HashAlgorithm.Sha) ||
            (value == HashAlgorithm.Mac);
 }
Example #30
0
 public Context ( HttpContext context, HashAlgorithm algorithm, String key, FileInfo fileInfo, params object[] eTagArray ) {
     m_requestUri = fileInfo.FullName;
     m_requestXmlFileInfo = fileInfo;
     m_httpQueryString = context.Request.QueryString;
     m_httpForm = context.Request.Form;
     m_httpCookies = context.Request.Cookies;
     m_httpParams = context.Request.Params;
     m_hashKey = key;
     m_hashAlgorithm = algorithm;
     m_requestXmlETag = GenerateETag(key, algorithm, fileInfo.LastWriteTimeUtc, fileInfo.Length, m_requestUri);
     m_eTag = GenerateETag(key, algorithm, m_requestUri, eTagArray);
 }
Example #31
0
 /// <summary>
 /// Generates a BASE64-encoded hash from the specified input string
 /// using the specified hashing algorithm.
 /// </summary>
 /// <param name="input">The input string to hash.</param>
 /// <param name="algorithm">The hashing algorithm to use.</param>
 /// <returns>The hashed input as a BASE64-encoded string.</returns>
 /// <exception cref="ArgumentNullException">The input parameter or the
 /// algorithm parameter is null.</exception>
 /// <exception cref="NotSupportedException">The specified
 /// algorithm is not supported.</exception>
 string Hash(string input, HashAlgorithm algorithm)
 {
     input.ThrowIfNull("input");
     byte[] bytes = Encoding.UTF8.GetBytes(input);
     return(Convert.ToBase64String(algorithm.ComputeHash(bytes)));
 }
Example #32
0
 public HashModel(HashAlgorithm hashAlgorithm)
 {
     this.hashAlgorithm = hashAlgorithm;
 }
Example #33
0
 public override byte[] GetDigestedOutput(HashAlgorithm hash)
 {
     // no null check, MS throws a NullReferenceException here
     return(hash.ComputeHash((Stream)GetOutput()));
 }
Example #34
0
        public string Sign(KeyPair signingKeyPair, string text)
        {
            //Use PrivateKey to sign
            _rsaCryptoServiceProvider.FromXmlString(signingKeyPair.Private.Key);
            var signedData = _rsaCryptoServiceProvider.SignData(TextHelpers.ClearTextToClearBytes(text), HashAlgorithm.Create());
            var signature  = TextHelpers.CipherBytesToCipherText(signedData);

            return(string.Format("{0}<signature>{1}</signature>", text, signature));
        }
        /// <summary>
        /// Start the download.
        /// </summary>
        public async Task Start(CancellationToken cancellation = default)
        {
            if (CurrentState != State.Idle)
            {
                throw new InvalidOperationException("A download already in progress or instance not prepared.");
            }

            try {
                HashAlgorithm hasher = null;
                if (HashAlgorithm != null)
                {
                    hasher = (HashAlgorithm)Activator.CreateInstance(HashAlgorithm);
                }

                var filename = Path.GetFileName(TargetPath);

                // Check existing file
                var mode        = FileMode.Create;
                var startOffset = 0L;
                if (File.Exists(TargetPath) && Resume)
                {
                    // Try to resume existing file
                    var fileInfo = new FileInfo(TargetPath);
                    if (ExpectedSize > 0 && fileInfo.Length >= ExpectedSize)
                    {
                        if (hasher != null)
                        {
                            using (var input = File.Open(TargetPath, FileMode.Open, FileAccess.Read)) {
                                CurrentState = State.Hashing;
                                await CopyToAsync(input, Stream.Null, hasher, cancellation);
                            }
                            hasher.TransformFinalBlock(new byte[0], 0, 0);
                            Hash = Helpers.ToHexString(hasher.Hash);
                            if (ExpectedHash != null)
                            {
                                if (CheckHash())
                                {
                                    Logger.LogInformation($"Existing file '{filename}' has matching hash, skipping...");
                                    CurrentState = State.Complete;
                                    return;
                                }
                                 else {
                                    // Hash mismatch, force redownload
                                    Logger.LogWarning($"Existing file '{filename}' has different hash: Got {Hash} but expected {ExpectedHash}. Will redownload...");
                                    startOffset = 0;
                                    mode        = FileMode.Create;
                                }
                            }
                            else
                            {
                                Logger.LogInformation($"Existing file '{filename}' has hash {Hash} but we have nothing to check against, assuming it's ok...");
                            }
                        }
                        else
                        {
                            // Assume file is good
                            Logger.LogInformation($"Existing file '{filename}' cannot be checked for integrity, assuming it's ok...");
                            CurrentState = State.Complete;
                            return;
                        }
                    }
                    else
                    {
                        Logger.LogInformation($"Resuming partial download of '{filename}' ({Helpers.FormatSize(fileInfo.Length)} already downloaded)...");
                        startOffset = fileInfo.Length;
                        mode        = FileMode.Append;
                    }
                }

                // Load headers
                var request = new HttpRequestMessage(HttpMethod.Get, Url);
                if (startOffset != 0)
                {
                    request.Headers.Range = new RangeHeaderValue(startOffset, null);
                }

                if (client.Timeout != TimeSpan.FromSeconds(Timeout))
                {
                    client.Timeout = TimeSpan.FromSeconds(Timeout);
                }
                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellation);

                response.EnsureSuccessStatusCode();

                // Redownload whole file if resuming fails
                if (startOffset > 0 && response.StatusCode != HttpStatusCode.PartialContent)
                {
                    Logger.LogInformation("Server does not support resuming download.");
                    startOffset = 0;
                    mode        = FileMode.Create;
                }

                if (hasher != null)
                {
                    hasher.Initialize();

                    // When resuming, hash already downloaded data
                    if (startOffset > 0)
                    {
                        using (var input = File.Open(TargetPath, FileMode.Open, FileAccess.Read)) {
                            CurrentState = State.Hashing;
                            await CopyToAsync(input, Stream.Null, hasher, cancellation);
                        }
                    }
                }

                if (response.Content.Headers.ContentLength != null)
                {
                    BytesTotal = response.Content.Headers.ContentLength.Value + startOffset;
                }

                // Download
                Directory.CreateDirectory(Path.GetDirectoryName(TargetPath));
                using (Stream input = await response.Content.ReadAsStreamAsync(), output = File.Open(TargetPath, mode, FileAccess.Write)) {
                    CurrentState   = State.Downloading;
                    BytesProcessed = startOffset;
                    await CopyToAsync(input, output, hasher, cancellation);
                }

                if (hasher != null)
                {
                    hasher.TransformFinalBlock(new byte[0], 0, 0);
                    Hash = Helpers.ToHexString(hasher.Hash);
                }

                if (Hash != null && ExpectedHash != null && !CheckHash())
                {
                    if (ExpectedHash == null)
                    {
                        Logger.LogInformation($"Downloaded file '{filename}' with hash {Hash}");
                        CurrentState = State.Complete;
                    }
                    else if (CheckHash())
                    {
                        Logger.LogInformation($"Downloaded file '{filename}' with expected hash {Hash}");
                        CurrentState = State.Complete;
                    }
                    else
                    {
                        throw new Exception($"Downloaded file '{filename}' does not match expected hash (got {Hash} but expected {ExpectedHash})");
                    }
                }
                else
                {
                    Logger.LogInformation($"Downloaded file '{filename}'");
                    CurrentState = State.Complete;
                }
            } catch {
                CurrentState = State.Error;
                throw;
            }
        }
Example #36
0
 /// <summary>
 /// Generate the signature value based on the given signature base and hash algorithm
 /// </summary>
 /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
 /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
 /// <returns>A base64 string of the hash value</returns>
 public static string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
 {
     return(ComputeHash(hash, signatureBase));
 }
 public HashingService(HashAlgorithm hasher, Encoding encoding)
 {
     Hasher   = hasher;
     Encoding = encoding;
 }
 public override void Write(BinaryWriter writer, HashAlgorithm algo = null)
 {
     OutputOffset      = (ulong)writer.BaseStream.Position;
     OutputValueOffset = writer.Ebml_Write_Utf8_With_Id(Id, Value);
 }
Example #39
0
 /// <summary>
 /// Getting hash from string.
 /// <para/>
 /// Получение хэша из строки.
 /// </summary>
 ///
 /// <param name="str">
 /// String.
 /// <para/>
 /// Строка.
 /// </param>
 ///
 /// <param name="hash">
 /// Hash algorithm.
 /// <para/>
 /// Хэш алгоритм.
 /// </param>
 ///
 /// <param name="encoding">
 /// Encoding, default value: UTF8.
 /// <para/>
 /// Кодировка, стандартное значение: UTF8.
 /// </param>
 ///
 /// <exception cref="ArgumentNullException"/>
 public static byte[] GetHash(this string str, HashAlgorithm hash, Encoding encoding = null) => str.GetBytes(encoding).GetHash(hash);
Example #40
0
 private static byte[] GetHash(string inputString)
 {
     using (HashAlgorithm algorithm = SHA256.Create())
         return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
 }
 public PCLCryptographer(HashAlgorithm algorithm = HashAlgorithm.Md5)
 {
     _hasher = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(algorithm);
 }
 /// <summary>
 /// Sets the hashing function used in the filter.
 /// </summary>
 /// <param name="h">The HashAlgorithm to use.</param>
 public void SetHash(HashAlgorithm h)
 {
     this.Hash = h;
 }
Example #43
0
        /// <summary>
        /// Verilen input verisinin istenen algoritmaya göre hash'ini üretir.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="alg"></param>
        /// <returns></returns>
        public byte[] GetHash(byte[] input, HashAlgorithms alg)
        {
            HashAlgorithm hash = HashAlgorithm.Create(alg.ToString());

            return(hash.ComputeHash(input));
        }
Example #44
0
        /// <summary>
        ///     使用指定算法Hash
        /// </summary>
        public static byte[] Hash(this byte[] data, string hashName)
        {
            var algorithm = string.IsNullOrEmpty(hashName) ? HashAlgorithm.Create() : HashAlgorithm.Create(hashName);

            return(algorithm?.ComputeHash(data));
        }
Example #45
0
 private byte[] GetComputerNameHash()
 {
     return(HashAlgorithm
            .Create("MD5").ComputeHash(Encoding.UTF8.GetBytes(_computerNameProvider.Get())));
 }
Example #46
0
        private void ReadFrom(Stream s, string password)
        {
            byte[] format = new byte[2];
            s.Read(format, 0, 2);

            if (Encoding.ASCII.GetString(format) != "CC")
            {
                throw new InvalidCryptoContainerException("Invalid CryptoContainer format.");
            }

            switch (s.ReadByte()) //version
            {
            case 0:
                ReadPlainTextFrom(s);
                break;

            case 1:     //depricated version
            {
                if (password == null)
                {
                    throw new InvalidCryptoContainerException("Password required.");
                }

                //CryptoAlgo
                SymmetricEncryptionAlgorithm cryptoAlgo = (SymmetricEncryptionAlgorithm)s.ReadByte();

                //KeySizeBytes
                int keySizeBytes = s.ReadByte();

                byte[] IV = new byte[s.ReadByte()];
                s.Read(IV, 0, IV.Length);

                byte[] key;

                switch (keySizeBytes)
                {
                case 16:
                    key = HashAlgorithm.Create("MD5").ComputeHash(Encoding.UTF8.GetBytes(password));
                    break;

                case 32:
                    key = HashAlgorithm.Create("SHA256").ComputeHash(Encoding.UTF8.GetBytes(password));
                    break;

                default:
                    throw new CryptoException("CryptoContainer key size not supported.");
                }

                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                ReadPlainTextFrom(_containerKey.GetCryptoStreamReader(s));

                //auto upgrade to version 2 with PBKDF2-HMAC-SHA256 when calling WriteTo
                _kdf          = PBKDF2.CreateHMACSHA256(password, keySizeBytes, PBKDF2_ITERATION_COUNT);
                key           = _kdf.GetBytes(keySizeBytes);
                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                _hmac         = new HMACSHA256(key);
            }
            break;

            case 2:     //using PBKDF2-HMAC-SHA256
            {
                if (password == null)
                {
                    throw new InvalidCryptoContainerException("Password required.");
                }

                //CryptoAlgo
                SymmetricEncryptionAlgorithm cryptoAlgo = (SymmetricEncryptionAlgorithm)s.ReadByte();

                //KeySizeBytes
                int keySizeBytes = s.ReadByte();

                byte[] IV = new byte[s.ReadByte()];
                s.Read(IV, 0, IV.Length);

                byte[] salt = new byte[s.ReadByte()];
                s.Read(salt, 0, salt.Length);

                byte[] HMAC = new byte[s.ReadByte()];
                s.Read(HMAC, 0, HMAC.Length);

                _kdf = PBKDF2.CreateHMACSHA256(password, salt, PBKDF2_ITERATION_COUNT);
                byte[] key = _kdf.GetBytes(keySizeBytes);

                //authenticate data
                _hmac = new HMACSHA256(key);
                long   startPosition = s.Position;
                byte[] computedHMAC  = _hmac.ComputeHash(s);
                s.Position = startPosition;

                //verify hmac
                for (int i = 0; i < HMAC.Length; i++)
                {
                    if (HMAC[i] != computedHMAC[i])
                    {
                        throw new CryptoException("Invalid password or data tampered.");
                    }
                }

                //decrypt data
                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                ReadPlainTextFrom(_containerKey.GetCryptoStreamReader(s));
            }
            break;

            case -1:
                throw new EndOfStreamException();

            default:
                throw new InvalidCryptoContainerException("CryptoContainer format version not supported.");
            }
        }
Example #47
0
        /// <summary>
        /// Encrypts a stream
        /// </summary>
        /// <param name="Input">Source stream</param>
        /// <param name="Output">Output stream</param>
        /// <returns>true, if successfull</returns>
        /// <remarks>Output stream must be seekable</remarks>
        public CryptResult Encrypt(Stream Input, Stream Output)
        {
            if (Key == null || Salt == null)
            {
                return(CryptResult.PasswordInvalid);
            }
            if (!Input.CanRead)
            {
                return(CryptResult.StreamCantRead);
            }
            if (!Output.CanWrite)
            {
                return(CryptResult.StreamCantWrite);
            }
            if (!Output.CanSeek)
            {
                return(CryptResult.IOError);
            }
            else
            {
                using (Rijndael R = Rijndael.Create())
                {
                    var Header = new CryptHeader();
                    Header.Valid  = true;
                    Header.Cycles = Difficulty;
                    R.GenerateIV();
                    Header.IV = R.IV;
                    //Randomly generate a salt for each encryption task.
                    //This makes the password different for each file even if the source file and password are identical.
                    Header.Salt = Salt;
                    //Get Hash for password verification.
                    //This hash allows us to check if a user supplied the correct password for decryption.
                    //This should not be insecure as it still goes through the password generator and thus is very slow.
                    Header.KeyHash = GetPasswordByteHash(Key);
                    //Placeholder for the File hash. When decrypting, this is used to verify integrity.
                    Header.FileHash = new byte[256 / 8];
                    long HashPos = 0;
                    NotClosingCryptoStream CS;

                    Header.WriteTo(Output);
                    HashPos = Output.Position - Header.FileHash.Length - sizeof(int) /*Header.Cycles*/;

                    try
                    {
                        CS = new NotClosingCryptoStream(Output, R.CreateEncryptor(Key, R.IV), CryptoStreamMode.Write);
                    }
                    catch
                    {
                        return(CryptResult.CryptoStreamError);
                    }

                    using (CS)
                    {
                        using (var Hasher = (SHA256)HashAlgorithm.Create(HASHALG))
                        {
                            int    readed = 0;
                            byte[] Buffer = new byte[R.BlockSize * 10];
                            do
                            {
                                try
                                {
                                    readed = Input.Read(Buffer, 0, Buffer.Length);
                                }
                                catch
                                {
                                    return(CryptResult.IOError);
                                }
                                if (readed > 0)
                                {
                                    try
                                    {
                                        CS.Write(Buffer, 0, readed);
                                    }
                                    catch (IOException)
                                    {
                                        return(CryptResult.IOError);
                                    }
                                    catch
                                    {
                                        return(CryptResult.CryptoStreamError);
                                    }

                                    if (Input.Position == Input.Length)
                                    {
                                        var temp = Hasher.TransformFinalBlock(Buffer, 0, readed);
                                    }
                                    else
                                    {
                                        Hasher.TransformBlock(Buffer, 0, readed, Buffer, 0);
                                    }
                                }
                            } while (readed > 0);
                            Header.FileHash = CreateHMAC(Key, (byte[])Hasher.Hash.Clone());
                        }
                        try
                        {
                            CS.FlushFinalBlock();
                        }
                        catch (IOException)
                        {
                            return(CryptResult.IOError);
                        }
                        catch
                        {
                            return(CryptResult.CryptoStreamError);
                        }
                        //Store File hash and seek back to the end
                        try
                        {
                            Output.Flush();
                            long CurrentPos = Output.Position;
                            Output.Seek(HashPos, SeekOrigin.Begin);
                            Output.Write(Header.FileHash, 0, Header.FileHash.Length);
                            Output.Flush();
                            Output.Seek(Output.Position, SeekOrigin.Begin);
                        }
                        catch
                        {
                            return(CryptResult.IOError);
                        }
                    }
                }
            }
            return(CryptResult.Success);
        }
Example #48
0
File: Hash.cs Project: radtek/Pos
 Create_hash(HashAlgorithm algorithm, byte[] input)
 {
     return(algorithm.ComputeHash(input));
 }
Example #49
0
        private byte[] EncryptDataAgile(byte[] data, EncryptionInfoAgile encryptionInfo, HashAlgorithm hashProvider)
        {
            var ke = encryptionInfo.KeyEncryptors[0];

#if Core
            var aes = Aes.Create();
#else
            RijndaelManaged aes = new RijndaelManaged();
#endif
            aes.KeySize = ke.KeyBits;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;

            int pos     = 0;
            int segment = 0;

            //Encrypt the data
            var ms = RecyclableMemoryStream.GetStream();
            ms.Write(BitConverter.GetBytes((ulong)data.Length), 0, 8);
            while (pos < data.Length)
            {
                var segmentSize = (int)(data.Length - pos > 4096 ? 4096 : data.Length - pos);

                var ivTmp = new byte[4 + encryptionInfo.KeyData.SaltSize];
                Array.Copy(encryptionInfo.KeyData.SaltValue, 0, ivTmp, 0, encryptionInfo.KeyData.SaltSize);
                Array.Copy(BitConverter.GetBytes(segment), 0, ivTmp, encryptionInfo.KeyData.SaltSize, 4);
                var iv = hashProvider.ComputeHash(ivTmp);

                EncryptAgileFromKey(ke, ke.KeyValue, data, pos, segmentSize, iv, ms);
                pos += segmentSize;
                segment++;
            }
            ms.Flush();
            return(ms.ToArray());
        }
 /// <summary>
 /// Generates the file hash.
 /// </summary>
 /// <param name="fileSystem">The file system.</param>
 /// <param name="filePath">The file path.</param>
 /// <param name="hashProvider">The hash provider.</param>
 /// <returns>
 /// An SHA1 hash for the file.
 /// </returns>
 private static byte[] GenerateFileHash(IFileSystem fileSystem, string filePath, HashAlgorithm hashProvider)
 {
     using (var stream = fileSystem.OpenInputStream(filePath))
     {
         var hash = hashProvider.ComputeHash(stream);
         return(hash);
     }
 }
Example #51
0
 public HashStream(Stream wrapped, Ownership ownsWrapped, HashAlgorithm hashAlg)
 {
     _wrapped    = wrapped;
     _ownWrapped = ownsWrapped;
     _hashAlg    = hashAlg;
 }
Example #52
0
 /// <summary>
 /// Creates a Hasher with a specified algorithm and custom options
 /// </summary>
 /// <param name="algorithm"></param>
 /// <param name="options"></param>
 public Hasher(HashAlgorithm algorithm = null, HasherOptions options = null)
 {
     _algorithm = algorithm != null ? algorithm : SHA256.Create();
     Options    = HasherOptions.CreateMergedInstance(options);
 }
 /// <summary>
 /// Creates a new Hash function
 /// </summary>
 /// <param name="expr">Expression</param>
 /// <param name="hash">Hash Algorithm to use</param>
 public BaseHashFunction(ISparqlExpression expr, HashAlgorithm hash)
     : base(expr)
 {
     this._crypto = hash;
 }
 public static string HashFile(string filename, HashAlgorithm hashAlg)
 {
     return(Files.HashFile(filename, hashAlg));
 }
Example #55
0
        /// <summary>
        /// Decrypts a stream
        /// </summary>
        /// <param name="Input">Input stream</param>
        /// <param name="Output">Output stream</param>
        /// <returns>true, if successfull</returns>
        public CryptResult Decrypt(Stream Input, Stream Output, string Password)
        {
            if (!Input.CanRead)
            {
                return(CryptResult.StreamCantRead);
            }
            if (!Output.CanWrite)
            {
                return(CryptResult.StreamCantWrite);
            }
            var Header = GetHeader(Input);

            if (!Header.Valid)
            {
                return(CryptResult.InvalidFileState);
            }
            using (Rijndael R = Rijndael.Create())
            {
                NotClosingCryptoStream CS;

                byte[] Key = DeriveBytes(Password, MaxKeySize, Header.Salt, Header.Cycles);

                if (!CheckPasswordBytes(Key, Header.KeyHash))
                {
                    return(CryptResult.PasswordInvalid);
                }

                try
                {
                    CS = new NotClosingCryptoStream(Input, R.CreateDecryptor(Key, Header.IV), CryptoStreamMode.Read);
                }
                catch
                {
                    return(CryptResult.CryptoStreamError);
                }
                using (CS)
                {
                    using (var Hasher = (SHA256)HashAlgorithm.Create(HASHALG))
                    {
                        byte[] Data   = new byte[R.BlockSize * 100];
                        int    readed = 0;
                        do
                        {
                            try
                            {
                                readed = CS.Read(Data, 0, Data.Length);
                            }
                            catch (IOException)
                            {
                                return(CryptResult.IOError);
                            }
                            catch
                            {
                                return(CryptResult.CryptoStreamError);
                            }
                            if (readed > 0)
                            {
                                try
                                {
                                    Output.Write(Data, 0, readed);
                                }
                                catch
                                {
                                    return(CryptResult.IOError);
                                }
                                //Always read a multiple of the supported blocksize to avoid problems with readahead
                                if (Input.Position == Input.Length)
                                {
                                    Hasher.TransformFinalBlock(Data, 0, readed);
                                }
                                else
                                {
                                    Hasher.TransformBlock(Data, 0, readed, Data, 0);
                                }
                            }
                        } while (readed > 0);
                        if (!VerifyHMAC(Key, Header.FileHash, Hasher.Hash))
                        {
                            return(CryptResult.FileHashInvalid);
                        }
                    }
                }
            }
            return(CryptResult.Success);
        }
 static void hash <O, T, D, M>(O result, HashAlgorithm algo, T @base, D data, M max)
 {
     throw new NotImplementedException();
 }
Example #57
0
 // Methods
 private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
 {
     byte[] bytes = Encoding.GetEncoding("ASCII").GetBytes(data);
     return(Convert.ToBase64String(hashAlgorithm.ComputeHash(bytes)));
 }
Example #58
0
 private string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
 {
     return(this.ComputeHash(hash, signatureBase));
 }
        private static void CompressTemplate(string sampleFileName, bool useSpan, bool success, int threads, LzmaCompLevel level, bool extreme)
        {
            string destDir = Path.GetTempFileName();

            File.Delete(destDir);
            Directory.CreateDirectory(destDir);
            try
            {
                string tempDecompFile = Path.Combine(destDir, Path.GetFileName(sampleFileName));
                string tempXzFile     = tempDecompFile + ".xz";

                XZCompressOptions compOpts = new XZCompressOptions
                {
                    Level       = level,
                    ExtremeFlag = extreme,
                    LeaveOpen   = true,
                };
                XZThreadedCompressOptions threadOpts = new XZThreadedCompressOptions
                {
                    Threads = threads,
                };

                string sampleFile = Path.Combine(TestSetup.SampleDir, sampleFileName);
                using (FileStream xzCompFs = new FileStream(tempXzFile, FileMode.Create, FileAccess.Write, FileShare.None))
                    using (FileStream sampleFs = new FileStream(sampleFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        using (XZStream xzs = new XZStream(xzCompFs, compOpts, threadOpts))
                        {
                            if (useSpan)
                            {
                                byte[] buffer = new byte[64 * 1024];

                                int bytesRead;
                                do
                                {
                                    bytesRead = sampleFs.Read(buffer.AsSpan());
                                    xzs.Write(buffer.AsSpan(0, bytesRead));
                                } while (0 < bytesRead);
                            }
                            else
                            {
                                sampleFs.CopyTo(xzs);
                            }

                            xzs.Flush();
                            xzs.GetProgress(out ulong finalIn, out ulong finalOut);

                            Assert.AreEqual(sampleFs.Length, xzs.TotalIn);
                            Assert.AreEqual(xzCompFs.Length, xzs.TotalOut);
                            Assert.AreEqual((ulong)sampleFs.Length, finalIn);
                            Assert.AreEqual((ulong)xzCompFs.Length, finalOut);
                        }

                Assert.IsTrue(TestHelper.RunXZ(tempXzFile) == 0);

                byte[] decompDigest;
                byte[] originDigest;
                using (FileStream fs = new FileStream(sampleFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using HashAlgorithm hash = SHA256.Create();
                    originDigest             = hash.ComputeHash(fs);
                }

                using (FileStream fs = new FileStream(tempDecompFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using HashAlgorithm hash = SHA256.Create();
                    decompDigest             = hash.ComputeHash(fs);
                }

                Assert.IsTrue(originDigest.SequenceEqual(decompDigest));
                Assert.IsTrue(success);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception)
            {
                Assert.IsFalse(success);
            }
#pragma warning restore CA1031 // Do not catch general exception types
            finally
            {
                if (Directory.Exists(destDir))
                {
                    Directory.Delete(destDir, true);
                }
            }
        }
Example #60
0
        public static byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = MD5.Create();  //or use SHA1.Create();

            return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
        }