crypto.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var CryptoUtils = {
  2. cypher: "AES-GCM",
  3. key: null,
  4. urlSafeKey: null,
  5. initialize: function(key = null) {
  6. if(key === null) {
  7. return this.generateKey();
  8. }
  9. else {
  10. this.urlSafeKey = key;
  11. return this.importKey(this.base64ToArrayBuffer(key));
  12. }
  13. },
  14. generateKey: function() {
  15. var self = this;
  16. return window.crypto.subtle.generateKey(
  17. {
  18. name: this.cypher,
  19. length: 256,
  20. },
  21. true,
  22. ["encrypt", "decrypt"]
  23. ).then(function(k){
  24. self.key = k;
  25. return window.crypto.subtle.exportKey("raw", k)
  26. }).then(function(keydata) {
  27. console.log(keydata);
  28. self.urlSafeKey = self.arrayBufferToBase64(keydata);
  29. }).catch(function(err){
  30. console.error(err)
  31. });
  32. },
  33. encrypt: function(data) {
  34. var self = this;
  35. var iv = window.crypto.getRandomValues(new Uint8Array(12));
  36. return window.crypto.subtle.encrypt(
  37. {
  38. name: this.cypher,
  39. iv: iv,
  40. },
  41. this.key,
  42. data
  43. ).then(function(encrypted){
  44. return new Blob([iv, encrypted], {type: 'application/octet-binary'});
  45. });
  46. },
  47. decrypt: function(data) {
  48. var self = this;
  49. return window.crypto.subtle.decrypt(
  50. {
  51. name: this.cypher,
  52. iv: data.slice(0,12),
  53. },
  54. this.key,
  55. data.slice(12)
  56. );
  57. },
  58. importKey: function(key) {
  59. var self = this;
  60. return window.crypto.subtle.importKey(
  61. "raw",
  62. key,
  63. {
  64. name: self.cypher
  65. },
  66. true,
  67. ["encrypt", "decrypt"]
  68. ).then(function(k){
  69. self.key = k;
  70. });
  71. },
  72. arrayBufferToBase64: function(a) {
  73. return btoa(String.fromCharCode(...new Uint8Array(a)))
  74. },
  75. base64ToArrayBuffer: function(b) {
  76. var str = atob(b);
  77. var buf = new ArrayBuffer(str.length);
  78. var bufView = new Uint8Array(buf);
  79. for (var i=0, strLen=str.length; i<strLen; i++) {
  80. bufView[i] = str.charCodeAt(i);
  81. }
  82. return buf;
  83. }
  84. }