shim.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const Buffer = require('./buffer')
  2. const api = {Buffer: Buffer}
  3. if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
  4. var crypto = window.crypto || window.msCrypto;
  5. var subtle = crypto.subtle || crypto.webkitSubtle;
  6. const TextEncoder = window.TextEncoder
  7. const TextDecoder = window.TextDecoder
  8. Object.assign(api, {
  9. crypto,
  10. subtle,
  11. TextEncoder,
  12. TextDecoder,
  13. random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
  14. })
  15. } else {
  16. try{
  17. var crypto = require('crypto');
  18. const { subtle } = require('@trust/webcrypto') // All but ECDH
  19. const { TextEncoder, TextDecoder } = require('text-encoding')
  20. Object.assign(api, {
  21. crypto,
  22. subtle,
  23. TextEncoder,
  24. TextDecoder,
  25. random: (len) => Buffer.from(crypto.randomBytes(len))
  26. });
  27. //try{
  28. const WebCrypto = require('node-webcrypto-ossl')
  29. api.ossl = new WebCrypto({directory: 'ossl'}).subtle // ECDH
  30. //}catch(e){
  31. //console.log("node-webcrypto-ossl is optionally needed for ECDH, please install if needed.");
  32. //}
  33. }catch(e){
  34. console.log("@trust/webcrypto and text-encoding are not included by default, you must add it to your package.json!");
  35. console.log("node-webcrypto-ossl is temporarily needed for ECDSA signature verification, and optionally needed for ECDH, please install if needed (currently necessary so add them to your package.json for now).");
  36. TRUST_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
  37. }
  38. }
  39. module.exports = api