3131 * Released under the Apache License, Version 2.0
3232 * see: https://github.com/dcodeIO/bcrypt.js for details
3333 */
34- module . exports = ( function ( ) {
35-
36- var crypto = require ( "crypto" ) ;
34+ ( function ( global ) {
3735
3836 /**
3937 * @type {Array.<string> }
@@ -158,7 +156,7 @@ module.exports = (function() {
158156 res . push ( rs [ off ] . charCodeAt ( 0 ) ) ;
159157 }
160158 return res ;
161- } ;
159+ } ;
162160 /**
163161 * bcrypt namespace.
164162 * @type {Object.<string,*> }
@@ -722,6 +720,26 @@ module.exports = (function() {
722720 }
723721 }
724722
723+ /**
724+ * Generates cryptographically secure random bytes.
725+ * @param {number } len Number of bytes to generate
726+ * @returns {Array.<number> }
727+ * @private
728+ */
729+ function _randomBytes ( len ) {
730+ // node.js, see: http://nodejs.org/api/crypto.html
731+ if ( typeof module !== 'undefined' && module . exports ) {
732+ var crypto = require ( "crypto" ) ;
733+ return crypto . randomBytes ( len ) ;
734+
735+ // Browser, see: http://www.w3.org/TR/WebCryptoAPI/
736+ } else {
737+ var array = new Uint32Array ( len ) ;
738+ window . crypto . getRandomValues ( array ) ;
739+ return Array . prototype . slice . call ( array ) ;
740+ }
741+ }
742+
725743 /**
726744 * Internally generates a salt.
727745 * @param {number } rounds Number of rounds to use
@@ -740,7 +758,7 @@ module.exports = (function() {
740758 salt . push ( rounds . toString ( ) ) ;
741759 salt . push ( '$' ) ;
742760 try {
743- salt . push ( base64 . encode ( crypto . randomBytes ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ;
761+ salt . push ( base64 . encode ( _randomBytes ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ;
744762 return salt . join ( '' ) ;
745763 } catch ( err ) {
746764 throw ( err ) ;
@@ -902,8 +920,18 @@ module.exports = (function() {
902920 }
903921 return hash . substring ( 0 , 29 ) ;
904922 } ;
923+
924+ // Enable module loading if available
925+ if ( typeof module != 'undefined' && module [ "exports" ] ) { // CommonJS
926+ module [ "exports" ] = bcrypt ;
927+ } else if ( typeof define != 'undefined' && define [ "amd" ] ) { // AMD
928+ define ( "bcrypt" , function ( ) { return bcrypt ; } ) ;
929+ } else { // Shim
930+ if ( ! global [ "dcodeIO" ] ) {
931+ global [ "dcodeIO" ] = { } ;
932+ }
933+ global [ "dcodeIO" ] [ "bcrypt" ] = bcrypt ;
934+ }
905935
906- return bcrypt ;
907-
908- } ) ( ) ;
936+ } ) ( this ) ;
909937
0 commit comments