shim.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  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.TextDecoder)
  13. {
  14. const { TextEncoder, TextDecoder } = require('text-encoding');
  15. api.TextDecoder = TextDecoder;
  16. api.TextEncoder = TextEncoder;
  17. }
  18. if(!api.crypto)
  19. {
  20. try
  21. {
  22. var crypto = require('crypto', 1);
  23. Object.assign(api, {
  24. crypto,
  25. random: (len) => Buffer.from(crypto.randomBytes(len))
  26. });
  27. const { Crypto: WebCrypto } = require('@peculiar/webcrypto', 1);
  28. api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
  29. }
  30. catch(e){
  31. console.log("text-encoding and peculiar/nwebcrypto may not be included by default, please add it to your package.json!");
  32. }}
  33. module.exports = api