Skip to content

Instantly share code, notes, and snippets.

@timeturnback
Created July 29, 2023 13:52
Show Gist options
  • Save timeturnback/f171c37591a42a8a7570357695a70632 to your computer and use it in GitHub Desktop.
Save timeturnback/f171c37591a42a8a7570357695a70632 to your computer and use it in GitHub Desktop.
AES CFB 256 encrypt and decrypt text
import CryptoJS from 'crypto-js';
export function encryptText(keyStr, text) {
const private_key = CryptoJS.SHA256(keyStr).toString(CryptoJS.enc.Latin1);
const rem = text.length % 16;
const padded = CryptoJS.enc.Latin1.parse(text.padEnd(text.length + (16 - rem), '\0'));
const iv = CryptoJS.lib.WordArray.random(16);
const cipher = CryptoJS.AES.encrypt(padded, CryptoJS.enc.Latin1.parse(private_key), {
iv: iv,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding,
segmentSize: 128,
});
const ciphertext = iv.concat(cipher.ciphertext);
return ciphertext.toString(CryptoJS.enc.Base64);
}
export const decryptText = (keyStr, text) => {
const private_key = CryptoJS.SHA256(keyStr).toString(CryptoJS.enc.Latin1);
const encrypted = CryptoJS.enc.Base64.parse(text);
const iv = encrypted.clone().words.slice(0, 4);
const ciphertext = encrypted.clone().words.slice(4);
const cipherParams = {
ciphertext: CryptoJS.lib.WordArray.create(ciphertext),
};
const decrypted = CryptoJS.AES.decrypt(cipherParams, CryptoJS.enc.Latin1.parse(private_key), {
iv: CryptoJS.lib.WordArray.create(iv),
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.ZeroPadding,
segmentSize: 128,
});
const decryptedText = CryptoJS.enc.Utf8.stringify(decrypted);
return decryptedText;
};
@timeturnback
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment