How to use the pki function from node-forge

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

Node-forge.pki is a library in Node.js that provides a set of tools to work with public key infrastructure (PKI) related tasks, such as creating, validating, and managing digital certificates and keys.

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){
fork icon187
star icon616
watch icon53

+ 11 other calls in file

2
3
4
5
6
7
8
9
10
11
module.exports = async function (input, options = {}) {
    return new Promise((resolve, reject) => {
        try {
            let output = {};
            
            forge.pki.rsa.generateKeyPair(2048, (err, keys) => {
                if (err) {
                    throw err;
                }
                output.publicKey = forge.pki.publicKeyToPem(keys.publicKey);
fork icon185
star icon980
watch icon19

+ 5 other calls in file

How does node-forge.pki work?

Node-forge.pki is a JavaScript library that provides a set of tools for managing and working with public key infrastructure (PKI) certificates and keys. It can be used to generate, sign, verify, and export certificates, as well as perform other operations related to PKI. The library implements the necessary cryptographic algorithms and protocols to ensure the security and integrity of PKI operations.

2
3
4
5
6
7
8
9
10
 */

console.log('生成根证书\n');

const forge = require('node-forge');
const pki = forge.pki;
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
fork icon106
star icon423
watch icon28

+ 5 other calls in file

147
148
149
150
151
152
153
154
155
156
// CNanme
var domain = 'github.com';

var caCertPem = fs.readFileSync(path.join(__dirname, '../../rootCA/rootCA.crt'));
var caKeyPem = fs.readFileSync(path.join(__dirname, '../../rootCA/rootCA.key.pem'));
var caCert = forge.pki.certificateFromPem(caCertPem);
var caKey = forge.pki.privateKeyFromPem(caKeyPem);

var keys = pki.rsa.generateKeyPair(1024);
var cert = pki.createCertificate();
fork icon92
star icon410
watch icon13

+ 47 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const forge = require("node-forge");

// generate a key pair
const keys = forge.pki.rsa.generateKeyPair(2048);

// create a certificate
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = "01";
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

// set the subject and issuer attributes
const attrs = [
  {
    name: "commonName",
    value: "example.org",
  },
  {
    name: "countryName",
    value: "US",
  },
  {
    shortName: "ST",
    value: "California",
  },
  {
    name: "localityName",
    value: "San Francisco",
  },
  {
    name: "organizationName",
    value: "Example Org",
  },
  {
    shortName: "OU",
    value: "Example Org Certificate Authority",
  },
];
cert.setSubject(attrs);
cert.setIssuer(attrs);

// sign the certificate with the private key
cert.sign(keys.privateKey);

// output the certificate and private key
console.log(forge.pki.certificateToPem(cert));
console.log(forge.pki.privateKeyToPem(keys.privateKey));

7
8
9
10
11
12
13
14
15
16
var fs = require('fs');
var os = require('os');
var https = require('https');
var path = require('path');
var forge = require('node-forge');
var pki = forge.pki;
var md5 = forge.md.md5;
var mkdirp = require('./mkdirp');
var dirtool = require('../helpers/dirTool');
var certDir = dirtool.getCertificateDir();
fork icon59
star icon674
watch icon22

+ 13 other calls in file

70
71
72
73
74
75
76
77
78
};

var getPrivateKey = function() {

  var keyFile = fs.readFileSync(__dirname + '/../private.key');
  var privkey = forge.pki.privateKeyFromPem(keyFile);

  return privkey;
};
fork icon65
star icon210
watch icon28

+ 41 other calls in file

164
165
166
167
168
169
170
171
172
173
authSafe.value.forEach((safe) => {
    const contentInfo = safe;
    forge.asn1.validate(contentInfo, contentInfoValidator, capture, errors);
    const data = capture.content.value[0];
    const contentType = forge.asn1.derToOid(capture.contentType);
    if (contentType === forge.pki.oids.encryptedData) {
        capture = {};
        forge.asn1.validate(data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors);
        const algOid = forge.asn1.derToOid(capture.encAlgorithm);
        if (algOid === forge.pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']) {
fork icon62
star icon142
watch icon52

+ 71 other calls in file

31
32
33
34
35
36
37
38
39
40
    result = forge.pki.privateKeyFromPem(input);
    break;

case 'PUBLIC KEY':
case 'RSA PUBLIC KEY':
    result = forge.pki.publicKeyFromPem(input);
    break;

case 'CERTIFICATE':
case 'X509 CERTIFICATE':
fork icon42
star icon203
watch icon17

+ 15 other calls in file

27
28
29
30
31
32
33
34
35
36
function issueCredentials(managementEndpoint, instanceId, log, callback) {
    log.info('registering with API to get token');

    const keyPair = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
    const privateKey = forge.pki.privateKeyToPem(keyPair.privateKey);
    const publicKey = forge.pki.publicKeyToPem(keyPair.publicKey);

    const postData = {
        publicKey,
    };
fork icon241
star icon0
watch icon87

+ 5 other calls in file

96
97
98
99
100
101
102
103
104
105
exports.decryptAsymmetricWith = decryptAsymmetricWith

function decryptAsymmetricWith (privateJwk, deserializer) {
  deserializer = deserializer || JSON.parse
  var privatePEM = importPrivateKey(privateJwk)
  var privateKey = forge.pki.privateKeyFromPem(privatePEM)
  return asyncify(function (encryptedValue) {
    var chunks = cipher.deserialize(encryptedValue)
    if (chunks.error) {
      throw chunks.error
fork icon38
star icon706
watch icon6

+ 11 other calls in file

15
16
17
18
19
20
21
22
23
24
  const { issuer, subject, validity } = cert;
  return {
    issuedBy: mapEntityAtrributes(issuer.attributes),
    issuedTo: mapEntityAtrributes(subject.attributes),
    validityPeriod: validity,
    pemCertificate: forge.pki.certificateToPem(cert),
  };
};

const extractCertificatesDetails = (certs) => certs
fork icon30
star icon41
watch icon8

13
14
15
16
17
18
19
20
21
});
// 30 days
const SERVER_CERT_TIMEOUT = 30;
const ROOT_CERT_TIMEOUT = 824;

const pki = NodeForge.pki;
const readFile = utils.promisify(fs.readFile);
const writeFile = utils.promisify(fs.writeFile);
const fsstat = utils.promisify(fs.stat);
fork icon23
star icon155
watch icon5

14
15
16
17
18
19
20
21
22
23
let pem = '-----BEGIN CERTIFICATE REQUEST-----\n'
        + base64 + '\n'
        + '-----END CERTIFICATE REQUEST-----\n';

// Parse with Forge
let csr = forge.pki.certificationRequestFromPem(pem);

// Set:
// * error
// * names
fork icon5
star icon5
watch icon4

68
69
70
71
72
73
74
75
76
77
  ]);

  cert.sign(keys.privateKey, forge.md.sha256.create());

  return {
    privateKey: forge.pki.privateKeyToPem(keys.privateKey),
    publicKey: forge.pki.publicKeyToPem(keys.publicKey),
    certificate: forge.pki.certificateToPem(cert)
  };
}
fork icon194
star icon0
watch icon30

+ 199 other calls in file

2
3
4
5
6
7
8
9
10
11

function initCipher(session, keyModulus, keyExponent)
{
    session.aesIV = generateIV();

    session.publicKey = forge.pki.rsa.setPublicKey(
        new forge.jsbn.BigInteger(keyModulus, 16),
        new forge.jsbn.BigInteger(keyExponent, 16)
    );
}
fork icon95
star icon14
watch icon1

+ 9 other calls in file

74
75
76
77
78
79
80
81
82
83
var keyString = null;
var size = options.size;
if (type == keyczar.TYPE_RSA_PRIVATE) {
    if (!size) size = RSA_DEFAULT_BITS;

    var generator = forge.pki.rsa.createKeyPairGenerationState(size);
    // run until done
    forge.pki.rsa.stepKeyPairGenerationState(generator, 0);
    keyString = keyczar_util._rsaPrivateKeyToKeyczarJson(generator.keys.privateKey);
} else if (type == keyczar.TYPE_AES) {
fork icon17
star icon38
watch icon9

+ 7 other calls in file

72
73
74
75
76
77
78
79
80
81
 * @returns { validations, validationState } validations list and validationState, where validationState = VALID if all the validations are VALID or NOT_AVAIABLE; INVALID otherwise
 */
validateJWSCertificate (publicKey) {
  const validation = new Validation(this.validationConfig.jwsCertValidations, true);
  try {
    forge.pki.publicKeyFromPem(publicKey);
  } catch (e) {
    validation.result = ValidationCodes.VALID_STATES.INVALID;
    validation.message = e.message;
    return {
fork icon7
star icon3
watch icon9

5
6
7
8
9
10
11
12
13
14
 * Creates a self signed certificate generated from JWK RSA with PEM format
 * @param rsaPEM PEM formatted RSA Key
 */
public static createSelfSignedCertificateFromRSA(rsaPEMPrivate: string, rsaPEMPublic: string, info: any) {
    const cert = forge.pki.createCertificate();
    cert.publicKey = forge.pki.publicKeyFromPem(
        rsaPEMPublic);
    // alternatively set public key from a csr
    //cert.publicKey = csr.publicKey;
    // NOTE: serialNumber is the hex encoded value of an ASN.1 INTEGER.
fork icon0
star icon1
watch icon4

+ 5 other calls in file

20
21
22
23
24
25
26
27
28
} catch (err) {
  // fallback to native JS (Raspberry Pi: 15 min)
  console.log('fallback to native JS...')
  let pair = forge.rsa.generateKeyPair(2048)
  keypair = {
    public: forge.pki.publicKeyToPem(pair.publicKey),
    private: forge.pki.privateKeyToPem(pair.privateKey)
  }
}
fork icon0
star icon1
watch icon2

+ 9 other calls in file

60
61
62
63
64
65
66
67
68
69
    forge.rsa.generateKeyPair({ bits: 2048, workers: -1 }, (err, keypair) => {
        if (err) {
            err.code = 'KeyGenereateError';
            return callback(err);
        }
        privateKeyPem = forge.pki.privateKeyToPem(keypair.privateKey);
        publicKeyPem = forge.pki.publicKeyToPem(keypair.publicKey);
        return done();
    });
};
fork icon245
star icon0
watch icon2

+ 19 other calls in file