@@ -3,6 +3,24 @@ import CryptoJS from 'crypto-js';
33
44import 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
725const shuffleCharacterAt = ( content , rNumber ) => {
826 if ( rNumber < 1 ) {
@@ -20,7 +38,7 @@ const randomNumberGenerator = () => {
2038}
2139let possibleCharactersSeed = "Abm6fixYq;rMh9sSkjaGvl@*$tOVDZRyQF:8WzonIT41K0wL3PHp7XCEecB&Jgu£2dUN5" ;
2240const 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+
3561export const encrypt = ( content , password ) => escape ( CryptoJS . AES . encrypt ( content , password ) . toString ( ) ) ;
3662
3763export const decrypt = ( content , password ) => CryptoJS . AES . decrypt ( unescape ( content ) , password ) . toString ( CryptoJS . enc . Utf8 ) ;
0 commit comments