简体   繁体   English

生成具有指定限制和规则的字符的散列算法

[英]Hashing algorithm that generates characters with specified limits and rules

I would like to have a hashing algorithm, that can generate a hash string but with alphanumeric characters but under a specified limit.我想要一个散列算法,它可以生成一个散列字符串,但带有字母数字字符,但在指定的限制之下。

For example, If I provide it some text, it should generate a string that can be used as a password for websites.例如,如果我提供一些文本,它应该生成一个可以用作网站密码的字符串。 So at least 8 characters long, must contain at least a capital letter and at least a number.所以至少 8 个字符长,必须至少包含一个大写字母和至少一个数字。

Is there any hash algorithm like this?有没有这样的哈希算法? or would I have to create a custom implementation?还是我必须创建一个自定义实现? or is it not possible at all?还是根本不可能?

I'd like to do this in javascript我想在 javascript 中执行此操作

So at least 8 characters long, must contain at least a capital letter and at least a number所以至少8个字符长,必须至少包含一个大写字母和至少一个数字

  1. Generate a random integer that determines the number of capitals, Use getRandomInt from this answer that uses sampling with rejecting.生成一个确定大写字母数量的随机整数,使用此答案中的getRandomInt ,该答案使用带有拒绝的采样。 This uses the getRandomValues to get cryptographically strong random values .这使用getRandomValues获得加密的强随机值

    let capNum = getRandomInt(1,7)

    One reserved for digits一个为数字保留

  2. Generate the number of digits.生成位数。

    let digNum = getRandomInt(1, 8-capNum)

  3. Now we have 8 - capnum - digNum amount letters ( not capitals)现在我们有8 - capnum - digNum数量字母(不是大写字母)

  4. Generate necessary random elements for each group and store all of them into a string arr .为每个组生成必要的随机元素并将它们全部存储到字符串arr中。

  5. Apply Fisher–Yates shuffle algorithm so that the order of the characters in the string shuffles.应用Fisher-Yates shuffle算法,使字符串中的字符顺序发生shuffle。

   var i = arr.length, k , temp;  
   while(--i > 0){
      k = getRandomInt(0, i);
      /swap
      temp = arr[k];
      arr[k] = arr[i];
      arr[i] = temp;
   }

I didn't say in which language you need the algorithm .我没有说你需要哪种语言的算法。

In CSharp:在 CSharp 中:

public static string Hash(string password) 
    {
        var bytes = System.Text.Encoding.UTF8.GetBytes(password);
        using var hash = System.Security.Cryptography.SHA512.Create();
        {
            var hashedInputBytes = hash.ComputeHash(bytes);

            // Convert to text
            // StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte 
            var hashedInputStringBuilder = new System.Text.StringBuilder(128);
            foreach (var b in hashedInputBytes)
                hashedInputStringBuilder.Append(b.ToString("X2"));
            return hashedInputStringBuilder.ToString();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM