Created
January 29, 2019 12:38
-
-
Save fukasawah/ff65cddb7a52a2bba6f14ccc9d0d4639 to your computer and use it in GitHub Desktop.
証明書と秘密鍵からPKCS12(PFX)形式に変換
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* PFX converter | |
* | |
* (Usage) node convertpfx.js chain-certifications.crt private.pem private-passphrase.txt output.pfx | |
* | |
*/ | |
const fs = require('fs') | |
const forge = require('node-forge') | |
const certificateFile = process.argv[2] | |
const privateKeyFile = process.argv[3] | |
const privateKeyPassFile = process.argv[4] | |
const outputFile = process.argv[5] | |
console.log("certificateFile:", certificateFile) | |
console.log("privateKeyFile:", privateKeyFile) | |
console.log("privateKeyPassFile:", privateKeyPassFile) | |
const passfrase = fs.readFileSync(privateKeyPassFile, 'utf8') | |
// 秘密鍵を読み取る | |
const privateKey = forge.pki.decryptRsaPrivateKey(fs.readFileSync(privateKeyFile, 'utf8'), passfrase) | |
// 証明書を読み取る。ファイル→pem→der→asn1の変換をかける。 | |
// また、証明書はチェインしている(2つ以上ある)ので、`forge.pki.certificateFromPem`を使わない | |
const certs = forge.pem.decode( | |
fs.readFileSync(certificateFile, 'utf8') | |
).map( | |
(data) => forge.asn1.fromDer(data.body, true) | |
).map( | |
(asn1)=>forge.pki.certificateFromAsn1(asn1) | |
); | |
// TODO: 証明書部分が暗号化から外れてしまうので、pfxファイルを見られると、情報が見られてしまう。 | |
// しかし、node-forgeで証明書部分を暗号化して、そこからpkcs12に変換する方法がわからなかった。 | |
// 秘密鍵、証明書からpkcs12形式のデータを作る。'aes-256-cbc'ではなく'3des'にしないと、Azureで取り込めない。 | |
const pkcs12asn1 = forge.pkcs12.toPkcs12Asn1(privateKey, certs, passfrase, {algorithm: '3des'}) | |
// pkcs12形式のデータをder形式に変換して、binaryファイルとして書き出す | |
const binary = forge.asn1.toDer(pkcs12asn1).getBytes() | |
// 出力 | |
fs.writeFileSync(outputFile, binary, 'binary') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment