0

I need to cypher a textual payload, save it somewhere and after a while read it and decypher it again.

I started with some code and I noticed that there is an inconsistent behavior when I tell nodejs standard cypher to give me the output in base64. Some characters at the end of the result are missing. Changing the output encoding solve completely the problem. See the example.

import crypto from 'crypto'

const key = 'base64:Zm9vYmFy'

const payload = 'the cat is on the table'

const cypher = crypto.createCipheriv('RC4', key, null)
const decipher = crypto.createDecipheriv('RC4', key, null)

// Missing characters on result
const cypheredPayload = cypher.update(payload, 'ascii', 'base64')
const decipheredPayload = decipher.update(cypheredPayload, 'base64', 'ascii')

// All works fine
//const cypheredPayload = cypher.update(payload, 'ascii', 'ascii')
//const decipheredPayload = decipher.update(cypheredPayload, 'ascii', 'ascii')

console.log(decipheredPayload)

The result when I choose the output as base64 is the cat is on the tab (the last two characters are missing), if I switch to the version with the ascii output there is no problem.

What's happening here?

jps
  • 20,041
  • 15
  • 75
  • 79
Elia
  • 1,417
  • 1
  • 18
  • 28
  • 1
    The two `final()` calls that finalize encryption and decryption are missing (s. e.g. [here](https://nodejs.org/api/crypto.html#cipherfinaloutputencoding) for the `Cipher` class). For Base64 encoding this leads to data loss during encryption for the posted example. – Topaco Apr 11 '22 at 13:30
  • 1
    Also, for encryption, not `ascii` but `binary` should be used as output encoding (even if `ascii` works for this example, it won't work in general). – Topaco Apr 11 '22 at 14:23
  • @Topaco you are right! I fall in the very strange use of the cypher class! If you write your response I will accept it – Elia Apr 11 '22 at 21:05

0 Answers0