System.Security.Cryptography.SHA256.Create()

Here are the examples of the csharp api System.Security.Cryptography.SHA256.Create() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

630 Examples 7

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

19 View Source File : UI.cs
License : MIT License
Project Creator : aaaddress1

private void compile_Click(object sender, EventArgs e)
        {

            (new System.Threading.Thread(() =>
            {
                this.Invoke((MethodInvoker)delegate () {
                    compile.Enabled = false;
                    logBox.Clear();
                    logMsg(demostr, Color.Blue);
                    this.splitContainer.Panel2Collapsed = false;
                    this.logPanelBtn.Text = "x";
                });
                File.WriteAllText(srcPath, this.fastColoredTextBox.Text);
                File.Delete(exePath);
                File.Delete(asmPath);
                File.Delete(obfAsmPath);

                logMsg(" --- \n", Color.Blue);
                logMsg(string.Format(
                        "[\tInfo\t] current compile info... \n" +
                        " - source: {0}\n" +
                        " - asm path: {1}\n" +
                        " - obfuscated asm path: {2}\n" +
                        " - output exe path: {3}\n", srcPath, asmPath, obfAsmPath, exePath), Color.Blue);

                if (compiler.geneateAsmSource(srcPath, asmPath))
                    logMsg("[\tOK\t] generate replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }

                if (obfuscator.obfuscaAsm(asmPath, obfAsmPath))
                    logMsg("[\tOK\t] generate obfuscated replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate obfuscated replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }
                if (compiler.generateExe(obfAsmPath, exePath))
                {
                    var arr = System.IO.File.ReadAllBytes(exePath);
                    var size = arr.Length;
                    var md5 = BitConverter.ToString(MD5.Create().ComputeHash(arr)).Replace("-", "");
                    var sha256 = BitConverter.ToString(SHA256.Create().ComputeHash(arr)).Replace("-", "");
                    logMsg("[\tInfo\t] exe size: " + size + " bytes", Color.Blue);
                    logMsg("[\tInfo\t] MD5: " + md5, Color.Blue);
                    logMsg("[\tInfo\t] SHA256: " + sha256, Color.Blue);
                    logMsg("[\tOK\t] generate executable file successfully :)", Color.Green);
                }
                else
                    logMsg("[\tFail\t] generate executable file failure ... o___O", Color.Red);
 
                if (Properties.Settings.Default.clnAftCompile)
                {
                    File.Delete(asmPath);
                    File.Delete(obfAsmPath);
                }
                this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
            })
            { IsBackground = true }).Start();
        }

19 View Source File : SHA2.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string Hash(SHA2Type type, string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);

            try
            {
                byte[] digest;
                switch (type)
                {
                    case SHA2Type.SHA256:
                        digest = SHA256.Create().ComputeHash(buffer);
                        break;
                    case SHA2Type.SHA512:
                        digest = SHA512.Create().ComputeHash(buffer);
                        break;
                    default:
                        return "";
                }

                return BitConverter.ToString(digest).Replace("-", "").ToLower();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return "";
            }
        }

19 View Source File : SelfUpdater.cs
License : MIT License
Project Creator : actions

private async Task DownloadLatestRunner(CancellationToken token)
        {
            string latestRunnerDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory);
            IOUtil.DeleteDirectory(latestRunnerDirectory, token);
            Directory.CreateDirectory(latestRunnerDirectory);

            int runnerSuffix = 1;
            string archiveFile = null;
            bool downloadSucceeded = false;

            try
            {
                // Download the runner, using multiple attempts in order to be resilient against any networking/CDN issues
                for (int attempt = 1; attempt <= Constants.RunnerDownloadRetryMaxAttempts; attempt++)
                {
                    // Generate an available package name, and do our best effort to clean up stale local zip files
                    while (true)
                    {
                        if (_targetPackage.Platform.StartsWith("win"))
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.zip");
                        }
                        else
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.tar.gz");
                        }

                        try
                        {
                            // delete .zip file
                            if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                            {
                                Trace.Verbose("Deleting latest runner package zip '{0}'", archiveFile);
                                IOUtil.DeleteFile(archiveFile);
                            }

                            break;
                        }
                        catch (Exception ex)
                        {
                            // couldn't delete the file for whatever reason, so generate another name
                            Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                            runnerSuffix++;
                        }
                    }

                    // Allow a 15-minute package download timeout, which is good enough to update the runner from a 1 Mbit/s ADSL connection.
                    if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_DOWNLOAD_TIMEOUT") ?? string.Empty, out int timeoutSeconds))
                    {
                        timeoutSeconds = 15 * 60;
                    }

                    Trace.Info($"Attempt {attempt}: save latest runner into {archiveFile}.");

                    using (var downloadTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)))
                    using (var downloadCts = CancellationTokenSource.CreateLinkedTokenSource(downloadTimeout.Token, token))
                    {
                        try
                        {
                            Trace.Info($"Download runner: begin download");

                            //open zip stream in async mode
                            using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
                            {
                                if (!string.IsNullOrEmpty(_targetPackage.Token))
                                {
                                    Trace.Info($"Adding authorization token ({_targetPackage.Token.Length} chars)");
                                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _targetPackage.Token);
                                }

                                Trace.Info($"Downloading {_targetPackage.DownloadUrl}");

                                using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                                using (Stream result = await httpClient.GetStreamAsync(_targetPackage.DownloadUrl))
                                {
                                    //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
                                    await result.CopyToAsync(fs, 81920, downloadCts.Token);
                                    await fs.FlushAsync(downloadCts.Token);
                                }
                            }

                            Trace.Info($"Download runner: finished download");
                            downloadSucceeded = true;
                            break;
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            Trace.Info($"Runner download has been canceled.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            if (downloadCts.Token.IsCancellationRequested)
                            {
                                Trace.Warning($"Runner download has timed out after {timeoutSeconds} seconds");
                            }

                            Trace.Warning($"Failed to get package '{archiveFile}' from '{_targetPackage.DownloadUrl}'. Exception {ex}");
                        }
                    }
                }

                if (!downloadSucceeded)
                {
                    throw new TaskCanceledException($"Runner package '{archiveFile}' failed after {Constants.RunnerDownloadRetryMaxAttempts} download attempts");
                }

                // If we got this far, we know that we've successfully downloaded the runner package
                // Validate Hash Matches if it is provided
                using (FileStream stream = File.OpenRead(archiveFile))
                {
                    if (!String.IsNullOrEmpty(_targetPackage.HashValue))
                    {
                        using (SHA256 sha256 = SHA256.Create())
                        {
                            byte[] srcHashBytes = await sha256.ComputeHashAsync(stream);
                            var hash = PrimitiveExtensions.ConvertToHexString(srcHashBytes);
                            if (hash != _targetPackage.HashValue)
                            {
                                // Hash did not match, we can't recover from this, just throw
                                throw new Exception($"Computed runner hash {hash} did not match expected Runner Hash {_targetPackage.HashValue} for {_targetPackage.Filename}");
                            }
                            Trace.Info($"Validated Runner Hash matches {_targetPackage.Filename} : {_targetPackage.HashValue}");
                        }
                    }
                }
                if (archiveFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile.ExtractToDirectory(archiveFile, latestRunnerDirectory);
                }
                else if (archiveFile.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
                {
                    string tar = WhichUtil.Which("tar", trace: Trace);

                    if (string.IsNullOrEmpty(tar))
                    {
                        throw new NotSupportedException($"tar -xzf");
                    }

                    // tar -xzf
                    using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                    {
                        processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Info(args.Data);
                            }
                        });

                        processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Error(args.Data);
                            }
                        });

                        int exitCode = await processInvoker.ExecuteAsync(latestRunnerDirectory, tar, $"-xzf \"{archiveFile}\"", null, token);
                        if (exitCode != 0)
                        {
                            throw new NotSupportedException($"Can't use 'tar -xzf' extract archive file: {archiveFile}. return code: {exitCode}.");
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException($"{archiveFile}");
                }

                Trace.Info($"Finished getting latest runner package at: {latestRunnerDirectory}.");
            }
            finally
            {
                try
                {
                    // delete .zip file
                    if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                    {
                        Trace.Verbose("Deleting latest runner package zip: {0}", archiveFile);
                        IOUtil.DeleteFile(archiveFile);
                    }
                }
                catch (Exception ex)
                {
                    //it is not critical if we fail to delete the .zip file
                    Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                }
            }

            // copy latest runner into runner root folder
            // copy bin from _work/_update -> bin.version under root
            string binVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.BinDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(binVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory)} to {binVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory), binVersionDir, token);

            // copy externals from _work/_update -> externals.version under root
            string externalsVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.ExternalsDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(externalsVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory)} to {externalsVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory), externalsVersionDir, token);

            // copy and replace all .sh/.cmd files
            Trace.Info($"Copy any remaining .sh/.cmd files into runner root.");
            foreach (FileInfo file in new DirectoryInfo(latestRunnerDirectory).GetFiles() ?? new FileInfo[0])
            {
                string destination = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), file.Name);

                // Removing the file instead of just trying to overwrite it works around permissions issues on linux.
                // https://github.com/actions/runner/issues/981
                Trace.Info($"Copy {file.FullName} to {destination}");
                IOUtil.DeleteFile(destination);
                file.CopyTo(destination, true);
            }
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static string GetSha256Hash(string path)
        {
            string hashString = path.ToLowerInvariant();
            using (SHA256 sha256hash = SHA256.Create())
            {
                byte[] data = sha256hash.ComputeHash(Encoding.UTF8.GetBytes(hashString));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                string hash = sBuilder.ToString();
                return hash;
            }
        }

19 View Source File : HashPII.cs
License : MIT License
Project Creator : Adoxio

public static byte[] ComputeHashPiiSha256(byte[] piiToBeHashed)
		{
			using (var sha256 = SHA256.Create())
			{
				return sha256.ComputeHash(piiToBeHashed);
			}
		}

19 View Source File : PinCodeHashGenerator.cs
License : Apache License 2.0
Project Creator : advanced-cms

public static string Hash(string pinCode, string token)
        {
            var value = token.Substring(0, 4) + pinCode + token.Substring(5, 4);

            var builder = new StringBuilder();

            using (var hash = SHA256.Create())
            {
                var result = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
                foreach (var b in result)
                {
                    builder.Append(b.ToString("x2"));
                }
            }

            return builder.ToString();
        }

19 View Source File : BlockExecutingService.cs
License : MIT License
Project Creator : AElfProject

private Hash CalculateWorldStateMerkleTreeRoot(BlockStateSet blockStateSet)
        {
            Logger.LogTrace("Start world state calculation.");
            Hash merkleTreeRootOfWorldState;
            var byteArrays = GetDeterministicByteArrays(blockStateSet);
            using (var hashAlgorithm = SHA256.Create())
            {
                foreach (var bytes in byteArrays)
                {
                    hashAlgorithm.TransformBlock(bytes, 0, bytes.Length, null, 0);
                }

                hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);
                merkleTreeRootOfWorldState = Hash.LoadFromByteArray(hashAlgorithm.Hash);
            }

            return merkleTreeRootOfWorldState;
        }

19 View Source File : Base58.cs
License : MIT License
Project Creator : AElfProject

private static byte[] _GetCheckSum(byte[] data)
        {
            var result = new byte[CheckSumSize];
            using (SHA256 sha256 = SHA256.Create())
            {
                var hash1 = sha256.ComputeHash(data);
                var hash2 = sha256.ComputeHash(hash1);
                Buffer.BlockCopy(hash2, 0, result, 0, result.Length);
            }

            return result;
        }

19 View Source File : ByteExtensions.cs
License : MIT License
Project Creator : AElfProject

public static byte[] ComputeHash(this byte[] bytes)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                return sha256.ComputeHash(bytes);
            }
        }

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aequabit

public static string SHA256(string input)
        {
            using (SHA256 hasher = System.Security.Cryptography.SHA256.Create())
            {
                byte[] dbytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(input));
                StringBuilder sBuilder = new StringBuilder();

                for (int n = 0; n <= dbytes.Length - 1; n++)
                {
                    sBuilder.Append(dbytes[n].ToString("X2"));
                }

                return sBuilder.ToString().ToLower();
            }
        }

19 View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static string Sha256(this string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            using (var sha = SHA256.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(value);
                var hash = sha.ComputeHash(bytes);

                return Convert.ToBase64String(hash);
            }
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static string EncryptText(string input)
        {
            // Get the bytes of the string
            byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(new NetworkCredential("", Key).Preplacedword);
            // Hash the preplacedword with SHA256
            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
            byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, preplacedwordBytes);
            string result = Convert.ToBase64String(bytesEncrypted);
            return result;
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static string DecryptText(string input)
        {
            // Get the bytes of the string
            byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(new NetworkCredential("", Key).Preplacedword);
            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
            byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, preplacedwordBytes);
            string result = Encoding.UTF8.GetString(bytesDecrypted);
            return result;
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static void EncryptFile(string inFile, string outFile)
        {
            byte[] bytesToBeEncrypted = File.ReadAllBytes(inFile);
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(new NetworkCredential("", Key).Preplacedword);
            // Hash the preplacedword with SHA256
            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
            byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, preplacedwordBytes);
            File.WriteAllBytes(outFile, bytesEncrypted);
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static void DecryptFile(string inFile, string outFile)
        {
            byte[] bytesToBeDecrypted = File.ReadAllBytes(inFile);
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(new NetworkCredential("", Key).Preplacedword);
            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
            byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, preplacedwordBytes);
            File.WriteAllBytes(outFile, bytesDecrypted);
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> CreateAsync(string preplacedword, string mnemonic, string walletName = DefaultWalletName)
        {
            if (IsCreated)
            {
                Logger.Warn("Wallet already created.");
                return true;
            }

            if (!IsValidPreplacedword(preplacedword))
            {
                Logger.Warn(
                    "Preplacedword isn't is invalid, please provide a proper preplacedword. Minmimu eight size and must have upper, lower and digits.");
                return false;
            }

            Logger.Info("Creating new wallet from mnemonic.");

            var seed = Mnemonic.GetSecretKeyFromMnemonic(mnemonic, "Substrate", BIP39Wordlist.English);

            var randomBytes = new byte[48];

            _random.NextBytes(randomBytes);

            var memoryBytes = randomBytes.AsMemory();

            var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

            var salt = memoryBytes.Slice(0, 16).ToArray();

            pswBytes = SHA256.Create().ComputeHash(pswBytes);

            var encryptedSeed =
                ManagedAes.EncryptStringToBytes_Aes(Utils.Bytes2HexString(seed, Utils.HexStringFormat.Pure), pswBytes, salt);

            var miniSecret = new MiniSecret(seed, ExpandMode.Ed25519);
            var getPair = miniSecret.GetPair();

            var keyType = KeyType.Sr25519;
            _walletFile = new WalletFile(keyType, getPair.Public.Key, encryptedSeed, salt);

            Caching.Persist(AddWalletFileType(walletName), _walletFile);

            Account = Account.Build(keyType, getPair.Secret.ToBytes(), getPair.Public.Key);

            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> CreateAsync(string preplacedword, string walletName = DefaultWalletName)
        {
            if (IsCreated)
            {
                Logger.Warn("Wallet already created.");
                return true;
            }

            if (!IsValidPreplacedword(preplacedword))
            {
                Logger.Warn(
                    "Preplacedword isn't is invalid, please provide a proper preplacedword. Minmimu eight size and must have upper, lower and digits.");
                return false;
            }

            Logger.Info("Creating new wallet.");

            var randomBytes = new byte[48];

            _random.NextBytes(randomBytes);

            var memoryBytes = randomBytes.AsMemory();

            var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

            var salt = memoryBytes.Slice(0, 16).ToArray();

            var seed = memoryBytes.Slice(16, 32).ToArray();

            pswBytes = SHA256.Create().ComputeHash(pswBytes);

            var encryptedSeed =
                ManagedAes.EncryptStringToBytes_Aes(Utils.Bytes2HexString(seed, Utils.HexStringFormat.Pure), pswBytes,
                    salt);

            Ed25519.KeyPairFromSeed(out var publicKey, out var privateKey, seed);

            var keyType = KeyType.Ed25519;
            _walletFile = new WalletFile(keyType, publicKey, encryptedSeed, salt);

            Caching.Persist(AddWalletFileType(walletName), _walletFile);

            Account = Account.Build(keyType, privateKey, publicKey);

            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> UnlockAsync(string preplacedword, bool noCheck = false)
        {
            if (IsUnlocked || !IsCreated)
            {
                Logger.Warn("Wallet is already unlocked or doesn't exist.");
                return IsUnlocked && IsCreated;
            }

            Logger.Info("Unlock new wallet.");

            try
            {
                var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

                pswBytes = SHA256.Create().ComputeHash(pswBytes);

                var seed = ManagedAes.DecryptStringFromBytes_Aes(_walletFile.EncryptedSeed, pswBytes, _walletFile.Salt);

                byte[] publicKey = null;
                byte[] privateKey = null;
                switch (_walletFile.KeyType)
                {
                    case KeyType.Ed25519:
                        Ed25519.KeyPairFromSeed(out publicKey, out privateKey, Utils.HexToByteArray(seed));
                        break;
                    case KeyType.Sr25519:
                        var miniSecret = new MiniSecret(Utils.HexToByteArray(seed), ExpandMode.Ed25519);
                        var getPair = miniSecret.GetPair();
                        privateKey = getPair.Secret.ToBytes();
                        publicKey = getPair.Public.Key;
                        break;
                }

                if (noCheck || !publicKey.SequenceEqual(_walletFile.PublicKey))
                    throw new Exception("Public key check failed!");

                Account = Account.Build(_walletFile.KeyType, privateKey, publicKey);
            }
            catch (Exception exception)
            {
                Logger.Warn($"Couldn't unlock the wallet with this preplacedword. {exception}");
                return false;
            }


            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : AddressUtils.cs
License : MIT License
Project Creator : alexanderdna

public static bool VerifyAddress(string address, bool needChecksum = true)
        {
            if (string.IsNullOrEmpty(address)) return false;

            var hash4 = Base58Check.Decode(address);
            if (hash4 == null) return false;

            if (hash4.Length != 25
                || hash4[0] != 0x32)
                return false;

            if (needChecksum)
            {
                using var sha256 = SHA256.Create();
                var hash2 = new byte[hash4.Length - 4];
                Buffer.BlockCopy(hash4, 0, hash2, 0, hash2.Length);

                var hash3 = sha256.ComputeHash(sha256.ComputeHash(hash2));
                if (hash4[21] != hash3[0]
                    || hash4[22] != hash3[1]
                    || hash4[23] != hash3[2]
                    || hash4[24] != hash3[3])
                    return false;
            }

            return true;
        }

19 View Source File : HashUtils.cs
License : MIT License
Project Creator : alexanderdna

public static string SHA256(Stream stream)
        {
            using var sha256 = Crypto.SHA256.Create();
            stream.Seek(0, SeekOrigin.Begin);
            var result = sha256.ComputeHash(stream);
            return HexUtils.HexFromByteArray(result);
        }

19 View Source File : HashUtils.cs
License : MIT License
Project Creator : alexanderdna

public static string SHA256(byte[] data)
        {
            using var sha256 = Crypto.SHA256.Create();
            var result = sha256.ComputeHash(data);
            return HexUtils.HexFromByteArray(result);
        }

19 View Source File : AddressUtils.cs
License : MIT License
Project Creator : alexanderdna

public static string AddressFromPublicKey(PublicKey publicKey)
        {
            using var ripemd160 = new DevHawk.Security.Cryptography.RIPEMD160();
            using var sha256 = SHA256.Create();

            byte[] publicKeyPlain = publicKey.toString(encoded: false);
            byte[] publicKeyCorrect = new byte[1 + publicKeyPlain.Length];
            publicKeyCorrect[0] = 0x04;
            Buffer.BlockCopy(publicKeyPlain, 0, publicKeyCorrect, 1, publicKeyPlain.Length);

            byte[] hash1 = ripemd160.ComputeHash(sha256.ComputeHash(publicKeyCorrect));

            byte[] hash2 = new byte[1 + hash1.Length];
            hash2[0] = 0x32;
            Buffer.BlockCopy(hash1, 0, hash2, 1, hash1.Length);

            byte[] hash3 = sha256.ComputeHash(sha256.ComputeHash(hash2));

            byte[] hash4 = new byte[hash2.Length + 4];
            Buffer.BlockCopy(hash2, 0, hash4, 0, hash2.Length);
            Buffer.BlockCopy(hash3, 0, hash4, hash4.Length - 4, 4);

            var sb = StringBuilderPool.Acquire();
            Base58Check.Encode(sb, hash4);
            return StringBuilderPool.GetStringAndRelease(sb);
        }

19 View Source File : Pow.cs
License : MIT License
Project Creator : alexanderdna

public static byte[] Hash(Stream stream)
        {
            using var hashAlgo = SHA256.Create();
            stream.Seek(0, SeekOrigin.Begin);
            sw.Restart();
            var hash = hashAlgo.ComputeHash(stream);
            sw.Stop();
            return hash;
        }

19 View Source File : Wallet.cs
License : MIT License
Project Creator : alexanderdna

public BigInteger? TryGetSecret(string preplacedphrase)
        {
            using var sha256 = SHA256.Create();
            var ppBytes = Encoding.UTF8.GetBytes(preplacedphrase);
            var ppHash = sha256.ComputeHash(ppBytes);
            var decryptedPayload = AesEncryptor.Decrypt(payload, ppHash);
            var decryptedChecksum = sha256.ComputeHash(decryptedPayload);
            if (equalBytes(decryptedChecksum, checksum))
                return new BigInteger(decryptedPayload);
            else
                return null;
        }

19 View Source File : SpkiFingerprint.cs
License : MIT License
Project Creator : alexrainman

public static string ComputeSHA256(byte[] certificate)
        {
            // Load ASN.1 encoded certificate structure
            var certAsn1 = Asn1Object.FromByteArray(certificate);
            var certStruct = X509CertificateStructure.GetInstance(certAsn1);

            // Extract SPKI and DER-encode it
            var spki = certStruct.SubjectPublicKeyInfo;
            var spkiDer = spki.GetDerEncoded();

            // Compute spki fingerprint (sha256)
            string spkiFingerprint;

            using (var digester = SHA256.Create())
            {
                var digest = digester.ComputeHash(spkiDer);
                spkiFingerprint = Convert.ToBase64String(digest);
            }

            return $"sha256/{spkiFingerprint}";
        }

19 View Source File : KrakenRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private byte[] sha256_hash(String value)
        {
            using (SHA256 hash = SHA256Managed.Create())
            {
                Encoding enc = Encoding.UTF8;

                Byte[] result = hash.ComputeHash(enc.GetBytes(value));

                return result;
            }
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private byte[] SHA256Hash(byte[] value)
        {
            using (var hash = SHA256.Create())
            {
                return hash.ComputeHash(value);
            }
        }

19 View Source File : AddressExtensions.cs
License : MIT License
Project Creator : allartprotocol

public static byte[] CreateProgramAddress(IList<byte[]> seeds, byte[] programId)
        {
            var buffer = new List<byte>();

            foreach (var seed in seeds)
            {
                if (seed.Length > 32)
                {
                    throw new ArgumentException("max seed length exceeded", nameof(seeds));
                }
                buffer.AddRange(seed);
            }
            
            buffer.AddRange(programId);
            buffer.AddRange(Encoding.ASCII.GetBytes("ProgramDerivedAddress"));

            var hash = SHA256.Create().Hash;// HashData(buffer.ToArray());

            if (hash.IsOnCurve() != 0)
            {
                throw new Exception("invalid seeds, address must fall off curve");
            }

            return hash;
        }

19 View Source File : ExpRoomEditor.cs
License : Apache License 2.0
Project Creator : allenai

public static string CreateSHA256Hash(string path) {
        SHA256 hasher = SHA256.Create();

        using (System.IO.FileStream fs = System.IO.File.OpenRead(path)) {
            return string.Join("", hasher.ComputeHash(fs).Select(b => b.ToString("x2")).ToArray());
        }
    }

19 View Source File : GoogleCredential.cs
License : Apache License 2.0
Project Creator : aloneguid

public string CreateSignature(byte[] data)
      {
         using(SHA256 shA256 = SHA256.Create())
            return Convert.ToBase64String(Key.SignHash(shA256.ComputeHash(data), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
      }

19 View Source File : HashHelper.cs
License : MIT License
Project Creator : AlphaYu

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();
            }
        }

19 View Source File : AuthenticationController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static string HashNonce(string nonce)
        {
            using (SHA256 nonceHash = SHA256Managed.Create())
            {
                byte[] byteArrayResultOfRawData = Encoding.UTF8.GetBytes(nonce);
                byte[] byteArrayResult = nonceHash.ComputeHash(byteArrayResultOfRawData);
                return Convert.ToBase64String(byteArrayResult);
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : AmazingDM

public static string SHA256CheckSum(string filePath)
        {
            try
            {
                var sha256 = SHA256.Create();
                var fileStream = File.OpenRead(filePath);
                return sha256.ComputeHash(fileStream).Aggregate(string.Empty, (current, b) => current + b.ToString("x2"));
            }
            catch
            {
                return "";
            }
        }

19 View Source File : Block.cs
License : MIT License
Project Creator : Amine-Smahi

public string CalculateHash()
        {
            var sha256 = SHA256.Create();

            var inputBytes = Encoding.ASCII.GetBytes($"{TimeStamp}-{PreviousHash ?? ""}-{JsonConvert.SerializeObject(Transactions)}-{Nonce}");
            var outputBytes = sha256.ComputeHash(inputBytes);

            return Convert.ToBase64String(outputBytes);
        }

19 View Source File : StorageExtensions.cs
License : MIT License
Project Creator : Aminator

public static async Task<byte[]> ComputeHashOfFileAsync(IStorageFile file)
        {
            using Stream stream = await file.OpenStreamForReadAsync();
            using SHA256 sha256 = SHA256.Create();

            return sha256.ComputeHash(stream);
        }

19 View Source File : SHA256Hasher.cs
License : MIT License
Project Creator : angusmillar

public static byte[] GetSHA256Hash(this string input)
    {  
      using (var sha256Hash = System.Security.Cryptography.SHA256.Create())
      {
        return sha256Hash.ComputeHash(Utf8EncodingSupport.GetBytes(input));        
      }
    }

19 View Source File : MD5Hepler.cs
License : Apache License 2.0
Project Creator : anjoy8

public static string Sha256(string str, string format = "x2")
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA256.Create().ComputeHash(buffer);
            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString(format));
            }
            return sb.ToString();
        }

19 View Source File : HashExtensions.cs
License : MIT License
Project Creator : Arch

public static byte[] Sha256(this string input, string encoding = "gb2312")
        {
            if (string.IsNullOrEmpty(input))
                return _empty;

            return Hash(input, SHA256.Create());
        }

19 View Source File : HashExtensions.cs
License : MIT License
Project Creator : Arch

public static byte[] Sha256(this byte[] input)
        {
            if (input == null)
            {
                return null;
            }

            using (var sha = SHA256.Create())
            {
                return sha.ComputeHash(input);
            }
        }

19 View Source File : CryptoUtil.cs
License : MIT License
Project Creator : architdate

public static SHA256 GetSHA256Provider()
        {
            return SHA256.Create();
        }

19 View Source File : RawUserStore.cs
License : GNU General Public License v3.0
Project Creator : arduosoft

public static string ComputePreplacedwordHash(string preplacedword)
        {
            using (var algorithm = SHA256.Create())
            {
                // Create the at_hash using the access token returned by CreateAccessTokenAsync.
                var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(preplacedword));
                return Convert.ToBase64String(hash);
            }
        }

19 View Source File : DefaultCrypto.cs
License : Apache License 2.0
Project Creator : aruss

public string Hash(byte[] input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            using (HashAlgorithm alg = SHA256.Create())
            {
                if (alg == null)
                {
                    //String.Format(CultureInfo.InvariantCulture, HelpersResources.Crypto_NotSupportedHashAlg, algorithm));
                    throw new InvalidOperationException();

                }

                byte[] hashData = alg.ComputeHash(input);
                return this.BinaryToHex(hashData);
            }
        }

19 View Source File : DataCalculator.cs
License : MIT License
Project Creator : aslotte

public string CalculateDataHash(IDataView dataView)
        {
            using SHA256 sha256Hash = SHA256.Create();
            using var stream = new MemoryStream();

            new MLContext().Data.SaveAsBinary(dataView, stream);
            var bytes = sha256Hash.ComputeHash(stream);
            return Convert.ToBase64String(bytes);
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private static string GetIdFromUrlPath(string path)
        {
            if (string.IsNullOrEmpty(path))
                return null;

            using (var hasher = System.Security.Cryptography.SHA256.Create())
            {
                var inputBytes = Encoding.ASCII.GetBytes(path);
                var hashBytes = hasher.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                var sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                    sb.Append(hashBytes[i].ToString("X2"));

                return sb.ToString();
            }
        }

19 View Source File : OpenidConnectAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                // order for redirect_uri
                // 1. challenge.Properties.RedirectUri
                // 2. CurrentUri
                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = CurrentUri;
                }

                // this value will be preplaceded to the AuthorizationCodeReceivedNotification
                if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
                {
                    properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
                }

                if (_configuration == null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage
                {
                    ClientId = Options.ClientId,
                    IssuerAddress = _configuration.AuthorizationEndpoint ?? string.Empty,
                    RedirectUri = Options.RedirectUri,
                    RequestType = OpenIdConnectRequestType.Authentication,
                    Resource = Options.Resource,
                    ResponseType = Options.ResponseType,
                    Scope = Options.Scope
                };

                // https://tools.ietf.org/html/rfc7636
                if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code)
                {
                    using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
                    using (HashAlgorithm hash = SHA256.Create())
                    {
                        byte[] bytes = new byte[32];
                        randomNumberGenerator.GetBytes(bytes);
                        string codeVerifier = TextEncodings.Base64Url.Encode(bytes);

                        // Store this for use during the code redemption.
                        properties.Dictionary.Add(OAuthConstants.CodeVerifierKey, codeVerifier);
                        byte[] challengeBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                        string codeChallenge = TextEncodings.Base64Url.Encode(challengeBytes);

                        openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeKey, codeChallenge);
                        openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeMethodKey, OAuthConstants.CodeChallengeMethodS256);
                    }
                }

                openIdConnectMessage.State = OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));

                // Omitting the response_mode parameter when it already corresponds to the default
                // response_mode used for the specified response_type is recommended by the specifications.
                // See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes
                if (!string.Equals(Options.ResponseType, OpenIdConnectResponseType.Code, StringComparison.Ordinal) ||
                    !string.Equals(Options.ResponseMode, OpenIdConnectResponseMode.Query, StringComparison.Ordinal))
                {
                    openIdConnectMessage.ResponseMode = Options.ResponseMode;
                }

                if (Options.ProtocolValidator.RequireNonce)
                {
                    AddNonceToMessage(openIdConnectMessage);
                }

                var notification = new RedirectToIdenreplacedyProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };

                await Options.Notifications.RedirectToIdenreplacedyProvider(notification);

                if (!notification.HandledResponse)
                {
                    string redirectUri = notification.ProtocolMessage.CreateAuthenticationRequestUrl();
                    if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                    {
                        _logger.WriteWarning("The authenticate redirect URI is malformed: " + redirectUri);
                    }
                    Response.Redirect(redirectUri);
                }
            }

            return;
        }

19 View Source File : OpenidConnectAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

protected virtual string GetNonceKey(string nonce)
        {
            if (nonce == null)
            {
                return null;
            }

            using (HashAlgorithm hash = SHA256.Create())
            {
                // computing the hash of the nonce and appending it to the cookie name
                // it is possible here that the value is NOT an int64, but this had to be because a custom nonce was created.
                return OpenIdConnectAuthenticationDefaults.CookiePrefix + OpenIdConnectAuthenticationDefaults.Nonce + Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(nonce)));
            }
        }

19 View Source File : CdnScriptTagTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [MemberData(nameof(SubresourceIntegrityCheckScriptData))]
        public async Task CheckScriptSubresourceIntegrity(ScriptTag scriptTag)
        {
            string expectedIntegrity;
            using (var responseStream = await _httpClient.GetStreamAsync(scriptTag.Src))
            using (var alg = SHA256.Create())
            {
                var hash = alg.ComputeHash(responseStream);
                expectedIntegrity = "sha256-" + Convert.ToBase64String(hash);
            }

            if (!expectedIntegrity.Equals(scriptTag.Integrity, StringComparison.OrdinalIgnoreCase))
            {
                replacedert.False(true, $"Expected {scriptTag.Src} to have Integrity '{expectedIntegrity}' but it had '{scriptTag.Integrity}'.");
            }
        }

19 View Source File : CdnScriptTagTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [MemberData(nameof(SubresourceIntegrityCheckLinkData))]
        public async Task CheckLinkSubresourceIntegrity(LinkTag linkTag)
        {
            string expectedIntegrity;
            using (var responseStream = await _httpClient.GetStreamAsync(linkTag.HRef))
            using (var alg = SHA256.Create())
            {
                var hash = alg.ComputeHash(responseStream);
                expectedIntegrity = "sha256-" + Convert.ToBase64String(hash);
            }

            if (!expectedIntegrity.Equals(linkTag.Integrity, StringComparison.OrdinalIgnoreCase))
            {
                replacedert.False(true, $"Expected {linkTag.HRef} to have Integrity '{expectedIntegrity}' but it had '{linkTag.Integrity}'.");
            }
        }

19 View Source File : Sha256.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public static byte[] Compute(byte[] input, int offset, int count)
        {
            using var sha256 = SHA256.Create();
            return sha256.ComputeHash(input, offset, count);
        }

See More Examples