简体   繁体   English

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

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

How to get the certificate ID / fingerprint of an x.509 certificate using node-forge ?如何使用node- forge 获取 x.509 证书的证书 ID/指纹?

Update更新

I need this for AWS IoT.我需要这个用于 AWS IoT。 I've been investigating and ended up that AWS probably uses some fingerprint algorithm to extract the certificate ID.我一直在调查并最终发现 AWS 可能使用了一些指纹算法来提取证书 ID。 It is not baked into the cert, probably the public key is used as a base for the fingerprint.它没有被烘焙到证书中,可能公钥被用作指纹的基础。

Update 2更新 2

Running this command returns the correct fingerprint: openssl x509 -noout -fingerprint -sha256 -inform pem -in cert.crt运行此命令会返回正确的指纹: openssl x509 -noout -fingerprint -sha256 -inform pem -in cert.crt

How to achieve this with node-forge ?如何使用node-forge实现这一点?

I've put together the following one but it does not return the same fp.:我已经将以下一个放在一起,但它不会返回相同的 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()

To expand on the solution of haxpanel with some code in your requested NodeJS code:在您请求的 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, "$1:");
    // 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
}

here you are.给你。 The result will same as openssl x509 -in a.pem -fingerprint -sha256 -noout结果将与openssl x509 -in a.pem -fingerprint -sha256 -noout相同

  import forge from 'node-forge'
  fingerprint() {
    const der = forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes()
    const m = forge.md.sha256.create().start().update(der)
    return  m.digest()
        .toHex()
        .match(/.{2}/g)
        .join(':')
        .toUpperCase()
  }

The solution is: 解决方案是:

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.您只需要从“-----BEGIN CERTIFICATE-----”标头和“-----END CERTIFICATE-----”页脚之间提取字符串,base64对其进行解码并计算SHA1哈希解码数据。

In this case SHA256.在这种情况下,SHA256。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM