0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsでOpenSSL証明書を発行する方法

Posted at

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ツールを使うため、正確で信頼性が高い。

プロジェクトの要件やセキュリティポリシーに応じて、適切な方法を選定すると良いでしょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?