How to generate random password?

1.1k Views Asked by At

I need to generate a random password that will be used in OpenPGP.js to encrypt something symmetrically. The user should never have to touch or see the password (everything happens behind the scenes). Thus, ideally the password would just be a number of random bytes. Unfortunately, OpenPGP.js does not support that (to my knowledge). It only supports strings as passwords.

So I need to generate a random password string. I want it to be as random as possible; excluding as few characters as possible.

How can I generate a secure random password string?

I currently have this:

String.fromCharCode.apply(null, crypto.getRandomValues(new Uint8Array(32)));

However, I'm a little worried that it might mess up UTF-16 surrogate pairs when certain random bytes appear, and that the password might get interpreted differently on other browsers depending on their Unicode implementation.

Is this solution safe to use across browsers?

3

There are 3 best solutions below

0
On BEST ANSWER

To answer my own question:

A part of my system encrypts and decrypts passwords (such as the random one in the question). When testing my solution with OpenPGP.js, the string returned from the decryption operation (after encrypting) randomly does not fully equal the original string (maybe one in ten).

This suggests that OpenPGP.js does not serialize or deserialize UTF-8 correctly (or whatever encoding it uses) when its input is incorrect. I'm guessing the strings I'm producing are invalid Unicode -- at least in Chrome.

I works when I define a limited known character set, obviously.

To sum up:

String.fromCharCode.apply(null, crypto.getRandomValues(new Uint8Array(32)));

is not safe to use.

1
On

I would easyly use something like:

function generatePass() {
  var pass = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  var passLength = (Math.random() * 15) + 5;
  
  for (var i = 0; i < passLength; i++)
    pass += possible.charAt(Math.floor(Math.random() * possible.length));

  return pass;
}

console.log(generatePass());

Das anpassen und variieren des Codes ist auch sehr leicht und läuft überall.

2
On

Here Check it out Fiddle

function CreateRandomPassword(Length, isUpperAlpha, isLowerAlpha, isNumaric ,SpecialChars)
{
  var _allowedChars = "";
  if (isUpperAlpha != false)
    _allowedChars += "ABCDEFGHJKLMNOPQRSTUVWXYZ";
  if (isLowerAlpha != false)
    _allowedChars += "abcdefghijkmnopqrstuvwxyz";
  if (isNumaric != false)
    _allowedChars += "0123456789";
  _allowedChars += SpecialChars;
  if(!Length)
    Length = 8
  var chars = "";
  allowedCharCount = _allowedChars.length;
  if(allowedCharCount == 0)
    return " ";
  for (var i = 0; i < Length; i++)
  {
    chars += _allowedChars[Math.floor(Math.random() * Math.floor(allowedCharCount))];
  }
  return chars;
}

I have developed easy function to generate password