簡體   English   中英

如何生成隨機密碼?

[英]How to generate random password?

我需要生成一個隨機密碼,該密碼將在 OpenPGP.js 中用於對稱加密。 用戶永遠不必觸摸或看到密碼(一切都發生在幕后)。 因此,理想情況下,密碼只是一些隨機字節。 不幸的是,OpenPGP.js 不支持(據我所知)。 它只支持字符串作為密碼。

所以我需要生成一個隨機密碼字符串。 我希望它盡可能隨機; 排除盡可能少的字符。

如何生成安全的隨機密碼字符串?

我目前有這個:

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

但是,我有點擔心當某些隨機字節出現時它可能會弄亂 UTF-16 代理對,並且密碼可能會在其他瀏覽器上根據它們的 Unicode 實現而得到不同的解釋。

此解決方案是否可以安全地跨瀏覽器使用?

我會很容易地使用類似的東西:

 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。

在這里檢查一下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;
}

我開發了簡單的功能來生成密碼

回答我自己的問題:

我的系統的一部分加密和解密密碼(例如問題中的隨機密碼)。 在使用 OpenPGP.js 測試我的解決方案時,從解密操作(加密后)隨機返回的字符串不完全等於原始字符串(可能是十分之一)。

這表明 OpenPGP.js 在輸入不正確時不會正確序列化或反序列化 UTF-8(或它使用的任何編碼)。 我猜我生成的字符串是無效的 Unicode——至少在 Chrome 中是這樣。

顯然,我在定義有限的已知字符集時工作。

總結:

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

使用不安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM