Search code examples
node.jscryptojs

migrate createCipher et createCipheriv


I just moved to node 12.13 and I have some issue with crypto.createDecipher and crypto.createCipher

First I have deprecation warnings when I am using the two functions.

const encodeString = (value, password) =>
  new Promise((resolve, reject) => {
    const cipher = crypto.createCipher("aes192", password);
    let encrypted = "";
    cipher.on("readable", () => {
      const data = cipher.read();
      if (data) encrypted += data.toString("hex");
    });
    cipher.on("end", () => resolve(encrypted));

    cipher.write(value);
    cipher.end();
  });

const decodeString = (encrypted, password) =>
  new Promise((resolve, reject) => {
    const decipher = crypto.createDecipher("aes192", password);
    let decrypted = "";
    decipher.on("readable", () => {
      const data = decipher.read();
      if (data) decrypted += data.toString("utf8");
    });
    decipher.on("end", () => resolve(decrypted));

    decipher.write(encrypted, "hex");
    decipher.end();
  });

data()
  .then(data => {
    console.log("final", data);
  })
  .catch(err => {
    console.log("final err", err);
  });

I am looking for a way to migrate to createCipheriv and createDecipheriv but I can not find how to convert my password into key and iv


Solution

  • find below way to generate key and IV & methods for implementations

    const keyBytes: Buffer = Buffer.from(password, 'base64');
      // Generates 16 byte cryptographically strong pseudo-random data as IV
      // https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
      const ivBytes: Buffer = crypto.randomBytes(16);
      const ivText: string = ivBytes.toString('base64');     
    

    encrypt

    export function encryptString(plainText: string, secret: string): string {
        if (!plainText || plainText.length === 0) {
            return plainText;
        }
        if (!secret || secret.length === 0) {
            throw new Error('you must pass a secret');
        }
        const keyBytes: Buffer = Buffer.from(secret, 'base64');
        // Generates 16 byte cryptographically strong pseudo-random data as IV
        // https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
        const ivBytes: Buffer = crypto.randomBytes(16);
        const ivText: string = ivBytes.toString('base64');
        // encrypt using aes256 iv + key + plainText = encryptedText
        const cipher: crypto.Cipher = crypto.createCipheriv('aes-256-cbc', keyBytes, ivBytes);
        let encryptedValue: string = cipher.update(plainText, 'utf8', 'base64');
        encryptedValue += cipher.final('base64');
        // store base64(ivBytes)!base64(encryptedValue)
        return `${ ivText }!${ encryptedValue }`;
    }
    

    decrypt

        export function decryptString(encryptedValue: string, secret: string):string {
    
            if (!encryptedValue || encryptedValue.length === 0) {
            return encryptedValue;
          }
    
        if (!secret || secret.length === 0) {
            throw new Error('you must pass a secret');
        }
    
         const parts: string[] = encryptedValue.split('!');
        if (parts.length !== 2) {
            throw new Error('The encrypted value is not a valid format');
        }
        const ivText: string = parts[0];
        const encryptedText: string = parts[1];
        const ivBytes: Buffer = Buffer.from(ivText, 'base64');
        const keyBytes: Buffer = Buffer.from(secret, 'base64');
    
        if (ivBytes.length !== 16) {
            throw new Error('The encrypted value is not a valid format');
        }
    
        if (keyBytes.length !== 32) {
            throw new Error('The secret is not valid format');
        }
    
        // decrypt using aes256 iv + key + encryptedText = decryptedText
        const decipher: crypto.Decipher = crypto.createDecipheriv('aes-256-cbc', keyBytes, ivBytes);
        let value: string = decipher.update(encryptedText, 'base64', 'utf8');
        value += decipher.final('utf8');    
        return value;}