0

I encrypted a file stream using aes-256-cfb in node.js and read it back in java with AES/CFB8/NoPadding, but this gets corrupted data.

node.js

const aes = crypto.createCipher('aes-256-cfb', '1234567812345678');
aes.setAutoPadding(false);
//const aesd = crypto.createDecipher('aes-256-cfb', password);  If i decrypt //with this in node.js, i am able to get back the data.  just for a test
var readStream = fs.createReadStream('c:\\test\\orig.txt');
var wstream = fs.createWriteStream('c:\\test\\encrypted.txt');

  readStream 
    .pipe(cipher)  // encrypts with aes256
    .pipe(wstream) 

    .on('finish', function () {  // finished
        console.log('done writing encrypted file');
    });

java:

InputStream in = new FileInputStream(new File("c:\\test\\encrypted.txt"));
OutputStream out = new FileOuputStream("c:\\test\\decrypted.txt");
Cipher dcipher = Cipher.getInstance("AES/CFB8/NoPadding");
Key skeySpec = new SecretKeySpec("1234567812345678".getBytes(), "AES");

    byte[] ivd = new byte[dcipher.getBlockSize()];

    IvParameterSpec ivParams = new IvParameterSpec(ivd);

    dcipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParams);

    in = new CipherInputStream(in, dcipher);
    int numRead = 0;
    while ((numRead = in.read(buf)) >= 0) {
        out.write(buf, 0, numRead);
    }
    out.close();

any idea?

Sathish Kumar
  • 313
  • 2
  • 15
  • 2
    https://stackoverflow.com/a/30394775/1759845 – BackSlash Apr 30 '19 at 07:05
  • sorry, i tried these links before, doesn't work.. can you spot whats wrong with the code i posted? – Sathish Kumar Apr 30 '19 at 18:31
  • Need help with this badly.. – Sathish Kumar May 02 '19 at 18:33
  • 1
    There is huuuge difference between `crypto.createCipher` (and `createDecipher`) as you've used, and `crypto.create{Cipher,Decipher}iv` as in the linked Q; see [the doc](https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options). If you change node to the `iv` version and use a correct length key (32 bytes not 16), and specify `CFB128` or just `CFB` but NOT `CFB8` in Java, it should work as per the other Q. But note hardcoded=fixed IV is insecure and suitable only for test; for real use choose it randomly for each encryption and include with the ciphertext. ... – dave_thompson_085 May 02 '19 at 23:29
  • 1
    ... If you really need to match in Java the non-iv version of node crypto, that won't fit in comments, but there are quite a few other Qs about it already; start with https://stackoverflow.com/questions/33391533/ https://stackoverflow.com/questions/48510385/ https://stackoverflow.com/questions/48047155/ – dave_thompson_085 May 02 '19 at 23:31
  • Thanks @dave_thompson_085, it worked well with iv version! – Sathish Kumar May 06 '19 at 03:06

0 Answers0