Home > front end >  Hashing algorithm that generates characters with specified limits and rules
Hashing algorithm that generates characters with specified limits and rules

Time:05-20

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.

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

CodePudding user response:

So at least 8 characters long, must contain at least a capital letter and at least a number

  1. Generate a random integer that determines the number of capitals, Use getRandomInt from this answer that uses sampling with rejecting. This uses the getRandomValues to get cryptographically strong random values.

    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)

  4. Generate necessary random elements for each group and store all of them into a string arr.

  5. Apply Fisher–Yates shuffle algorithm so that the order of the characters in the string shuffles.

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

CodePudding user response:

I didn't say in which language you need the algorithm .

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