gradio/js/browserstate/crypto.ts
Abubakar Abid fc06fe41f0
Add ability to read and write from LocalStorage (#9950)
* localstate

* add changeset

* changes

* changes

* changes

* add changeset

* changes

* add changeset

* format

* notebook

* some changes

* add changeset

* format

* fix

* changes

* fix js lint and ts

* add changeset

* fix pytest

* component demo

* rename

* rename

* notebooks

* revert

* changes

* revert

* revert

* revert

* changes

* changes

* format

* fix

* notebook

* docstring

* guide

* types

* cleanup

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
2024-11-15 12:56:36 -08:00

29 lines
886 B
TypeScript

import CryptoJS from "crypto-js";
export function encrypt(data: string, key: string): string {
const hashedKey = CryptoJS.SHA256(key).toString();
const iv = CryptoJS.lib.WordArray.random(16);
const encrypted = CryptoJS.AES.encrypt(data, hashedKey, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
const ivString = CryptoJS.enc.Base64.stringify(iv);
const cipherString = encrypted.toString();
return ivString + ":" + cipherString;
}
export function decrypt(encryptedData: string, key: string): string {
const hashedKey = CryptoJS.SHA256(key).toString();
const [ivString, cipherString] = encryptedData.split(":");
const iv = CryptoJS.enc.Base64.parse(ivString);
const decrypted = CryptoJS.AES.decrypt(cipherString, hashedKey, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}