Using the Node crypto library to create a self-signed certificate?

Is it possible in pure JavaScript (no openssl binary) to use the crypto Node library to create a self-signed certificate? Here is my script that uses openssl to create a certificate:

#!/bin/bash
FQDN="*"

# Create a private key
openssl genrsa \
    -out server-key.pem \
    2048

# Create a certificate signing request
openssl req \
    -new \
    -key server-key.pem \
    -out certificate-signing-request.csr \
    -subj "/C=US/ST=StateL=City/O=Full Name/CN=${FQDN}"

# Sign the certificate signing request to create the server certificate
openssl x509 \
    -req -in certificate-signing-request.csr \
    -signkey server-key.pem \
    -out server-certificate.pem \
    -days 36159

I'm curious if all this can be done using JavaScript and the classes and methods available here:

https://nodejs.org/api/crypto.html

If so, what will be the code for creating the files above?

+4
source share
2 answers

Node crypto , API ( openSSL). , , .

, , , JS ( @robertklep), JavaScript, Forge.

, PEM. Forge , , crypto .

var forge = require('node-forge');
var pki = forge.pki;

// generate a keypair or use one you have already
var keys = pki.rsa.generateKeyPair(2048);

// create a new certificate
var cert = pki.createCertificate();

// fill the required fields
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);

// use your own attributes here, or supply a csr (check the docs)
var attrs = [{
  name: 'commonName',
  value: 'example.org'
}, {
  name: 'countryName',
  value: 'US'
}, {
  shortName: 'ST',
  value: 'Virginia'
}, {
  name: 'localityName',
  value: 'Blacksburg'
}, {
  name: 'organizationName',
  value: 'Test'
}, {
  shortName: 'OU',
  value: 'Test'
}];

// here we set subject and issuer as the same one
cert.setSubject(attrs);
cert.setIssuer(attrs);

// the actual certificate signing
cert.sign(keys.privateKey);

// now convert the Forge certificate to PEM format
var pem = pki.certificateToPem(cert);
console.log(pem);

. forge readme , csr , .

+8

- "" "". CryptoJS ASN.1/DER, . . , , ASN.1/DER .

, CryptoJS , . , , , , . ASN.1/DER - , , , , ASN.1/DER. ASN.1/DER , .

, "", "".

+1

Source: https://habr.com/ru/post/1599625/


All Articles