Esempio n. 1
0
 /// <summary>
 ///     Initializes the SHA384 hash provider
 /// </summary>
 public Sha384Context()
 {
     sha384Provider = SHA384.Create();
 }
Esempio n. 2
0
        /// <summary>
        /// 获取Hash后的字节数组
        /// </summary>
        /// <param name="type">哈希类型</param>
        /// <param name="key">key</param>
        /// <param name="bytes">原字节数组</param>
        /// <returns></returns>
        public static byte[] GetHashedBytes(HashType type, byte[] bytes, byte[] key)
        {
            if (null == bytes)
            {
                return(bytes);
            }

            HashAlgorithm algorithm = null;

            try
            {
                if (key == null)
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = MD5.Create();
                        break;

                    case HashType.SHA1:
                        algorithm = SHA1.Create();
                        break;

                    case HashType.SHA256:
                        algorithm = SHA256.Create();
                        break;

                    case HashType.SHA384:
                        algorithm = SHA384.Create();
                        break;

                    case HashType.SHA512:
                        algorithm = SHA512.Create();
                        break;

                    default:
                        algorithm = MD5.Create();
                        break;
                    }
                }
                else
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = new HMACMD5(key);
                        break;

                    case HashType.SHA1:
                        algorithm = new HMACSHA1(key);
                        break;

                    case HashType.SHA256:
                        algorithm = new HMACSHA256(key);
                        break;

                    case HashType.SHA384:
                        algorithm = new HMACSHA384(key);
                        break;

                    case HashType.SHA512:
                        algorithm = new HMACSHA512(key);
                        break;

                    default:
                        algorithm = new HMACMD5(key);
                        break;
                    }
                }
                return(algorithm.ComputeHash(bytes));
            }
            finally
            {
                algorithm?.Dispose();
            }
        }
Esempio n. 3
0
 protected override HashAlgorithm Create()
 {
     return(SHA384.Create());
 }
Esempio n. 4
0
        private async void cryptButton_Click(object sender, RoutedEventArgs e)
        {
            switch (comboBox.Text)
            {
            case "MD5":
            {
                hashObject = MD5.Create();

                // this ain't working //Task<byte[]> task = new Task<byte[]>(hashObject.ComputeHash(fstream));
                //Task<byte[]> task = new Task<byte[]>(() => hashObject.ComputeHash(fstream));
                Task <byte[]> task = new Task <byte[]>(() => myComputeHash(hashObject, fstream));
                task.Start();
                hashValue = await task;
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            case "RIPEMD160":
            {
                hashObject = RIPEMD160.Create();
                Task <byte[]> task = new Task <byte[]>(() => hashObject.ComputeHash(fstream));
                task.Start();
                hashValue = await task;
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            case "SHA1":
            {
                hashObject = SHA1.Create();
                //before
                //hashValue = hashObject.ComputeHash(fstream);
                //after
                Task <byte[]> task = new Task <byte[]>(() => hashObject.ComputeHash(fstream));
                task.Start();
                hashValue = await task;
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            case "SHA256":
            {
                hashObject = SHA256.Create();
                hashValue  = hashObject.ComputeHash(fstream);
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            case "SHA384":
            {
                hashObject = SHA384.Create();
                hashValue  = hashObject.ComputeHash(fstream);
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            case "SHA512":
            {
                hashObject = SHA512.Create();
                hashValue  = hashObject.ComputeHash(fstream);
                MessageBox.Show(BitConverter.ToString(hashValue).Replace("-", ""));
                break;
            }

            default:
            {
                MessageBox.Show("You didn't choose ANYTHING.");
                break;
            }
            }
        }
 public SHA384CryptoServiceProvider2()
 {
     _implementation = CryptoServiceFallbackHelper.CreateImplementation <SHA384, SHA384CryptoServiceProvider, SHA384Managed>();
 }
Esempio n. 6
0
 protected override HashAlgorithm CreateHashAlgorithm() => SHA384.Create();
Esempio n. 7
0
        public static byte[] GetHash(HashType type, Stream stream, long reportInterval, IProgress <long> progress)
        {
            HashAlgorithm hash = null;

            try
            {
                switch (type)
                {
                case HashType.MD5:
                    hash = MD5.Create();
                    break;

                case HashType.SHA1:
                    hash = SHA1.Create();
                    break;

                case HashType.SHA256:
                    hash = SHA256.Create();
                    break;

                case HashType.SHA384:
                    hash = SHA384.Create();
                    break;

                case HashType.SHA512:
                    hash = SHA512.Create();
                    break;

                default:
                    throw new InvalidOperationException("Invalid Hash Type");
                }

                // No progress report
                if (reportInterval <= 0 || progress == null)
                {
                    return(hash.ComputeHash(stream));
                }

                // With progress report
                long   nextReport = reportInterval;
                long   offset     = stream.Position;
                byte[] buffer     = new byte[BufferSize];
                int    bytesRead;
                do
                {
                    bytesRead = stream.Read(buffer, 0, buffer.Length);
                    hash.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                    offset += bytesRead;
                    if (nextReport <= offset)
                    {
                        progress.Report(offset);
                        nextReport += reportInterval;
                    }
                }while (0 < bytesRead);

                hash.TransformFinalBlock(buffer, 0, 0);
                return(hash.Hash);
            }
            finally
            {
                if (hash != null)
                {
                    hash.Dispose();
                }
            }
        }
 public SHA384Function() : base()
 {
     _Hash = SHA384.Create();
 }
Esempio n. 9
0
 // Test the properties of the default algorithm instance.
 public void TestSHA384Properties()
 {
     HashPropertyTest(SHA384.Create(), 384);
 }
Esempio n. 10
0
        /// <summary>
        /// Computes the SHA384 hash
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private byte[] ComputeSHA384(byte[] data)
        {
            var sha384 = SHA384.Create();

            return(sha384.ComputeHash(data));
        }
Esempio n. 11
0
 public static SHA384 CreateSHA384()
 {
     return(SHA384.Create(CryptoConfig.AllowOnlyFipsAlgorithms ? _SHA384CryptoServiceProvider : _SHA384Cng));
 }
Esempio n. 12
0
 public SHA384Cng()
 {
     // note: we don't use SHA384.Create since CryptoConfig could,
     // if set to use this class, result in a endless recursion
     hash = new SHA384Managed();
 }
Esempio n. 13
0
        internal static async Task SignRequest(HttpClient client, HttpMethod method, string serviceUrl,
                                               HttpContent content, string consumerKey, string consumerSecret, SignatureMethod signatureMethod)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (string.IsNullOrEmpty(serviceUrl))
            {
                throw new ArgumentNullException(nameof(serviceUrl));
            }

            var serviceUri = new Uri(serviceUrl, UriKind.RelativeOrAbsolute);

            if (!serviceUri.IsAbsoluteUri)
            {
                if (client.BaseAddress == null)
                {
                    throw new LtiException("If serviceUrl is relative, client.BaseAddress cannot be null.");
                }

                if (!Uri.TryCreate(client.BaseAddress, serviceUrl, out serviceUri))
                {
                    throw new LtiException($"Cannot form a valid URI from {client.BaseAddress} and {serviceUrl}.");
                }
            }

            var ltiRequest = new LtiRequest(LtiConstants.LtiOauthBodyHashMessageType)
            {
                ConsumerKey = consumerKey,
                HttpMethod  = method.Method,
                Url         = serviceUri
            };

            AuthenticationHeaderValue authorizationHeader;

            // Determine hashing algorithm
            HashAlgorithm sha;

            switch (signatureMethod)
            {
            default:
            case SignatureMethod.HmacSha1:
                sha = SHA1.Create();
                break;

            case SignatureMethod.HmacSha256:
                sha = SHA256.Create();
                break;

            case SignatureMethod.HmacSha384:
                sha = SHA384.Create();
                break;

            case SignatureMethod.HmacSha512:
                sha = SHA512.Create();
                break;
            }

            // Create an Authorization header using the body hash
            using (sha)
            {
                var hash = sha.ComputeHash(await content.ReadAsByteArrayAsync());
                authorizationHeader = ltiRequest.GenerateAuthorizationHeader(hash, consumerSecret);
            }

            // Attach the header to the client request
            client.DefaultRequestHeaders.Authorization = authorizationHeader;
        }
Esempio n. 14
0
        public Command GetCommand()
        {
            CTS = new CancellationTokenSource();
            CT  = CTS.Token;
            TABLE.Add(new CommandArgumentEntry("[string] [string]", true, "[wordlist path] [hash]"));
            CMD_HASHCRACK = new Command("HASHCRACK", TABLE, false, "Starts a search for a matching hash value in the specified wordlist. Supported hash types: SHA1, SHA256, SHA384, SHA512.", ExecutionLevel.User, CLIMode.Default);
            CMD_HASHCRACK.SetAsyncFunction(async() =>
            {
                processedWords = 0;
                progress       = 0;
                count          = 0;
                currentWord    = null;
                currentResult  = null;
                try
                {
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = true;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown += Main_KeyDown;
                    });
                    HashType hashType;

                    string result = null;
                    async Task HASH_TASK(string word)
                    {
                        await Task.Delay(0);
                        object hashingObject = null;
                        string hash          = null;
                        if (result == null)
                        {
                            switch (hashType)
                            {
                            case HashType.SHA1:
                                hashingObject = SHA1.Create();
                                hash          = BitConverter.ToString(((SHA1)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA256:
                                hashingObject = SHA256.Create();
                                hash          = BitConverter.ToString(((SHA256)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA384:
                                hashingObject = SHA384.Create();
                                hash          = BitConverter.ToString(((SHA384)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA512:
                                hashingObject = SHA512.Create();
                                hash          = BitConverter.ToString(((SHA512)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;
                            }
                            if (hash == CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString().ToUpper())
                            {
                                result = word;
                            }
                        }

                        currentResult = hash;
                        currentWord   = word;
                        processedWords++;
                        progress      = processedWords / count * 100;
                        word          = null;
                        hash          = null;
                        hashingObject = null;
                    }

                    List <Task> taskList = new List <Task>();
                    Regex hexCheck       = new Regex("^[a-fA-F0-9]*$");
                    switch (CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString().Length)
                    {
                    case 40 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA1;
                        break;

                    case 64 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA256;
                        break;

                    case 96 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA384;
                        break;

                    case 128 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA512;
                        break;

                    default:
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        });
                        return("\nIncorrect hash format or unsupported type!");
                    }
                    string path = null;
                    if (File.Exists(CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString()) && CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString().Contains(":"))
                    {
                        path = CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString();
                    }
                    else if (File.Exists(EnvironmentVariables.GetCurrentValue("DIRECTORY").ToString() + CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString()))
                    {
                        path = EnvironmentVariables.GetCurrentValue("DIRECTORY").ToString() + CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString();
                    }
                    if (path == null)
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        });
                        return("\nFile not found!");
                    }
                    string[] lines = File.ReadAllLines(path);
                    count          = lines.Length;
                    taskList.Add(Task.Run(async() => { await HASH_TASK(lines[0]); }));
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (CT.IsCancellationRequested)
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                            {
                                ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                                ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                            });
                            return("\nProcess interrupted.");
                        }
                        if (result != null)
                        {
                            break;
                        }
                        taskList.RemoveAll(x => x.IsCompleted);
                        taskList.Add(Task.Run(async() => { await HASH_TASK(lines[i]); }));
                    }
                    await Task.WhenAll(taskList).ContinueWith(t => t.Dispose());
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                    });
                    if (result == null)
                    {
                        return("\nNo matching hash found!");
                    }
                    return($"\nResult: {result}");
                }
                catch (Exception ex)
                {
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        IOInteractLayer.StandardError(CMD_HASHCRACK, ex);
                    });
                    return("");
                }
            });
            return(CMD_HASHCRACK);
        }
Esempio n. 15
0
        public static byte[] GetHash(HashType type, byte[] input, int reportInterval, IProgress <long> progress)
        {
            HashAlgorithm hash = null;

            try
            {
                switch (type)
                {
                case HashType.MD5:
                    hash = MD5.Create();
                    break;

                case HashType.SHA1:
                    hash = SHA1.Create();
                    break;

                case HashType.SHA256:
                    hash = SHA256.Create();
                    break;

                case HashType.SHA384:
                    hash = SHA384.Create();
                    break;

                case HashType.SHA512:
                    hash = SHA512.Create();
                    break;

                default:
                    throw new InvalidOperationException("Invalid Hash Type");
                }

                // No progress report
                if (reportInterval <= 0 || progress == null)
                {
                    return(hash.ComputeHash(input));
                }

                // With progress report
                int offset = 0;
                while (offset < input.Length)
                {
                    if (offset + reportInterval < input.Length)
                    {
                        hash.TransformBlock(input, offset, reportInterval, input, offset);
                        offset += reportInterval;
                    }
                    else // Last run
                    {
                        int bytesRead = input.Length - offset;
                        hash.TransformFinalBlock(input, offset, bytesRead);
                        offset += bytesRead;
                    }

                    progress.Report(offset);
                }
                return(hash.Hash);
            }
            finally
            {
                if (hash != null)
                {
                    hash.Dispose();
                }
            }
        }
        /// <summary>
        /// Construct the strong assembly name from metadata
        /// </summary>
        internal static string GetAssemblyStrongName(MetadataReader metadataReader)
        {
            AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
            string             asmName            = metadataReader.GetString(assemblyDefinition.Name);
            string             asmVersion         = assemblyDefinition.Version.ToString();
            string             asmCulture         = metadataReader.GetString(assemblyDefinition.Culture);

            asmCulture = (asmCulture == string.Empty) ? "neutral" : asmCulture;

            AssemblyHashAlgorithm hashAlgorithm = assemblyDefinition.HashAlgorithm;
            BlobHandle            blobHandle    = assemblyDefinition.PublicKey;
            BlobReader            blobReader    = metadataReader.GetBlobReader(blobHandle);

            string publicKeyTokenString = "null";

            // Extract public key token only if PublicKey exists in the metadata
            if (blobReader.Length > 0)
            {
                byte[] publickey = blobReader.ReadBytes(blobReader.Length);

                HashAlgorithm hashImpl = null;
                switch (hashAlgorithm)
                {
                case AssemblyHashAlgorithm.Sha1:
                    hashImpl = SHA1.Create();
                    break;

                case AssemblyHashAlgorithm.MD5:
                    hashImpl = MD5.Create();
                    break;

                case AssemblyHashAlgorithm.Sha256:
                    hashImpl = SHA256.Create();
                    break;

                case AssemblyHashAlgorithm.Sha384:
                    hashImpl = SHA384.Create();
                    break;

                case AssemblyHashAlgorithm.Sha512:
                    hashImpl = SHA512.Create();
                    break;

                default:
                    throw new NotSupportedException();
                }

                byte[] publicKeyHash       = hashImpl.ComputeHash(publickey);
                byte[] publicKeyTokenBytes = new byte[8];
                // Note that, the low 8 bytes of the hash of public key in reverse order is the public key tokens.
                for (int i = 1; i <= 8; i++)
                {
                    publicKeyTokenBytes[i - 1] = publicKeyHash[publicKeyHash.Length - i];
                }

                // Convert bytes to hex format strings in lower case.
                publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant();
            }

            string strongAssemblyName = string.Format(CultureInfo.InvariantCulture,
                                                      "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                                                      asmName, asmVersion, asmCulture, publicKeyTokenString);

            return(strongAssemblyName);
        }
        internal static string GetHashCore(KernelTransaction transaction, string fileFullPath, HashType hashType, PathFormat pathFormat)
        {
            const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;
            var fileNameLp = Path.GetExtendedLengthPathCore(transaction, fileFullPath, pathFormat, options);

            byte[] hash = null;


            using (var fs = OpenCore(transaction, fileNameLp, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath))
            {
                switch (hashType)
                {
                case HashType.CRC32:
                    using (var hType = new Crc32())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.CRC64ISO3309:
                    using (var hType = new Crc64())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.MD5:
                    using (var hType = MD5.Create())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.RIPEMD160:
                    using (var hType = RIPEMD160.Create())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.SHA1:
                    using (var hType = SHA1.Create())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.SHA256:
                    using (var hType = SHA256.Create())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.SHA384:
                    using (var hType = SHA384.Create())
                        hash = hType.ComputeHash(fs);
                    break;


                case HashType.SHA512:
                    using (var hType = SHA512.Create())
                        hash = hType.ComputeHash(fs);
                    break;
                }
            }


            if (null != hash)
            {
                var sb = new StringBuilder(hash.Length);

                foreach (var b in hash)
                {
                    sb.Append(b.ToString("X2", CultureInfo.InvariantCulture));
                }

                return(sb.ToString().ToUpperInvariant());
            }

            return(string.Empty);
        }
        private static void Verify(
            ref ECParameters iutParameters,
            ref ECParameters cavsParameters,
            ECCurve explicitCurve,
            byte[] iutZ)
        {
            using (ECDiffieHellman iut = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman cavs = ECDiffieHellmanFactory.Create())
                {
                    iut.ImportParameters(iutParameters);
                    cavs.ImportParameters(cavsParameters);

                    using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                        using (HashAlgorithm sha256 = SHA256.Create())
                            using (HashAlgorithm sha384 = SHA384.Create())
                            {
                                Verify(iut, cavsPublic, sha256, HashAlgorithmName.SHA256, iutZ);
                                Verify(iut, cavsPublic, sha384, HashAlgorithmName.SHA384, iutZ);
                            }

                    if (ECDiffieHellmanFactory.ExplicitCurvesSupported)
                    {
                        iutParameters.Curve = explicitCurve;
                        iut.ImportParameters(iutParameters);

                        // IUT is explicit, CAVS is named, but they're the same key.
                        // If this test ever starts throwing CryptographicException we can guard it.
                        // Support is entirely left up to the library.
                        // It was kind of surprising that it worked.
                        using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                            using (HashAlgorithm sha256 = SHA256.Create())
                                using (HashAlgorithm sha512 = SHA512.Create())
                                {
                                    bool trySecondCase = true;

                                    try
                                    {
                                        Verify(iut, cavsPublic, sha256, HashAlgorithmName.SHA256, iutZ);
                                    }
                                    catch (CryptographicException)
                                    {
                                        // This is expected to work on Windows.
                                        // On Linux (via OpenSSL) it is less predictable, since it fails with
                                        // EVP_PKEY_derive_set_peer:different parameters if one key uses
                                        // the GFp_simple routines and another uses GFp_nist or GFp_mont (or,
                                        // one presumes, something custom from an HSM) even if they actually
                                        // represent the same curve.
                                        //
                                        // secp256r1 and secp521r1 both succeed this block, secp384r1 fails.
                                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                                        {
                                            throw;
                                        }

                                        trySecondCase = false;
                                    }

                                    // If the first one failed, don't try the second.
                                    // If the first one passed, the second should, too.
                                    if (trySecondCase)
                                    {
                                        Verify(iut, cavsPublic, sha512, HashAlgorithmName.SHA512, iutZ);
                                    }
                                }

                        cavsParameters.Curve = explicitCurve;
                        cavs.ImportParameters(cavsParameters);

                        // Explicit, explicit; over the same curve.
                        using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                            using (HashAlgorithm sha384 = SHA384.Create())
                                using (HashAlgorithm sha512 = SHA512.Create())
                                {
                                    Verify(iut, cavsPublic, sha384, HashAlgorithmName.SHA384, iutZ);
                                    Verify(iut, cavsPublic, sha512, HashAlgorithmName.SHA512, iutZ);
                                }
                    }
                }
        }
Esempio n. 19
0
        /// <summary>
        /// Populates the OutputColumn class with all the required information to generate Hash's.
        /// </summary>
        /// <param name="bufferManager">The buffermanager that is affected by this</param>
        /// <param name="output">The output to find the column in</param>
        /// <param name="input">The input where all the data comes from</param>
        /// <param name="outputColumnIndex">The Column Index of the output column.</param>
        public void AddColumnInformation(IDTSBufferManager bufferManager, IDTSOutput output, IDTSInput input, int outputColumnIndex)
        {
            if (bufferManager == null)
            {
                throw new ArgumentNullException("bufferManager");
            }

            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            IDTSOutputColumn outputColumn = output.OutputColumnCollection[outputColumnIndex];

            string[] inputLineageIDList;
            inputLineageIDList  = outputColumn.CustomPropertyCollection[Utility.InputColumnLineagePropName].Value.ToString().Split(',');
            this.outputHashType = (MultipleHash.HashTypeEnumerator)outputColumn.CustomPropertyCollection[Utility.HashTypePropName].Value;
            this.outputDataType = (MultipleHash.OutputTypeEnumerator)outputColumn.CustomPropertyCollection[Utility.OutputColumnOutputTypePropName].Value;

            switch (this.outputHashType)
            {
            case MultipleHash.HashTypeEnumerator.None:
                break;

            case MultipleHash.HashTypeEnumerator.MD5:
                this.hashMD5 = MD5.Create();
                break;

            case MultipleHash.HashTypeEnumerator.RipeMD160:
                this.hashRipeMD160 = RIPEMD160.Create();
                break;

            case MultipleHash.HashTypeEnumerator.SHA1:
                this.hashSHA1 = SHA1.Create();
                break;

            case MultipleHash.HashTypeEnumerator.SHA256:
                this.hashSHA256 = SHA256.Create();
                break;

            case MultipleHash.HashTypeEnumerator.SHA384:
                this.hashSHA384 = SHA384.Create();
                break;

            case MultipleHash.HashTypeEnumerator.SHA512:
                this.hashSHA512 = SHA512.Create();
                break;

            case MultipleHash.HashTypeEnumerator.CRC32:
                this.hashCRC32 = CRC32.Create();
                break;

            case MultipleHash.HashTypeEnumerator.CRC32C:
                this.hashCRC32C = CRC32C.Create();
                break;

            case MultipleHash.HashTypeEnumerator.FNV1a32:
                this.hashFNV1a32 = FNV1a32.Create();
                break;

            case MultipleHash.HashTypeEnumerator.FNV1a64:
                this.hashFNV1a64 = FNV1a64.Create();
                break;

            case MultipleHash.HashTypeEnumerator.MurmurHash3a:
                //ToDo: Call the MurmurHash
                this.hashMurmur3a = Murmur3a.Create();
                break;

            case MultipleHash.HashTypeEnumerator.xxHash:
                // todo: call the xxHash
                this.hashxxHash = xxHash.Create();
                break;

            default:
                break;
            }

            // Store all the input column ID's for the column's to be Hashed
            int inputColumnLineageID;

            foreach (string inputLineageID in inputLineageIDList)
            {
                int columnId = System.Convert.ToInt32(inputLineageID.Substring(1));
                Microsoft.SqlServer.Dts.Pipeline.Wrapper.DTP_BUFFCOL columnData = new Microsoft.SqlServer.Dts.Pipeline.Wrapper.DTP_BUFFCOL();
                inputColumnLineageID = bufferManager.FindColumnByLineageID(input.Buffer, columnId);  // Strip the # from the ID

                bufferManager.GetColumnInfo(input.Buffer, inputColumnLineageID, ref columnData);
                MHashColumnInformation inputColumn = new MHashColumnInformation(inputColumnLineageID, columnData.DataType);
                this.inputColumnDetails.Add(inputColumn);
            }

            // Store the Column ID for the Output Column
            this.outputColumnID = bufferManager.FindColumnByLineageID(input.Buffer, outputColumn.LineageID);
        }
Esempio n. 20
0
        async Task AuthenticateSASL(List <string> mechanisms, string username, bool async, CancellationToken cancellationToken = default)
        {
            // At the time of writing PostgreSQL only supports SCRAM-SHA-256 and SCRAM-SHA-256-PLUS
            var supportsSha256     = mechanisms.Contains("SCRAM-SHA-256");
            var supportsSha256Plus = mechanisms.Contains("SCRAM-SHA-256-PLUS");

            if (!supportsSha256 && !supportsSha256Plus)
            {
                throw new NpgsqlException("No supported SASL mechanism found (only SCRAM-SHA-256 and SCRAM-SHA-256-PLUS are supported for now). " +
                                          "Mechanisms received from server: " + string.Join(", ", mechanisms));
            }

            var mechanism      = string.Empty;
            var cbindFlag      = string.Empty;
            var cbind          = string.Empty;
            var successfulBind = false;

            if (supportsSha256Plus)
            {
                var sslStream = (SslStream)_stream;
                if (sslStream.RemoteCertificate is null)
                {
                    Log.Warn("Remote certificate null, falling back to SCRAM-SHA-256");
                }
                else
                {
                    using var remoteCertificate = new X509Certificate2(sslStream.RemoteCertificate);
                    // Checking for hashing algorithms
                    HashAlgorithm?hashAlgorithm = null;
                    var           algorithmName = remoteCertificate.SignatureAlgorithm.FriendlyName;
                    if (algorithmName is null)
                    {
                        Log.Warn("Signature algorithm was null, falling back to SCRAM-SHA-256");
                    }
                    else if (algorithmName.StartsWith("sha1", StringComparison.OrdinalIgnoreCase) ||
                             algorithmName.StartsWith("md5", StringComparison.OrdinalIgnoreCase) ||
                             algorithmName.StartsWith("sha256", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA256.Create();
                    }
                    else if (algorithmName.StartsWith("sha384", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA384.Create();
                    }
                    else if (algorithmName.StartsWith("sha512", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA512.Create();
                    }
                    else
                    {
                        Log.Warn($"Support for signature algorithm {algorithmName} is not yet implemented, falling back to SCRAM-SHA-256");
                    }

                    if (hashAlgorithm != null)
                    {
                        using var _ = hashAlgorithm;

                        // RFC 5929
                        mechanism = "SCRAM-SHA-256-PLUS";
                        // PostgreSQL only supports tls-server-end-point binding
                        cbindFlag = "p=tls-server-end-point";
                        // SCRAM-SHA-256-PLUS depends on using ssl stream, so it's fine
                        var cbindFlagBytes = Encoding.UTF8.GetBytes($"{cbindFlag},,");

                        var certificateHash = hashAlgorithm.ComputeHash(remoteCertificate.GetRawCertData());
                        var cbindBytes      = cbindFlagBytes.Concat(certificateHash).ToArray();
                        cbind          = Convert.ToBase64String(cbindBytes);
                        successfulBind = true;
                        IsScramPlus    = true;
                    }
                }
            }

            if (!successfulBind && supportsSha256)
            {
                mechanism = "SCRAM-SHA-256";
                // We can get here if PostgreSQL supports only SCRAM-SHA-256 or there was an error while binding to SCRAM-SHA-256-PLUS
                // So, we set 'n' (client does not support binding) if there was an error while binding
                // or 'y' (client supports but server doesn't) in other case
                cbindFlag      = supportsSha256Plus ? "n" : "y";
                cbind          = supportsSha256Plus ? "biws" : "eSws";
                successfulBind = true;
                IsScram        = true;
            }

            if (!successfulBind)
            {
                // We can get here if PostgreSQL supports only SCRAM-SHA-256-PLUS but there was an error while binding to it
                throw new NpgsqlException("Unable to bind to SCRAM-SHA-256-PLUS, check logs for more information");
            }

            var passwd = GetPassword(username) ??
                         throw new NpgsqlException($"No password has been provided but the backend requires one (in SASL/{mechanism})");

            // Assumption: the write buffer is big enough to contain all our outgoing messages
            var clientNonce = GetNonce();

            await WriteSASLInitialResponse(mechanism, PGUtil.UTF8Encoding.GetBytes($"{cbindFlag},,n=*,r={clientNonce}"), async, cancellationToken);
            await Flush(async, cancellationToken);

            var saslContinueMsg = Expect <AuthenticationSASLContinueMessage>(await ReadMessage(async, cancellationToken), this);

            if (saslContinueMsg.AuthRequestType != AuthenticationRequestType.AuthenticationSASLContinue)
            {
                throw new NpgsqlException("[SASL] AuthenticationSASLFinal message expected");
            }
            var firstServerMsg = AuthenticationSCRAMServerFirstMessage.Load(saslContinueMsg.Payload);

            if (!firstServerMsg.Nonce.StartsWith(clientNonce))
            {
                throw new InvalidOperationException("[SCRAM] Malformed SCRAMServerFirst message: server nonce doesn't start with client nonce");
            }

            var saltBytes      = Convert.FromBase64String(firstServerMsg.Salt);
            var saltedPassword = Hi(passwd.Normalize(NormalizationForm.FormKC), saltBytes, firstServerMsg.Iteration);

            var clientKey = HMAC(saltedPassword, "Client Key");

            byte[] storedKey;
            using (var sha256 = SHA256.Create())
                storedKey = sha256.ComputeHash(clientKey);

            var clientFirstMessageBare         = $"n=*,r={clientNonce}";
            var serverFirstMessage             = $"r={firstServerMsg.Nonce},s={firstServerMsg.Salt},i={firstServerMsg.Iteration}";
            var clientFinalMessageWithoutProof = $"c={cbind},r={firstServerMsg.Nonce}";

            var authMessage = $"{clientFirstMessageBare},{serverFirstMessage},{clientFinalMessageWithoutProof}";

            var clientSignature  = HMAC(storedKey, authMessage);
            var clientProofBytes = Xor(clientKey, clientSignature);
            var clientProof      = Convert.ToBase64String(clientProofBytes);

            var serverKey       = HMAC(saltedPassword, "Server Key");
            var serverSignature = HMAC(serverKey, authMessage);

            var messageStr = $"{clientFinalMessageWithoutProof},p={clientProof}";

            await WriteSASLResponse(Encoding.UTF8.GetBytes(messageStr), async, cancellationToken);
            await Flush(async, cancellationToken);

            var saslFinalServerMsg = Expect <AuthenticationSASLFinalMessage>(await ReadMessage(async, cancellationToken), this);

            if (saslFinalServerMsg.AuthRequestType != AuthenticationRequestType.AuthenticationSASLFinal)
            {
                throw new NpgsqlException("[SASL] AuthenticationSASLFinal message expected");
            }

            var scramFinalServerMsg = AuthenticationSCRAMServerFinalMessage.Load(saslFinalServerMsg.Payload);

            if (scramFinalServerMsg.ServerSignature != Convert.ToBase64String(serverSignature))
            {
                throw new NpgsqlException("[SCRAM] Unable to verify server signature");
            }

            var okMsg = Expect <AuthenticationRequestMessage>(await ReadMessage(async, cancellationToken), this);

            if (okMsg.AuthRequestType != AuthenticationRequestType.AuthenticationOk)
            {
                throw new NpgsqlException("[SASL] Expected AuthenticationOK message");
            }
Esempio n. 21
0
        public static byte[] GetHash384(string data)
        {
            SHA384 create_hash = SHA384.Create();

            return(create_hash.ComputeHash(Encoding.UTF8.GetBytes(data)));
        }
Esempio n. 22
0
 /// <summary>
 /// SHA384
 /// </summary>
 /// <param name="text"></param>
 /// <returns>由96个字符组成的十六进制的哈希散列字符串</returns>
 public static string Sha384(this string text) => Hash(text, SHA384.Create());
Esempio n. 23
0
 /// <summary>
 /// SHA384 加密
 /// </summary>
 /// <param name="input"> 要加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static string Sha384Encrypt(string input, Encoding encoding)
 {
     return(HashEncrypt(SHA384.Create(), input, encoding));
 }
Esempio n. 24
0
 public sealed override HashAlgorithm CreateDigest()
 {
     return(SHA384.Create());
 }
        private static string GetHashedStr(string data)
        {
            var hasher = SHA384.Create();

            return(EncodeBase64(hasher.ComputeHash(Encoding.UTF8.GetBytes(data))));
        }
Esempio n. 26
0
        public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm)
        {
            byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign");

            // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses.
            byte[] dataArray = new byte[33333];

            byte[] dataArray2 = new byte[dataArray.Length + 2];
            dataArray.CopyTo(dataArray2, 1);

            HashAlgorithm halg;

            if (hashAlgorithm == HashAlgorithmName.MD5)
            {
                halg = MD5.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA1)
            {
                halg = SHA1.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA256)
            {
                halg = SHA256.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA384)
            {
                halg = SHA384.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA512)
            {
                halg = SHA512.Create();
            }
            else
            {
                throw new Exception("Hash algorithm not supported.");
            }

            List <byte[]> signatures = new List <byte[]>(6);

            // Compute a signature using each of the SignData overloads.  Then, verify it using each
            // of the VerifyData overloads, and VerifyHash overloads.
            //
            // Then, verify that VerifyHash fails if the data is tampered with.

            signatures.Add(SignData(ecdsa, dataArray, hashAlgorithm));

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray)));

            foreach (byte[] signature in signatures)
            {
                Assert.True(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify 1");
                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4");
            }

            int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count();

            Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized");

            foreach (byte[] signature in signatures)
            {
                signature[signature.Length - 1] ^= 0xFF; // flip some bits
                Assert.False(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify Tampered 1");
                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4");
            }
        }
Esempio n. 27
0
 public static ReadOnlyMemory <byte> SHA384Hash()
 {
     return(SHA384.Create().ComputeHash(KeyPair().publicKey.ToArray()));
 }
Esempio n. 28
0
        /// <summary>
        /// Рассчитываем хеш корневого сертификата
        /// </summary>
        /// <param name="SFDump">Считанная строка</param>
        /// <returns>Строка хеша</returns>
        private static string CertExtr(string SFDump)
        {
            int             rootcert = 0;              //Расположение корневого сертификата в файле (второй или третий)
            string          pattern  = "3082.{4}3082"; //Бинарный признак сертификата с его длиной в середине (3082-4 знака-3082)
            MatchCollection matchs   = Regex.Matches(SFDump, pattern);
            List <string>   certs    = new List <string>();
            StringBuilder   SHAstr   = new StringBuilder(string.Empty);
            SHA256          mysha256 = SHA256.Create();
            SHA384          rsaPSS   = SHA384.Create();

            byte[] hashbytes = null;
            if (matchs.Count >= 2)
            {
                //Проверяем, реально ли сертификат по длине между 1 и 2
                string certl   = SFDump.Substring(matchs[0].Index + 4, 4); // Получили длину сертификата в строке хекс
                int    certlen = int.Parse(certl, NumberStyles.HexNumber); // Перевели её в 10 инт
                if ((matchs[0].Index + certlen * 2 + 8) == matchs[1].Index)
                {
                    rootcert = 2;
                    if (matchs.Count >= 3)
                    {
                        rootcert = 3;
                    }
                }
            }
            if (rootcert > 0)
            {
                for (int i = 0; i < rootcert; i++)
                {
                    string certl   = SFDump.Substring(matchs[i].Index + 4, 4);   // Получили длину сертификата в строке хекс
                    int    certlen = Int32.Parse(certl, NumberStyles.HexNumber); // Перевели её в 10 инт
                    certs.Insert(i, matchs[i].Value + SFDump.Substring(matchs[i].Index + 12, certlen * 2 - 4));
                }
                Guide guide = new Guide();
                foreach (KeyValuePair <string, int> correct_SHA in guide.SHA_magic_numbers)
                {
                    if (certs[rootcert - 1].Contains(correct_SHA.Key))
                    {
                        switch (correct_SHA.Value)
                        {
                        case 0:    //SHA384 - старые серты
                            hashbytes = rsaPSS.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            break;

                        case 1:    //SHA256 - старые серты
                            hashbytes = mysha256.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            break;

                        case 2:    //SHA256 - нормальные серты
                            hashbytes = mysha256.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            break;

                        case 3:    //SHA384 - новые серты
                            hashbytes = rsaPSS.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            break;

                        case 4:    //SHA384 - паченый старый программер
                            hashbytes = rsaPSS.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            break;

                        default:
                            //hashbytes = mysha256.ComputeHash(StringToByteArray(certs[rootcert - 1]));
                            hashbytes = null;
                            break;
                        }
                    }
                }
                if (hashbytes != null)
                {
                    SHAstr.Append(BitConverter.ToString(hashbytes));
                    SHAstr.Replace("-", string.Empty);
                    while (SHAstr.Length < 64)
                    {
                        SHAstr.Insert(0, '0');
                    }
                }
            }
            return(SHAstr.ToString());
        }
        /// <inheritdoc />
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (AddSubresourceIntegrity != true)
            {
                await base.ProcessAsync(context, output);

                return;
            }

            string?filePath = (context.AllAttributes["src"].Value as string)?.TrimStart(Tilde);
            string?type     = context.AllAttributes["type"]?.Value?.ToString() as string;

            if (string.IsNullOrEmpty(filePath) ||
                (!string.IsNullOrEmpty(type) && !string.Equals(type, "text/javascript", StringComparison.OrdinalIgnoreCase)))
            {
                // No file or not JavaScript
                await base.ProcessAsync(context, output);

                return;
            }

            IFileInfo fileInfo = HostingEnvironment.WebRootFileProvider.GetFileInfo(filePath);

            if (!fileInfo.Exists)
            {
                // Not a local file
                await base.ProcessAsync(context, output);

                return;
            }

            string cacheKey = $"sri-hash-{fileInfo.PhysicalPath}";

            if (!Cache.TryGetValue(cacheKey, out string hash))
            {
                using (var algorithm = SHA384.Create())
                {
                    using var stream = fileInfo.CreateReadStream();
                    hash             = Convert.ToBase64String(algorithm.ComputeHash(stream));
                }

                var options = new MemoryCacheEntryOptions()
                {
                    Size = hash.Length,
                };

                Cache.Set(cacheKey, hash, options);
            }

            output.Attributes.Add("integrity", $"sha384-{hash}");
            output.Attributes.Add("crossorigin", "anonymous");
        }
Esempio n. 30
0
		public SHA384Cng ()
		{
			// note: we don't use SHA384.Create since CryptoConfig could, 
			// if set to use this class, result in a endless recursion
			hash = new SHA384Managed ();
		}
Esempio n. 31
0
 public static byte[] ComputeSHA384(this byte[] buffer)
 {
     using var hasher = SHA384.Create();
     return(hasher.ComputeHash(buffer));
 }