From 73d0385722ba679543e9503c608438152bd9b1ce Mon Sep 17 00:00:00 2001
From: Thomas Champagne
Date: Tue, 23 Jan 2024 19:16:59 +0100
Subject: [PATCH] Update sample
---
.vscode/settings.json | 1 -
src/index.ts | 17 +++++++++++++----
test/index.test.ts | 2 +-
3 files changed, 14 insertions(+), 6 deletions(-)
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 63e3340..1bfc81d 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -10,7 +10,6 @@
"typescript",
"typescriptreact",
"html",
- "json",
"yaml"
]
}
\ No newline at end of file
diff --git a/src/index.ts b/src/index.ts
index 0008c58..4d2e21c 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,3 +1,5 @@
+import crypto from 'crypto';
+
/**
* @author Thomas Champagne
* @description Password generator used as demo for the purpose of this starter library
@@ -7,16 +9,23 @@ export class Sesame {
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*{}(),.;:/<>?|_-+=';
/**
- * Create a password according length parameter
+ * Create a password according to the length parameter
*
* @param length the length of the password to be created.
* @returns password created
*/
public static create(length: number): string {
const availableChars = Sesame.AVAILABLE_CHARS;
- const randomChars = Array.from({ length }, () =>
- availableChars.charAt(Math.floor(Math.random() * availableChars.length))
- );
+ const randomChars = new Array(length);
+ const cryptoArray = new Uint32Array(length);
+
+ crypto.getRandomValues(cryptoArray);
+
+ for (let i = 0; i < length; i++) {
+ const randomIndex = cryptoArray[i] % availableChars.length;
+ randomChars[i] = availableChars.charAt(randomIndex);
+ }
+
return randomChars.join('');
}
}
diff --git a/test/index.test.ts b/test/index.test.ts
index 2968eed..5436e74 100644
--- a/test/index.test.ts
+++ b/test/index.test.ts
@@ -4,7 +4,7 @@ import { Sesame } from '../src';
describe('Sesame', () => {
it('should create and assert password length', () => {
// Given
- const expectedLength = 24;
+ const expectedLength = 64;
// When
const password = Sesame.create(expectedLength);