Search code examples
reactjstypescriptcryptojs

Crypto-JS on typescript: Type 'string' is not assignable to type 'WordArray'. ts(2322)


I keep encountering a problem when using Crypto-JS with Typescript. The error is that Type 'string' is not assignable to type 'WordArray'. ts(2322) on the iv. Here's my code

encryption.tsx

import { FC } from "react";
import CryptoJS, { AES } from "crypto-js";

const Encryption: FC = () => {
  const application = {
    key: "key",
    iv: "iv"
  };

  const encrypt = (data: string) =>
    AES.encrypt(data, application.key, {
      iv: application.iv, // here's the error
    }).toString();

  const decrypt = (data: string) =>
    AES.decrypt(data, application.key, { iv: application.iv }).toString(
      CryptoJS.enc.Utf8
    );

  useEffect(()=>{
     const data = "hi";
     console.log({encrypted: encrypt(data), decrypted: decrypt(encrypt(data))});
  },[]);

  return <></>;
}

Solution

  • It's expecting for iv to have a specific format.

    For example CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");