@@ -48,22 +48,14 @@ const bitsWithPowers = (tPower, rPower) => {
4848}
4949
5050const randomString = ( bits , charSet ) => {
51- if ( ! CharSet . isValid ( charSet ) ) { throw new Error ( 'Invalid CharSet' ) }
52-
53- const count = Math . ceil ( bits / charSet . entropyPerChar )
54- if ( count <= 0 ) { return '' }
55-
56- const bytes = randomBytes ( count , charSet )
57-
51+ const bytes = cryptoBytes ( bits , charSet )
5852 return randomStringWithBytes ( bits , charSet , bytes )
5953}
6054
6155const randomStringWithBytes = ( bits , charSet , bytes ) => {
6256 if ( ! CharSet . isValid ( charSet ) ) {
63- console . log ( 'WTF?' )
6457 throw new Error ( 'Invalid CharSet' )
6558 }
66-
6759 if ( bits <= 0 ) { return '' }
6860
6961 const count = Math . ceil ( bits / charSet . entropyPerChar )
@@ -121,10 +113,17 @@ const randomStringWithBytes = (bits, charSet, bytes) => {
121113 return string
122114}
123115
124- const randomBytes = ( count , charSet ) => {
116+ const bytesNeeded = ( entropy , charSet ) => {
117+ if ( ! CharSet . isValid ( charSet ) ) { throw new Error ( 'Invalid CharSet' ) }
118+ const count = Math . ceil ( entropy / charSet . entropyPerChar )
119+ if ( count <= 0 ) { return 0 }
120+
125121 const bytesPerSlice = charSet . entropyPerChar / 8
126- const bytesNeeded = Math . ceil ( count * bytesPerSlice )
127- return Buffer . from ( crypto . randomBytes ( bytesNeeded ) )
122+ return Math . ceil ( count * bytesPerSlice )
123+ }
124+
125+ const cryptoBytes = ( entropy , charSet ) => {
126+ return Buffer . from ( crypto . randomBytes ( bytesNeeded ( entropy , charSet ) ) )
128127}
129128
130129const ndx64 = ( chunk , slice , bytes ) => {
@@ -178,6 +177,7 @@ export default {
178177 bitsWithPowers : bitsWithPowers ,
179178 randomString : randomString ,
180179 randomStringWithBytes : randomStringWithBytes ,
180+ bytesNeeded : bytesNeeded ,
181181
182182 charSet64 : CharSet . charSet64 ,
183183 charSet32 : CharSet . charSet32 ,
0 commit comments