How to use the util function from node-forge

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

node-forge.util provides various utility functions for working with cryptography in Node.js.

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) {
fork icon65
star icon210
watch icon28

+ 27 other calls in file

151
152
153
154
155
156
157
158
159
160
 * @returns {string} PEM body
 */

exports.getPemBody = (str) => {
    const msg = forge.pem.decode(str)[0];
    return forge.util.encode64(msg.body);
};


/**
fork icon42
star icon203
watch icon17

How does node-forge.util work?

node-forge is a cryptographic library for Node.js and the browser, and node-forge.util provides a variety of utility functions. It includes functions for converting between different data formats, encoding and decoding data to and from various formats, generating random bytes, encoding and decoding base64, hex, and binary data, and parsing and generating ASN.1 structures. These functions can be used to help with cryptographic operations such as generating keys, encrypting and decrypting data, and signing and verifying digital signatures.

33
34
35
36
37
38
39
40
41
42
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)
})
op.update(forge.util.createBuffer(body))
if (op.finish()) {
  if (inflate) {
fork icon38
star icon706
watch icon6

+ 5 other calls in file

186
187
188
189
190
191
192
193
194
195
const key4FilePath = path.join(profileDirectory, 'key4.db');
if (!fs.existsSync(key4FilePath)) {
    throw new Error('key4.db was not found in this profile directory.');
}

const masterPasswordBytes = forge.util.encodeUtf8(masterPassword || '');
const key4File = fs.readFileSync(key4FilePath);
const key4Db = new SQL.Database(key4File);
const metaData = key4Db.exec('SELECT item1, item2 FROM metadata WHERE id = \'password\';');
if (metaData && metaData.length && metaData[0].values && metaData[0].values.length) {
fork icon63
star icon475
watch icon31

Ai Example

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

const str = "Hello, World!";

const encodedStr = forge.util.encode64(str);

console.log(encodedStr); // 'SGVsbG8sIFdvcmxkIQ=='

In this example, we first require the node-forge library. We then define a string that we want to encode in base64. We use the forge.util.encode64() function to encode the string, and store the result in the encodedStr variable. Finally, we log the encoded string to the console.

126
127
128
129
130
131
132
133
134
135
    PKCS8: 'pkcs8',
    OPENSSL: 'openssl-legacy'
};

const getPkcs12Asn1 = function (pkcs12Item) {
    const pkcs12Der = forge.util.decode64(pkcs12Item);
    return forge.asn1.fromDer(pkcs12Der);
};

// from node-forge
fork icon62
star icon142
watch icon52

+ 11 other calls in file

70
71
72
73
74
75
76
77
78
79
     *
     * @method
     */
    _entropy(input: any): void {
        const inputString = String(input);
        const bytes = forge.util.encodeUtf8(inputString);

        forge.random.collect(bytes);
    }
}
fork icon40
star icon126
watch icon6

143
144
145
146
147
148
149
150
151
152

checkSum.update(message, 'utf8'); // Accept both PEMs and forge private key objects

if (typeof privateKey === 'string') privateKey = pki.privateKeyFromPem(privateKey);
var signature = privateKey.sign(checkSum);
var signature64 = forge.util.encode64(signature); // Return signature in JSON format

return JSON.stringify({
  signature: signature64,
  md: this.options.md
fork icon40
star icon126
watch icon6

+ 27 other calls in file

230
231
232
233
234
235
236
237
238
239

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);
}
fork icon17
star icon38
watch icon9

+ 3 other calls in file

30
31
32
33
34
35
36
37
38
39
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);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
fork icon13
star icon35
watch icon6

+ 55 other calls in file

94
95
96
97
98
99
100
101
102
103
    return new forge.util.ByteBuffer(forge.random.generate(16));
}

function getUUID(session, iv)
{
    return forge.util.encode64(session.publicKey.encrypt(iv.bytes()), 64);
}

function getLoginKey(username, password, scramble, fromCas)
{
fork icon95
star icon14
watch icon1

+ 109 other calls in file

117
118
119
120
121
122
123
124
125
}

convertJwkPubKeyToRsaPubKey (jwkPubKey) {
  // see: https://github.com/digitalbazaar/forge/issues/444#issuecomment-264224314
  function base64urlToBigInteger(str) {
    var bytes = forge.util.decode64(
      (str + '==='.slice((str.length + 3) % 4))
        .replace(/\-/g, '+')
        .replace(/_/g, '/'));
fork icon30
star icon130
watch icon16

92
93
94
95
96
97
98
99
100
101

function decryptLocalControlToken(encrypted: string, onSuccess: (string) => void) {
        if (supportRSA()) {
                getRSAKey(false, ({ pemPvt }: Object) => {
                        const privateKey = forge.pki.privateKeyFromPem(pemPvt);
                        const decoded64 = forge.util.decode64(encrypted);
                        const token = privateKey.decrypt(decoded64, 'RSA-OAEP', {
                                md: forge.md.sha256.create(),
                        });
                        onSuccess(token);
fork icon5
star icon13
watch icon7

+ 3 other calls in file

25
26
27
28
29
30
31
32
33
                // Generate keypair using forge
                pki.rsa.generateKeyPair({bits: keySize || this.options.keySize, workers: -1}, done);
        }

        _entropy(input) {
        bytes = forge.util.encodeUtf8(String(input));
        forge.random.collect(bytes);
    }
}
fork icon0
star icon2
watch icon1

27
28
29
30
31
32
33
34
35
36
  this.cipher.start({iv: ''});
  this.cipher.update(forge.util.createBuffer(options.data, 'utf8'));
  this.cipher.finish();

  if (options.base64 !== false) {
    return forge.util.encode64(this.cipher.output.data);
  }

  return this.cipher.output;
};
fork icon307
star icon0
watch icon2

+ 41 other calls in file

47
48
49
50
51
52
53
54
55
56

var bytesLength = 4;

// Get the main Key
var mainKey = publicFile.toString().split(' ')[1]; // [0] is prefix
var keyBytes = forge.util.decode64(mainKey);

// Get fields
var type = getField(keyBytes, 0);
var exponent = getField(keyBytes, type.end);
fork icon5
star icon4
watch icon5

15
16
17
18
19
20
21
22
23
24
var hashFileSync = function(md, file) {
  // Get a base64 version of the file
  // and give it to forge to obtain a
  // forge Buffer
  var buf64 = fs.readFileSync(file).toString('base64');
  var fBuf = forge.util.decode64(buf64);
  md.update(fBuf);
  return md.digest().toHex();
};
var hashFile = async.asyncify(hashFileSync);
fork icon4
star icon4
watch icon0

+ 15 other calls in file

41
42
43
44
45
46
47
48
49
50
// openssl enc -d -des3 -in input.enc -out input.dec.txt
function decrypt(password) {
  var input = fs.readFileSync('input.enc', {encoding: 'binary'});

  // parse salt from input
  input = forge.util.createBuffer(input, 'binary');
  // skip "Salted__" (if known to be present)
  input.getBytes('Salted__'.length);
  // read 8-byte salt
  var salt = input.getBytes(8);
fork icon1
star icon1
watch icon3

+ 7 other calls in file

217
218
219
220
221
222
223
224
225
226
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();
    const bytes = forge.asn1.toDer(p7.toAsn1()).getBytes();
    const raw = forge.util.encode64(bytes);
fork icon0
star icon56
watch icon7

+ 3 other calls in file

118
119
120
121
122
123
124
125
126
  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
}
fork icon333
star icon0
watch icon36

+ 3 other calls in file

277
278
279
280
281
282
283
284
285
286
  // server.process(connection.tlsData.getBytes());
},
dataReady: function(connection) {
  // clear data from the server is ready
  console.log('the server sent: ' +
    forge.util.decodeUtf8(connection.data.getBytes()));
  // close connection
  connection.close();
},
/* NOTE: experimental
fork icon767
star icon0
watch icon0

+ 5 other calls in file