How to use node-forge

Comprehensive node-forge code examples:

How to use node-forge.createCertificate:

11
12
13
14
15
16
17
18
19
20
  process.exit(1)
})

router.get('/generatecert', function (req, res, next) {
  const keys = pki.rsa.generateKeyPair(2048)
  const cert = pki.createCertificate()
  cert.publicKey = keys.publicKey
  res.send({
    keys: keys,
    cert: cert

How to use node-forge.md5:

782
783
784
785
786
787
788
789
790
791
if (loginType === 'email') {
  const email = getParameterByName('email', url);

  req_data = {
    username: email,
    password: forge.md5
      .create()
      .update(forge.util.encodeUtf8(password))
      .digest()
      .toHex(),

How to use node-forge.sha256:

39
40
41
42
43
44
45
46
47
48
  method,
  url,
  postdata,
  signingDate
)
const digest = forge.sha256
  .create()
  .update(sigData)
  .digest()
  .getBytes()

How to use node-forge.rc2:

13
14
15
16
17
18
19
20
21
22
23
24
const bad4 = CryptoJS.PBKDF2(password, salt, { keySize: 2 }); // NOT OK
const bad5 = CryptoJS.EvpKDF(password, salt, { keySize: 2 }); // NOT OK
const bad6 = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); // OK


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

How to use node-forge.pem:

20
21
22
23
24
25
26
27
28
29
 * @param {string} input PEM string
 * @return {object}
 */

function forgeObjectFromPem(input) {
    const msg = forge.pem.decode(input)[0];
    let result;

    switch (msg.type) {
        case 'PRIVATE KEY':

How to use node-forge.aes:

229
230
231
232
233
234
235
236
237
238
var key = keyczar_util.decodeBase64Url(data.key);

var derivedKey = _deriveKey(password, salt, data.iterationCount);

// decrypt the key with the derived key
var cipher = forge.aes.startDecrypting(derivedKey, iv, null);
cipher.update(new forge.util.ByteBuffer(key));
var success = cipher.finish();
if (!success) {
    throw new Error(PBE_DECRYPT_FAILED_MESSAGE);

How to use node-forge.privateKeyFromPem:

181
182
183
184
185
186
187
188
189
190
}

function decryptKeyInfoWithScheme(encryptedKey, options, scheme) {
  try {
    var key = new Buffer(encryptedKey.textContent, 'base64').toString('binary');
    var private_key = pki.privateKeyFromPem(options.key);
    var decrypted = private_key.decrypt(key, scheme);
    return new Buffer(decrypted, 'binary');
  }
  catch (e) {

How to use node-forge.kem:

71
72
73
74
75
76
77
78
79
80
const publicKey = toPem.publicKeyFromPem(pemPublicKey);

// Use RSA-KEM to encrypt the msg with a randomly
// 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;

How to use node-forge.rsa:

59
60
61
62
63
64
65
66
67
68
        return done();
    });
}

// Fallback to Forge
forge.rsa.generateKeyPair({ bits: 2048, workers: -1 }, (err, keypair) => {
    if (err) {
        err.code = 'KeyGenereateError';
        return callback(err);
    }

How to use node-forge.pbe:

28
29
30
31
32
33
34
35
36
37

function aesCbcPassphraseEncryptToBase64(password, data) {
  var keySize = 32;
  var ivSize = 16;
  var salt = generateRandomSalt8Byte();
  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);

How to use node-forge.pkcs5:

207
208
209
210
211
212
213
214
215
216
function _deriveKey(password, salt, iterationCount) {
    // check ! > 0 so that it fails for undefined
    if (!(iterationCount > 0)) {
        throw new Error('Invalid iterationCount: ' + iterationCount);
    }
    return forge.pkcs5.pbkdf2(
        password, salt, iterationCount, _PBE_AES_KEY_BYTES, forge.md.sha1.create());
}

var PBE_DECRYPT_FAILED_MESSAGE = 'AES decryption failed (password incorrect or data is corrupt?)';

How to use node-forge.hmac:

60
61
62
63
64
65
66
67
68
69
hash.file.sha512 = function(file, cb) {
  hashFile(forge.md.sha512.create(), file, cb);
};

hash.hmac = function(type, key, data, cb) {
  var hmac = forge.hmac.create();
  hmac.start(type, key);
  hashData(hmac, data, cb);
};
hash.file.hmac = function(type, key, file, cb) {

How to use node-forge.ssh:

35
36
37
38
39
40
41
  const forgePublicKey = forge.pki.setRsaPublicKey(
    forgePrivateKey.n,
    forgePrivateKey.e
  )

  return forge.ssh.publicKeyToOpenSSH(forgePublicKey).trim()
}

How to use node-forge.tls:

350
351
352
353
354
355
356
357
358
359

__Examples__

```js
// create TLS client
var client = forge.tls.createConnection({
  server: false,
  caStore: /* Array of PEM-formatted certs or a CA store object */,
  sessionCache: {},
  // supported cipher suites in order of preference

How to use node-forge.jsbn:

4
5
6
7
8
9
10
11
12
13
{
    session.aesIV = generateIV();

    session.publicKey = forge.pki.rsa.setPublicKey(
        new forge.jsbn.BigInteger(keyModulus, 16),
        new forge.jsbn.BigInteger(keyExponent, 16)
    );
}

function cipher(session, data, { key, compress, disableIV } = {})

How to use node-forge.publicKeyFromPem:

4
5
6
7
8
9
10
11
12
13
var utils   = require('./utils');
var pki     = require('node-forge').pki;

function encryptKeyInfoWithScheme(symmetricKey, options, scheme, callback) {
  try {
    var rsa_pub = pki.publicKeyFromPem(options.rsa_pub);
    var encrypted = rsa_pub.encrypt(symmetricKey.toString('binary'), scheme);
    var base64EncodedEncryptedKey = new Buffer(encrypted, 'binary').toString('base64');

    var params = {

How to use node-forge.random:

146
147
148
149
150
151
152
153
154
155
    })
}

function randomBytes (num) {
  return new Promise(function (resolve, reject) {
    forge.random.getBytes(16, function (err, bytes) {
      if (err) {
        return reject(err)
      }
      resolve(bytes)

How to use node-forge.cipher:

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;
  }

How to use node-forge.pkcs12:

116
117
118
119
120
121
122
123
124
125
const key = fs.readFileSync(keyPath)
const crt = fs.readFileSync(crtPath)
const prikey = forge.pki.privateKeyFromPem(key.toString())
const pubcrt = forge.pki.certificateFromPem(crt.toString())

const p12Asn1 = forge.pkcs12.toPkcs12Asn1(prikey, pubcrt, password)
const p12Der = forge.asn1.toDer(p12Asn1).getBytes()
const p12b64 = forge.util.encode64(p12Der)

return p12b64

How to use node-forge.asn1:

173
174
175
176
177
178
179
180
181
182

    return logins;
}

function decodeLoginData(b64) {
    const asn1 = forge.asn1.fromDer(forge.util.decode64(b64));
    return {
        iv: asn1.value[1].value[1].value,
        data: asn1.value[2].value
    };

How to use node-forge.default:

144
145
146
147
148
149
150
151
152
153
p7.addSigner({
  key: privateKey,
  certificate,
  digestAlgorithm: _nodeForge.default.pki.oids.sha256,
  authenticatedAttributes: [{
    type: _nodeForge.default.pki.oids.contentType,
    value: _nodeForge.default.pki.oids.data
  }, {
    type: _nodeForge.default.pki.oids.signingTime,
    // value can also be auto-populated at signing time

How to use node-forge.md:

76
77
78
79
80
81
82
83
84
85
  * Calculates a MD5 hash.
  * @param {String} data to hash
  * @returns {String} last 8 characters of hash of data
  */
  md5(data) {
    const md5hash = forge.md.md5.create().update(data).digest().toHex();
    return md5hash.toString().toLowerCase().substr(8, 16);
  }
}
module.exports = TuyaCipher;

How to use node-forge.pkcs7:

215
216
217
218
219
220
221
222
223
224
}

public encrypt(value: string, publicKey: string): any
{
    const cert = forge.pki.certificateFromPem(publicKey);
    const p7 = forge.pkcs7.createEnvelopedData();
    p7.addRecipient(cert);
    p7.content = forge.util.createBuffer();
    p7.content.putString(value);
    p7.encrypt();

How to use node-forge.util:

93
94
95
96
97
98
99
100
101

  fullChallenge = Buffer.concat([fullChallenge, new Buffer(padding)]).toString('binary');
  var response = forge.pki.rsa.encrypt(fullChallenge, privateKey, 0x01);
  debug('computed challenge: %s', forge.util.encode64(response));

  return forge.util.encode64(response);
};

var generateRfc2617Response = function(username, realm, password, nonce, uri, method) {

How to use node-forge.pki:

6
7
8
9
10
11
12
13
14
15
const logger = require('./logger.js').child({category: 'CMGR'});
const lpm_file = require('../util/lpm_file.js');
const zerr = require('../util/zerr.js');

const keys = forge.pki.rsa.generateKeyPair(2048);
keys.privateKeyPem = forge.pki.privateKeyToPem(keys.privateKey);
keys.publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey);

class Cluster_mgr {
    constructor(mgr){