decide.nolog.cz/app/utils/generate-passphrase.js

37 lines
1.2 KiB
JavaScript
Raw Normal View History

/*
* generates a passphrase
2016-01-28 23:48:14 +01:00
*
* uses window.crypto.getRandomValues() if it's supported by current browsers
* otherwise uses a fallback to Math.floor() which is not cryptographically strong
2016-01-28 23:48:14 +01:00
*
* implementation by Aaron Toponce:
* https://pthree.org/2014/06/25/cryptographically-secure-passphrases-in-d-note/
*/
export default function (length) {
2016-01-28 23:48:14 +01:00
let passphrase = '';
const possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
2016-01-28 23:48:14 +01:00
const randomArray = new Uint32Array(length);
2015-07-07 11:52:46 +02:00
// Make some attempt at preferring a strong CSPRNG first
if (window.crypto && window.crypto.getRandomValues) {
// Desktop Chrome 11.0, Firefox 21.0, Opera 15.0, Safari 3.1
// Mobile Chrome 23, Firefox 21.0, iOS 6
2016-01-28 23:48:14 +01:00
window.crypto.getRandomValues(randomArray);
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
2015-07-07 11:52:46 +02:00
// IE 11
2016-01-28 23:48:14 +01:00
window.msCrypto.getRandomValues(randomArray);
} else {
2015-07-07 11:52:46 +02:00
// Android browser, IE Mobile, Opera Mobile, older desktop browsers
for (let i = length; i--; ) {
2016-01-28 23:48:14 +01:00
randomArray[i] = Math.floor(Math.random() * Math.pow(2, 32));
}
2015-07-07 11:52:46 +02:00
}
for (let j = length; j--; ) {
2016-01-28 23:48:14 +01:00
passphrase += possible.charAt(Math.floor(randomArray[j] % possible.length));
2015-07-07 11:52:46 +02:00
}
2016-01-28 23:48:14 +01:00
return passphrase;
2015-07-07 11:52:46 +02:00
}