NodeJs
中有一个函数,它使用node-jose
从证书中获取指纹。
const jose = require('node-jose');
generateJwkThumbprint = async (jwk) => {
let jwkKey = await jose.JWK.asKey(jwk, 'pem'); //convert pem to jwk
let jwkThumbprintBuffer = await jwkKey.thumbprint('SHA-256'); // sha256 has of the jwk object
let jwkThumbprint = jose.util.base64url.encode(jwkThumbprintBuffer, 'utf8'); // base64 urlencode of the hash
return jwkThumbprint;
};
let publicKey = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZ1fr5JeX52k397Eex4oDBwODEOwz\nBG5qGAfmBFSz4aRZkqJeMPq5pV6jhaPN/w9wvTYNc0ibT8129/GCag6Snw==\n-----END PUBLIC KEY-----\n";
(async () => {
try {
let thumbprint = await generateJwkThumbprint(publicKey);
console.log(thumbprint);
} catch (error) {
console.error("Error:", error);
}
})();
字符串
上面的代码在NodeJs
中工作正常。
我尝试使用BouncyCastl
库在C#
中获取拇指指纹:
static void Main()
{
var publicKey =
"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZ1fr5JeX52k397Eex4oDBwODEOwz\nBG5qGAfmBFSz4aRZkqJeMPq5pV6jhaPN/w9wvTYNc0ibT8129/GCag6Snw==\n-----END PUBLIC KEY-----\n";
var thumbprint = GenerateJwkThumbprint(publicKey);
Console.Write(thumbprint);
}
private static AsymmetricKeyParameter JwkPemToAsymmetricKey(string jwkPem)
{
using StringReader reader = new StringReader(jwkPem);
var pemReader = new PemReader(reader);
var keyObject = pemReader.ReadObject();
if (keyObject is ECPublicKeyParameters ecPublicKey)
{
return ecPublicKey;
}
throw new InvalidOperationException("Invalid JWK PEM format or unsupported key type.");
}
private static string GenerateJwkThumbprint(string jwkPem)
{
// Convert PEM to JWK
var jwkKey = JwkPemToAsymmetricKey(jwkPem);
// Calculate SHA-256 thumbprint
var sha256Thumbprint = CalculateSha256Thumbprint(jwkKey);
// Base64url encode the thumbprint
var thumbprint = Base64UrlEncode(sha256Thumbprint);
return thumbprint;
}
private static string Base64UrlEncode(byte[] bytes)
{
return Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').Replace("=", "");
}
private static byte[] CalculateSha256Thumbprint(AsymmetricKeyParameter jwkKey)
{
IDigest digest = new Sha256Digest();
var jwkBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(jwkKey).GetDerEncoded();
digest.BlockUpdate(jwkBytes, 0, jwkBytes.Length);
var thumbprint = new byte[digest.GetDigestSize()];
digest.DoFinal(thumbprint, 0);
return thumbprint;
}
型
但最终我在C#
和NodeJs
中得到了不同的指纹。
结论在NodeJs
thumbprint = "Mts1dD5R6PnYesvL0YLbc43h4YBVrd8_koC9jFsv_Sg"
在C#
thumbprint = 'yLCIQ8WauQaPAC4A3-LQ5l5s_p9vRfOqPl10efd0hck'
他们是不同的,为什么呢?
1条答案
按热度按时间plicqrtu1#
使用ChilkatDnCore包解决
C#代码:
字符串