mikrosafe
Version:
Encrypt and decrypt your LocalStorage data, simply and securely.
2 lines (1 loc) • 1.61 kB
JavaScript
()=>{var s=class{cryptoKey;salt;constructor(r,e={}){if(e.salt)if(typeof e.salt=="string"){let t=new TextEncoder;this.salt=t.encode(e.salt)}else this.salt=e.salt;else this.salt=new Uint8Array([21,35,190,124,99,84,23,67,128,56,33,71,190,222,37,85]);this.cryptoKey=this.generateKey(r)}async setItem(r,e){try{let t=JSON.stringify(e),n=await this.encrypt(t);localStorage.setItem(r,n)}catch(t){throw console.error("Failed to encrypt and store data:",t),new Error("Encryption failed")}}async getItem(r){let e=localStorage.getItem(r);if(!e)return null;try{let t=await this.decrypt(e);return JSON.parse(t)}catch(t){return console.error("Failed to decrypt data:",t),null}}removeItem(r){localStorage.removeItem(r)}clear(){localStorage.clear()}async generateKey(r){let e=new TextEncoder().encode(r),t=await window.crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits","deriveKey"]);return window.crypto.subtle.deriveKey({name:"PBKDF2",salt:this.salt,iterations:1e5,hash:"SHA-256"},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encrypt(r){let e=window.crypto.getRandomValues(new Uint8Array(12)),t=await this.cryptoKey,n=new TextEncoder().encode(r),o=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e},t,n),a=new Uint8Array(e.length+o.byteLength);return a.set(e,0),a.set(new Uint8Array(o),e.length),btoa(String.fromCharCode(...a))}async decrypt(r){let e=Uint8Array.from(atob(r),i=>i.charCodeAt(0)),t=e.slice(0,12),n=e.slice(12),o=await this.cryptoKey,a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:t},o,n);return new TextDecoder().decode(a)}};window.MikroSafe=s;})();
;(