【问题标题】:C#: How to hash a string into RIPEMD160C#:如何将字符串散列到 RIPEMD160
【发布时间】:2017-02-07 13:04:20
【问题描述】:

例如密码是“Hello World”,我怎样才能让它返回一个RIPEMD160 Hash String?它应该返回一个字符串:“a830d7beb04eb7549ce990fb7dc962e499a27230”。我已经在互联网上搜索了我的问题的答案,但代码不是字符串,而是关于将文件加密到 RIPEMD160。

【问题讨论】:

    标签: c# security hash


    【解决方案1】:

    好的,我已经知道问题的解决方案。将字符串转换为字节,将其传递给 RIPEMD160 函数,创建 StringBuilder 并传递 RIPEMD160 函数的返回字节,将返回的 StringBuilder 转换为字符串并再次将其转换为小写。我为它创建了一个函数。这是我的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Security.Cryptography;
    
    namespace Password
    {
        class Program
        {
            static void Main(string[] args)
            {
                string thePassword = "Hello World";
                string theHash = getHash(thePassword);
                Console.WriteLine("String: " + thePassword);
                Console.WriteLine("Encrypted Hash: " + theHash);
                Console.ReadKey(true);
            }
    
            static string getHash(string password)
            {
                // create a ripemd160 object
                RIPEMD160 r160 = RIPEMD160Managed.Create();
                // convert the string to byte
                byte[] myByte = System.Text.Encoding.ASCII.GetBytes(password);
                // compute the byte to RIPEMD160 hash
                byte[] encrypted = r160.ComputeHash(myByte);
                // create a new StringBuilder process the hash byte
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < encrypted.Length; i++)
                {
                    sb.Append(encrypted[i].ToString("X2"));
                }
                // convert the StringBuilder to String and convert it to lower case and return it.
                return sb.ToString().ToLower();
            }
        }
    }
    

    【讨论】:

    • 如果使用ToString("x2"),则无需转为小写。
    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 2018-12-30
    • 2011-02-01
    • 2020-07-14
    • 2021-01-08
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多