shim.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const SEA = require('./root')
  2. const Buffer = require('./buffer')
  3. const api = {Buffer: Buffer}
  4. var o = {};
  5. if(SEA.window){
  6. api.crypto = window.crypto || window.msCrypto;
  7. api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
  8. api.TextEncoder = window.TextEncoder;
  9. api.TextDecoder = window.TextDecoder;
  10. api.random = (len) => Buffer.from(api.crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
  11. }
  12. if(!api.crypto){try{
  13. var crypto = require('crypto', 1);
  14. const { TextEncoder, TextDecoder } = require('text-encoding', 1)
  15. Object.assign(api, {
  16. crypto,
  17. //subtle,
  18. TextEncoder,
  19. TextDecoder,
  20. random: (len) => Buffer.from(crypto.randomBytes(len))
  21. });
  22. //try{
  23. const { Crypto: WebCrypto } = require('@peculiar/webcrypto', 1);
  24. api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
  25. //}catch(e){
  26. //console.log("node-webcrypto-ossl is optionally needed for ECDH, please install if needed.");
  27. //}
  28. }catch(e){
  29. console.log("node-webcrypto-ossl and text-encoding may not be included by default, please add it to your package.json!");
  30. OSSL_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
  31. }}
  32. module.exports = api