Node.jsでOpenSSL証明書を発行する方法として、ライブラリを使用する方法と、OpenSSLを直接実行する方法があります。ここでは代表的なライブラリであるnode-forgeと、最終的に採用されたchild_processでOpenSSLコマンドを実行する方法を紹介します。
1. node-forgeを使う方法
node-forgeは、SSL/TLSやX.509証明書などを扱える非常に有名なライブラリです。
特徴
- ブラウザ・Node.js両対応
- X.509証明書やRSA鍵ペアの生成が可能
- メンテナンス頻度が比較的高い
インストール
npm install --save-dev node-forge
サンプルコード
import forge from "node-forge";
const keyPair = forge.pki.rsa.generateKeyPair(2048);
const certificate = forge.pki.createCertificate();
certificate.publicKey = keyPair.publicKey;
certificate.serialNumber = "01";
certificate.validity.notBefore = new Date();
certificate.validity.notAfter = new Date();
certificate.validity.notAfter.setFullYear(certificate.validity.notBefore.getFullYear() + 1);
const attrs = [
{ name: "commonName", value: "example.org" },
{ name: "countryName", value: "JP" },
{ shortName: "ST", value: "Tokyo" },
{ name: "localityName", value: "Shibuya" },
{ name: "organizationName", value: "Example Inc." },
{ shortName: "OU", value: "IT Department" }
];
certificate.setSubject(attrs);
certificate.setIssuer(attrs);
certificate.sign(keyPair.privateKey);
const pem = forge.pki.certificateToPem(certificate);
console.log(pem);
2. OpenSSLをchild_processで実行する方法
OpenSSLを直接使用する場合、Node.jsのchild_processモジュールでコマンドを実行します。
特徴
- OpenSSLのすべての機能が使える
- システムにOpenSSLがインストールされている必要がある(例: Dockerコンテナに事前インストール)
サンプルコード(秘密鍵と自己署名証明書の生成)
import { execSync } from "child_process";
import { writeFileSync } from "fs";
const keyFile = "private.key";
const certFile = "certificate.crt";
try {
execSync(`openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout ${keyFile} -out ${certFile} \
-subj "/C=JP/ST=Tokyo/L=Shibuya/O=Example Inc./OU=IT Department/CN=example.org"`);
const privateKey = execSync(`cat ${keyFile}`).toString();
const certificate = execSync(`cat ${certFile}`).toString();
writeFileSync("output.key", privateKey);
writeFileSync("output.crt", certificate);
console.log("証明書と鍵が生成されました。");
} catch (error) {
console.error("OpenSSLコマンドの実行に失敗しました:", error);
}
まとめ
- node-forgeはJavaScriptのみで完結した証明書生成が可能。
- child_processでOpenSSL実行は、実際のOpenSSLツールを使うため、正確で信頼性が高い。
プロジェクトの要件やセキュリティポリシーに応じて、適切な方法を選定すると良いでしょう。