Skip to content

Commit abca85d

Browse files
committed
web-crypto-api
1 parent a380d12 commit abca85d

File tree

3 files changed

+77
-9
lines changed

3 files changed

+77
-9
lines changed

package-lock.json

Lines changed: 49 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
"homepage": "https://github.com/global-input/global-input-message#readme",
3636
"dependencies": {
3737
"axios": "^0.25.0",
38-
"crypto-js": "^4.0.0",
38+
"crypto-js": "^4.2.0",
3939
"socket.io-client": "^2.3.1"
4040
},
4141
"devDependencies": {

src/codedataUtil.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,24 @@ import CryptoJS from 'crypto-js';
33

44
import axios from 'axios';
55

6+
function isWebCryptoAvailable() {
7+
return typeof window !== 'undefined' && window.crypto && window.crypto.subtle;
8+
}
9+
10+
function generateRandomStringWebCrypto(length = 10) {
11+
const array = new Uint8Array(length);
12+
window.crypto.getRandomValues(array);
13+
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
14+
const charactersLength = characters.length;
15+
let result = '';
16+
for (let i = 0; i < length; i++) {
17+
// Map the random byte to a character index
18+
const randomIndex = array[i] % charactersLength;
19+
result += characters.charAt(randomIndex);
20+
}
21+
return result;
22+
}
23+
624

725
const shuffleCharacterAt = (content, rNumber) => {
826
if (rNumber < 1) {
@@ -20,7 +38,7 @@ const randomNumberGenerator = () => {
2038
}
2139
let possibleCharactersSeed = "Abm6fixYq;rMh9sSkjaGvl@*$tOVDZRyQF:8WzonIT41K0wL3PHp7XCEecB&Jgu£2dUN5";
2240
const startUpTime = new Date().getMilliseconds();
23-
export const generateRandomString = (length = 10) => {
41+
export const generateRandomStringCryptoJS = (length = 10) => {
2442
let result = '';
2543
for (let loop = 0; loop < length; loop++) {
2644
possibleCharactersSeed = shuffleCharacterAt(possibleCharactersSeed, Math.random() * possibleCharactersSeed.length); //reshuffle with browser random
@@ -32,6 +50,14 @@ export const generateRandomString = (length = 10) => {
3250
}
3351
return result;
3452
};
53+
export function generateRandomString(length = 10) {
54+
if (isWebCryptoAvailable()) {
55+
return generateRandomStringWebCrypto(length);
56+
} else {
57+
return generateRandomStringCryptoJS(length);
58+
}
59+
}
60+
3561
export const encrypt = (content, password) => escape(CryptoJS.AES.encrypt(content, password).toString());
3662

3763
export const decrypt = (content, password) => CryptoJS.AES.decrypt(unescape(content), password).toString(CryptoJS.enc.Utf8);

0 commit comments

Comments
 (0)