如何使用 node-forge 从 x.509 获得 AWS 使用的相同指纹?

How to get the same fingerprint that AWS uses from x.509 with node-forge?

如何使用 node-forge 获取 x.509 证书的证书 ID/指纹?

更新

我需要这个用于 AWS IoT。我一直在调查并最终发现 AWS 可能使用某种指纹算法来提取证书 ID。它没有被烘焙到证书中,可能 public 密钥用作指纹的基础。

更新 2

运行 这个命令 return 是正确的指纹:openssl x509 -noout -fingerprint -sha256 -inform pem -in cert.crt

如何使用 node-forge 实现此目的?

我已经把下面的放在一起了,但它 return 不是相同的 fp。:

const fs = require('fs')
const forge = require('node-forge')
const { pki } = forge
const { promisify } = require('es6-promisify')
const readFile = promisify(fs.readFile)

async function main() {
  const certPem = await readFile('./cert.crt', 'utf-8')
  const cert = pki.certificateFromPem(certPem)
  const fingerprint = pki.getPublicKeyFingerprint(cert.publicKey, {
    md: forge.md.sha256.create(),
    encoding: 'hex',
  })
}

main()

solution是:

You just need to extract the string from between the "-----BEGIN CERTIFICATE-----" header and "-----END CERTIFICATE----- " footer, base64 decode it and compute SHA1 hash of decoded data.

在本例中为 SHA256。

在您请求的 NodeJS 代码中使用一些代码扩展 haxpanel 的解决方案:

const crypto = require("crypto");

function getCertificateFingerprint(certString) {
    const baseString = certString.match(/-----BEGIN CERTIFICATE-----\s*([\s\S]+?)\s*-----END CERTIFICATE-----/i);
    const rawCert = Buffer.from(baseString[1], "base64");
    const sha256sum = crypto.createHash("sha256").update(rawCert).digest("hex");
    return sha256sum.toUpperCase().replace(/(.{2})(?!$)/g, ":");
    // eg 83:6E:3E:99:58:44:AE:61:72:55:AD:C6:24:BE:5C:2D:46:21:BA:BE:87:E4:3A:38:C8:E8:09:AC:22:48:46:20
}