JSFiddle - React, Tailwind, and code Playground

by Bacher

JavaScript 1.7

const encryptText = async (plainText, password) => {
  const ptUtf8 = new TextEncoder().encode(plainText);

  const pwUtf8 = new TextEncoder().encode(password);
  const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); 

  const iv = crypto.getRandomValues(new Uint8Array(12));
  const alg = { name: 'AES-GCM', iv: iv };
  const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt', 'decrypt']);

  const data = { iv, encBuffer: await crypto.subtle.encrypt(alg, key, ptUtf8) };
  
  console.log(data);
  
	const res = await crypto.subtle.decrypt(alg, key, data.encBuffer);
  console.log('res:', new TextDecoder().decode(res, { encoding: 'utf-8' }));
}

encryptText('hello world', '123');