Skip to content

Commit

Permalink
Added more secure crypto random algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Ziga committed May 31, 2021
1 parent ad5ad67 commit 50039ee
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
16 changes: 16 additions & 0 deletions js/default-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,22 @@ function isPasswordPasswordValid(password){
return true;
}

function randRange(min, max) {
var range = max - min;
var requestBytes = Math.ceil(Math.log2(range) / 8);
if (!requestBytes) return min;

var maxNum = Math.pow(256, requestBytes);
var ar = new Uint8Array(requestBytes);

while (true) {
window.crypto.getRandomValues(ar);
var val = 0;
for (var i = 0;i < requestBytes;i++) val = (val << 8) + ar[i];
if (val < maxNum - maxNum % range) return min + (val % range);
}
}

function refreshPasswords(){
var xhr = new XMLHttpRequest();
xhr.open("POST", localStorage.url + "/?action=getPasswords");
Expand Down
10 changes: 5 additions & 5 deletions js/passwords.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,28 +106,28 @@ function updateGeneratedPassword(upper, number, special){
let numbers = "1234567890";
let specials = "!@#$%?&*";

for (let i = 0; i < length; i++) password += lowers.charAt(Math.floor(Math.random() * lowers.length));
for (let i = 0; i < length; i++) password += lowers.charAt(randRange(0, lowers.length));

password = password.split("");

if(upper){
let upper_amount = Math.floor(length / 2 - Math.random() * (length / 2) + 1);
for(let i = 0; i < upper_amount; i++){
password[Math.floor(Math.random() * password.length)] = uppers.charAt(Math.floor(Math.random() * uppers.length));
password[randRange(0, password.length)] = uppers.charAt(randRange(0, uppers.length));
}
}

if(number){
let number_amount = Math.floor(length / 2 - Math.random() * (length / 2) + 1);
for(let i = 0; i < number_amount; i++){
password[Math.floor(Math.random() * password.length)] = numbers.charAt(Math.floor(Math.random() * numbers.length));
password[randRange(0, password.length)] = numbers.charAt(randRange(0, numbers.length));
}
}

if(special){
let special_amount = Math.floor(Math.random(3) + 1);
let special_amount = randRange(1, 3);
for(let i = 0; i < special_amount; i++){
password[Math.floor(Math.random() * password.length)] = specials.charAt(Math.floor(Math.random() * specials.length));
password[randRange(0, password.length)] = specials.charAt(randRange(0, specials.length));
}
}

Expand Down

0 comments on commit 50039ee

Please sign in to comment.