How to use the cipher function from node-forge

Find comprehensive JavaScript node-forge.cipher code examples handpicked from public code repositorys.

node-forge.cipher is a function in the Node.js Forge library that can be used to encrypt and decrypt data using various symmetric encryption algorithms.

9
10
11
12
13
14
15
16
17
* @example
* const cipher = new TuyaCipher({key: 'xxxxxxxxxxxxxxxx', version: 3.1})
*/
class TuyaCipher {
  constructor(options) {
    this.cipher = forge.cipher.createCipher('AES-ECB', options.key);
    this.decipher = forge.cipher.createDecipher('AES-ECB', options.key);
    this.version = options.version;
  }
fork icon311
star icon1
watch icon0

+ 3 other calls in file

33
34
35
36
37
38
39
40
41
42
var derivedBytes = forge.pbe.opensslDeriveBytes(
  password, salt, keySize + ivSize);
var buffer = forge.util.createBuffer(derivedBytes);
var key = buffer.getBytes(keySize);
var iv = buffer.getBytes(ivSize);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(data)));
cipher.finish();
var output = forge.util.createBuffer();
fork icon13
star icon38
watch icon6

+ 15 other calls in file

How does node-forge.cipher work?

node-forge.cipher is a function in the Node.js Forge library that can be used to encrypt and decrypt data using various symmetric encryption algorithms.

To use node-forge.cipher, you first need to create a new cipher object using the forge.cipher.createCipher or forge.cipher.createDecipher method, which takes an algorithm and a secret key as arguments.

Once the cipher object is created, you can use the cipher.update and cipher.final methods to encrypt or decrypt data.

The cipher.update method takes the data to be encrypted or decrypted as an argument and returns a chunk of processed data. This method can be called multiple times with different data to build up the final result.

The cipher.final method is called to retrieve any remaining data after all updates have been processed, and returns the final encrypted or decrypted data.

Overall, node-forge.cipher provides a powerful and flexible way to perform symmetric encryption and decryption operations in Node.js applications.

58
59
60
61
62
63
64
65
66
67
  if (this.devices[i].version === undefined) {
    this.devices[i].version = 3.1;
  }

  // Create cipher from key
  this.devices[i].cipher = forge.cipher.createCipher('AES-ECB', this.devices[i].key);
}

this._connectTotalTimeout = undefined;
this._connectRetryAttempts = undefined;
fork icon311
star icon9
watch icon2

29
30
31
32
33
34
35
36
37
38
case SYMMETRIC_ALGO_AESGCM: {
  // web crypto simply appends the authentication tag to the ciphertext
  // so this is what we are doing here as well
  var tag = chunks.cipher.slice(chunks.cipher.length - 16)
  var body = chunks.cipher.slice(0, chunks.cipher.length - 16)
  var op = forge.cipher.createDecipher('AES-GCM', keyBytes)
  op.start({
    iv: chunks.nonce,
    tagLength: 128,
    tag: forge.util.createBuffer(tag)
fork icon38
star icon706
watch icon6

+ 11 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const forge = require("node-forge");

const algorithm = "AES-CBC";
const key = "my-secret-key";
const iv = forge.random.getBytesSync(16);
const plaintext = "Hello, world!";

// Create a new cipher object for encryption
const cipher = forge.cipher.createCipher(algorithm, key);
cipher.start({ iv });
cipher.update(forge.util.createBuffer(plaintext));
cipher.finish();
const ciphertext = cipher.output.bytes();

// Create a new cipher object for decryption
const decipher = forge.cipher.createDecipher(algorithm, key);
decipher.start({ iv });
decipher.update(forge.util.createBuffer(ciphertext));
decipher.finish();
const decryptedPlaintext = decipher.output.bytes();

console.log(`Plaintext: ${plaintext}`);
console.log(`Ciphertext: ${ciphertext}`);
console.log(`Decrypted plaintext: ${decryptedPlaintext}`);

In this example, we use node-forge.cipher to encrypt and decrypt the plaintext string 'Hello, world!' using the AES encryption algorithm with a CBC (cipher-block chaining) mode of operation. We create a random initialization vector (IV) using forge.random.getBytesSync(16), which is used to ensure that the same plaintext does not always produce the same ciphertext. We then create a new cipher object using forge.cipher.createCipher with the algorithm and key arguments, and use the start, update, and finish methods to encrypt the plaintext. We do the same for the decipher object, using forge.cipher.createDecipher to create a new object with the same algorithm and key, and use the start, update, and finish methods to decrypt the ciphertext. Finally, we log the plaintext, ciphertext, and decrypted plaintext to the console. This is just one example of how node-forge.cipher can be used to perform symmetric encryption and decryption operations. With support for various encryption algorithms and modes, node-forge.cipher provides a powerful tool for securing data in Node.js applications.

218
219
220
221
222
223
224
225
226
227

  encryptedKeys[fingerprint] = forge.util.encode64(encryptedKey);
}); // Create buffer and cipher

var buffer = forge.util.createBuffer(message, 'utf8');
var cipher = forge.cipher.createCipher(this.options.aesStandard, key); // Actual encryption

cipher.start({
  iv: iv
});
fork icon40
star icon126
watch icon6

+ 3 other calls in file

60
61
62
63
64
65
66
67
68
  password, salt, keySize + ivSize);
var buffer = forge.util.createBuffer(derivedBytes);
var key = buffer.getBytes(keySize);
var iv = buffer.getBytes(ivSize);

var decipher = forge.cipher.createDecipher('3DES-CBC', key);
decipher.start({iv: iv});
decipher.update(input);
var result = decipher.finish(); // check 'result' for true/false
fork icon1
star icon1
watch icon3

+ 3 other calls in file

51
52
53
54
55
56
57
58
59
60
cipher.finish()
let ciphertext = iv + cipher.output.toHex()

iv = ciphertext.slice(0, AES_IV_LENGTH)
let encrypted = ciphertext.slice(AES_IV_LENGTH)
var decipher = forge.cipher.createDecipher('AES-CBC', key.slice(0, 32))
decipher.start({iv: iv})
decipher.update(forge.util.createBuffer(forge.util.hexToBytes(encrypted)))
decipher.finish()
decipher.output.toString()
fork icon19
star icon62
watch icon5

+ 3 other calls in file

74
75
76
77
78
79
80
81
82
83
// generated one time password and AES-256
const kdf1 = new forge.kem.kdf1(forge.md.sha256.create());
const kem = forge.kem.rsa.create(kdf1);
const otp = kem.encrypt(publicKey, 32);
const iv = forge.random.getBytesSync(12);
const cipher = forge.cipher.createCipher('AES-GCM', otp.key);
let aesCipherText;
let encryptedOTP;

cipher.start({ iv });
fork icon1
star icon3
watch icon1

+ 7 other calls in file

25
26
27
28
29
30
31
32
33
34
//   encrypted += cipher.final('base64');
//   return encrypted;
// };

function encrypt3DES(keyToEncryptWith, text) {
  const cipher = forge.cipher.createCipher(
    '3DES-ECB',
    forge.util.createBuffer(keyToEncryptWith),
  );
  cipher.start({ iv: '' });
fork icon0
star icon1
watch icon2

44
45
46
47
48
49
50
51
52
53
this.encryptFileWith3DES_ECB = function(plainFilePath, key, encryptedFilePath) {
    const data = fs.readFileSync(plainFilePath, {
        encoding: 'binary',
        mode: 0777
    });
    const cipher = forge.cipher.createCipher(ALGORITHM_3DES_ECB, key); // create cipher.
    cipher.start(); // start encryption.

    cipher.update(forge.util.createBuffer(data));
    cipher.finish(); // finish.
fork icon17
star icon30
watch icon0

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
27
28
const forge = require("node-forge");
var bad7 = forge.rc2.createEncryptionCipher(password, 64); // NOT OK
var good3 = forge.rc2.createEncryptionCipher(password, 128); // OK


var key1 = forge.random.getBytesSync(16);
var good4 = forge.cipher.createCipher('AES-CBC', key1); // OK


var key2 = forge.random.getBytesSync(8);
var bad8 = forge.cipher.createCipher('AES-CBC', key2); // NOT OK

fork icon0
star icon1
watch icon0

+ 3 other calls in file

87
88
89
90
91
92
93
94
95
96
const data = forge.util.decode64(cipherText)
const SYMMETRIC_KEY = forge.util.createBuffer((Buffer.from(symmetricKey, 'hex')).toString('binary'))
const IV = forge.util.createBuffer((Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])).toString('binary')) // Initialization vector of 16 null bytes
const CIPHERTEXT = forge.util.createBuffer(data.slice(0, -16))

const decipher = forge.cipher.createDecipher('AES-GCM', SYMMETRIC_KEY) // Creates and returns a Decipher object that uses the given algorithm and password (key)
const tag = data.slice(-16, data.length)

decipher.start({
  iv: IV,
fork icon1
star icon0
watch icon0

25
26
27
28
29
30
31
32
33
34
35
}


export function decryptBinaryStringCBC(binaryString, key, iv) {
    let thisBuffer = forge.util.createBuffer();
    thisBuffer.putBytes(binaryString);
    let decipher = forge.cipher.createDecipher('AES-CBC', key);
    decipher.start({
      iv: iv
    });
    decipher.update(thisBuffer);
fork icon1
star icon0
watch icon0

+ 13 other calls in file

348
349
350
351
352
353
354
355
356
357
358


//Encrypt data AES 256
export const _encryp = (secureData) => {
  var key = forge.random.getBytesSync(64);
  var iv = forge.random.getBytesSync(64);
  var cipher = forge.cipher.createCipher("AES-CBC", SECRET_KEY);
  cipher.start({ iv: iv });
  cipher.update(forge.util.createBuffer(secureData));
  cipher.finish();
  var encrypted = cipher.output;
fork icon0
star icon0
watch icon1

18
19
20
21
22
23
24
25
26
27
    console.log(decrypt(encrypted));
    return res;
}
function decrypt(encrypted) {
    let enc = forge.util.createBuffer(forge.util.hexToBytes(encrypted), "raw");
    var decipher = forge.cipher.createDecipher("AES-CBC", key);
    decipher.start({ iv: iv });
    decipher.update(enc);
    var result = decipher.finish(); // check 'result' for true/false
    return JSON.parse(decipher.output.toString());
fork icon0
star icon0
watch icon0

10
11
12
13
14
15
16
17
18
19
20
    return encrypted.toHex();
}


function decrypt(key, iv, encryptedData){
    encryptedData = forge.util.createBuffer(forge.util.hexToBytes(encryptedData));
    var decipher = forge.cipher.createDecipher('AES-CBC', key);
    decipher.start({iv: iv});
    decipher.update(encryptedData);
    decipher.finish();
    var result = decipher.output.data;
fork icon0
star icon0
watch icon0

64
65
66
67
68
69
70
71
72
73
74
75


};


const encrypt = function(bytes) {
  const iv = forge.random.getBytesSync(12);
  const cipher = forge.cipher.createCipher('AES-GCM', e2ee.key);
  cipher.start({
    iv: iv, // should be a 12-byte binary-encoded string or byte buffer
    //additionalData: 'binary-encoded string', // optional
    tagLength: 128 // optional, defaults to 128 bits
fork icon0
star icon0
watch icon0

0
1
2
3
4
5
6
7
8
9
10
const forge = require("node-forge");


module.exports.encrypt = (message) => {
  let key = forge.random.getBytesSync(16);
  let iv = forge.random.getBytesSync(16);
  let cipher = forge.cipher.createCipher("AES-CBC", key);
  cipher.start({ iv: iv });
  cipher.update(forge.util.createBuffer(message));
  cipher.finish();
  let encrypted = cipher.output.data;
fork icon0
star icon0
watch icon0

53
54
55
56
57
58
59
60
61
62
if (API_VERSION == constants.AUTH.API2_5.API_VERSION) {
	//AES-256/GCM
	let tsLast12Bytes = Buffer.from(ts).slice(-12);
	let tsLast16Bytes = Buffer.from(ts).slice(-16);

	let cipher = forge.cipher.createCipher(ALGO_AES_GCM, key);
	cipher.start({
		iv: tsLast12Bytes,
		additionalData: tsLast16Bytes
	});
fork icon0
star icon0
watch icon0