cryptoUtils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {Buffer} from 'safe-buffer';
  2. //не менять
  3. const iv = Buffer.from('B6E2XejNh2dS');
  4. let aesKeys = {};
  5. export async function aesKeyFromPassword(password) {
  6. return await window.crypto.subtle.importKey(
  7. "raw", //only "raw" is allowed
  8. Buffer.from(password), //your password
  9. {
  10. name: "PBKDF2",
  11. },
  12. false, //whether the key is extractable (i.e. can be used in exportKey)
  13. ["deriveKey"] //can be any combination of "deriveKey" and "deriveBits"
  14. ).then((key) => {
  15. return window.crypto.subtle.deriveKey(
  16. {
  17. "name": "PBKDF2",
  18. salt: Buffer.from('Liberama project is awesome'),//не менять
  19. iterations: 1000,
  20. hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
  21. },
  22. key, //your key from generateKey or importKey
  23. { //the key type you want to create based on the derived bits
  24. name: "AES-GCM", //can be any AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH", or "HMAC")
  25. //the generateKey parameters for that type of algorithm
  26. length: 256, //can be 128, 192, or 256
  27. },
  28. false, //whether the derived key is extractable (i.e. can be used in exportKey)
  29. ["encrypt", "decrypt"] //limited to the options in that algorithm's importKey
  30. );
  31. });
  32. }
  33. export async function aesEncrypt(data, password) {
  34. if (!aesKeys[password])
  35. aesKeys[password] = await aesKeyFromPassword(password);
  36. const key = aesKeys[password];
  37. return await window.crypto.subtle.encrypt(
  38. {
  39. name: "AES-GCM",
  40. iv
  41. },
  42. key, //from generateKey or importKey above
  43. data //ArrayBuffer of data you want to encrypt
  44. );
  45. }
  46. export async function aesDecrypt(data, password) {
  47. if (!aesKeys[password])
  48. aesKeys[password] = await aesKeyFromPassword(password);
  49. const key = aesKeys[password];
  50. return await window.crypto.subtle.decrypt(
  51. {
  52. name: "AES-GCM",
  53. iv
  54. },
  55. key, //from generateKey or importKey above
  56. data //ArrayBuffer of the data
  57. );
  58. }
  59. export async function sha256(data) {
  60. return await crypto.subtle.digest("SHA-256", Buffer.from(data));
  61. }