loadencryption.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. window.crypt = {}
  2. var crypto = window.crypto || window.msCrypto;
  3. function getEntropy() {
  4. var entropy = new Uint32Array(256)
  5. crypto.getRandomValues(entropy)
  6. return entropy
  7. }
  8. function getSeed() {
  9. var seed = new Uint8Array(16)
  10. crypto.getRandomValues(seed)
  11. return seed
  12. }
  13. var worker = new Worker("./js/encryption.js")
  14. var promises = {}
  15. function str2ab(str) {
  16. var buf = new ArrayBuffer(str.length * 2);
  17. var bufView = new DataView(buf);
  18. for (var i = 0, strLen = str.length; i < strLen; i++) {
  19. bufView.setUint16(i * 2, str.charCodeAt(i), false)
  20. }
  21. return buf;
  22. }
  23. worker.onmessage = function (e) {
  24. if (e.data.type == 'progress') {
  25. promises[e.data.id].notify(e.data)
  26. } else {
  27. promises[e.data.id].resolve(e.data)
  28. delete promises[e.data.id]
  29. }
  30. }
  31. var counter = 0
  32. function getpromise() {
  33. var promise = $.Deferred()
  34. var promiseid = counter
  35. counter += 1
  36. promise.id = promiseid
  37. promises[promiseid] = promise;
  38. return promise
  39. }
  40. crypt.encrypt = function (file, name) {
  41. var extension = file.type.split('/')
  42. var header = JSON.stringify({
  43. 'mime': file.type,
  44. 'name': name ? name : (file.name ? file.name : ('Pasted ' + extension[0] + '.' + (extension[1] == 'plain' ? 'txt' : extension[1])))
  45. })
  46. var zero = new Uint8Array([0, 0]);
  47. var blob = new Blob([str2ab(header), zero, file])
  48. var promise = getpromise()
  49. var fr = new FileReader()
  50. fr.onload = function () {
  51. worker.postMessage({
  52. 'data': this.result,
  53. 'entropy': getEntropy(),
  54. 'seed': getSeed(),
  55. 'id': promise.id
  56. })
  57. }
  58. fr.readAsArrayBuffer(blob)
  59. return promise
  60. }
  61. crypt.ident = function (seed) {
  62. var promise = getpromise()
  63. worker.postMessage({
  64. 'seed': seed,
  65. 'action': 'ident',
  66. 'id': promise.id
  67. })
  68. return promise
  69. }
  70. crypt.decrypt = function (file, seed) {
  71. var promise = getpromise()
  72. var fr = new FileReader()
  73. fr.onload = function () {
  74. worker.postMessage({
  75. 'data': this.result,
  76. 'action': 'decrypt',
  77. 'seed': seed,
  78. 'id': promise.id
  79. })
  80. }
  81. //console.log ( 'crypt.decrypt' );
  82. fr.readAsArrayBuffer(file)
  83. return promise
  84. }