AES Decrypt a file in NodeJs

Amir Saleem :

I have a JAVA code that does the AES encryption of excel file on the Windows Operating System. I want to decrypt the same file on the MacOs Operating System using NodeJS. I've written a decrypt function in NodeJs which is giving me the following error

error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

Here is the JAVA Code

import java.security.Key;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class fileEncrypter {
   try {
     final SecretKeySpec key = new SecretKeySpec("1234".getBytes(), "AES");
     final Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
     final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(name));
     final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(name2));
     instance.init(1, key);
     final byte[] b = new byte[4096];
     for (int i = bufferedInputStream.read(b); i > -1; i = bufferedInputStream.read(b)) {
        final byte[] update = instance.update(b, 0, I);
        bufferedOutputStream.write(update, 0, update.length);
     }
     bufferedInputStream.close();
     final byte[] doFinal = instance.doFinal();
     bufferedOutputStream.write(doFinal, 0, doFinal.length);
     bufferedOutputStream.flush();
     bufferedOutputStream.close();
     return "success";
   } catch(Exception obj) {
     System.err.println("Exception occured while encryption:" + obj);
     obj.printStackTrace();
     return obj.toString();
   }
}

Here is the NodeJs code to decrypt

function Decrypt_AES() {

const ALGORITHM = 'aes-128-ecb';
const ENCRYPTION_KEY = "1234";

var decipher = crypto.createDecipher(ALGORITHM, ENCRYPTION_KEY);
decipher.setAutoPadding(true);
var input = fs.createReadStream('test.enc');
var output = fs.createWriteStream('test_copy.xls');

input.pipe(decipher).pipe(output);

output.on('finish', function () {
    console.log('Encrypted file written to disk!');
});
output.on('error', function (e) {
    console.log(e);
});

}

Terry Lennox :

I've created some examples in both Java and Node.js that will encrypt and decrypt files. The code will be compatible as long as the same key and IV values are used, that is to say the Node code will decrypt the output from the Java and vice-versa.

Now I'm using text files as input here, but you can use any file type as input.

I've updated to use 128-bit AES in ECB mode.

The Key cannot be "1234" since it must be 128-bits long, so I've used the key given below (16 bytes / 128 bits).

Java

import java.io.*;
import javax.crypto.*;
import java.security.*;
import javax.crypto.spec.*;

public class fileEncrypter {

  private static final String key = "0123456789ABDCEF";

  public static void main(String[] args)
  {
      encryptFile(key, "java-input.txt", "java-output.txt");
      decryptFile(key, "java-output.txt", "java-decrypted.txt");
  }

  public static void encryptFile(String secret, String inputFile, String outputFile) 
  {
      try 
      {
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
          cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));

          byte[] inputData = readFile(inputFile);
          byte[] outputData = cipher.doFinal(inputData);
          writeToFile(outputFile, outputData);  
      } 
      catch (Exception e) 
      {
          System.out.println("Error while encrypting: " + e.toString());
      }
  }

  public static void decryptFile(String secret, String inputFile, String outputFile) 
    {
        try 
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));

            byte[] inputData = readFile(inputFile);
            byte[] outputData = cipher.doFinal(inputData);
            writeToFile(outputFile, outputData);  
        } 
        catch (Exception e) 
        {
            System.out.println("Error while decrypting: " + e.toString());
        }
    }

    private static byte[] readFile(String fileName) throws IOException {
        byte[] data = new byte[(int) new File(fileName).length()];
        DataInputStream dis = new DataInputStream(new FileInputStream(fileName));
        dis.readFully(data);
        dis.close();
        return data;
    }

    private static void writeToFile(String fileName, byte[] data) throws IOException {
        final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));
        bufferedOutputStream.write(data, 0, data.length);
        bufferedOutputStream.close();
    }
}

Node.js

const crypto = require("crypto");
const Algorithm = "aes-128-ecb";
const fs = require("fs");

function encryptFile(key, inputFile, outputFile) {
    const inputData = fs.readFileSync(inputFile);
    const cipher = crypto.createCipheriv(Algorithm, key, Buffer.alloc(0));
    const output = Buffer.concat([cipher.update(inputData) , cipher.final()]);
    fs.writeFileSync(outputFile, output);
}

function decryptFile(key, inputFile, outputFile) {
    const inputData = fs.readFileSync(inputFile);
    const cipher = crypto.createDecipheriv(Algorithm, key, Buffer.alloc(0));
    const output = Buffer.concat([cipher.update(inputData) , cipher.final()]);
    fs.writeFileSync(outputFile, output);
}

const KEY = Buffer.from("0123456789ABDCEF", "utf8");

encryptFile(KEY, "node-input.txt", "node-output.txt");
decryptFile(KEY, "node-output.txt", "node-decrypted.txt");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374622&siteId=1