1

i am trying to encrypt long tokens but i get error Error: Trying to add data in unsupported state

import * as crypto from 'crypto';
import { APP_CONFIG } from "@app-config";
const algorithm = 'aes-256-cbc';
const cipher = crypto.createCipheriv(algorithm, Buffer.from(APP_CONFIG.ENCRYPTION.ENCRYPTION_KEY), APP_CONFIG.ENCRYPTION.IV);
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(APP_CONFIG.ENCRYPTION.ENCRYPTION_KEY), APP_CONFIG.ENCRYPTION.IV);

class cryptoHelper {
    constructor() {
    }

    encrypt(text) {
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return encrypted.toString('hex');
    }

    decrypt(encryptedData) {
        let encryptedText = Buffer.from(encryptedData, 'hex');
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        return decrypted.toString();
    }
}

export const CryptoHelper = new cryptoHelper();

CryptoHelper.encrypt("long string"); // 1200 length for example
// encrypt will fail

i am trying to encrypt google auth tokens(access_token and refresh_token) is there any way to encrypt long strings?

Topaco
  • 40,594
  • 4
  • 35
  • 62
user8987378
  • 182
  • 1
  • 2
  • 17
  • 1
    The problem is not the length. After a `final()` call the `cipher`/`decipher` instance cannot be used anymore (s. e.g. [here](https://nodejs.org/api/crypto.html#crypto_cipher_final_outputencoding)), i.e. your architecture allows only one `encrypt()` and one `decrypt()` call. For multiple calls you have to reinstantiate the `cipher`/`decipher` instance. – Topaco Sep 05 '21 at 08:04

0 Answers0