gpt4 book ai didi

java - 如何确定X509公钥的长度

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:15:14 26 4
gpt4 key购买 nike

如何确定 Java 中 X509 公钥的长度(以位为单位)?

我希望在运行“openssl x509 -in cert.crt -noout -text”时获得与“Public-Key”相同的值。例如:

Certificate:
Data:
Version: 3 (0x2)
Serial Number:
17:00:00:01:a2:41:4b:56:3e:99:ba:92:b5:00:02:00:00:01:a2
Signature Algorithm: sha256WithRSAEncryption
Issuer: DC=com, DC=magnicomp, CN=MagniComp Issuing CA
Validity
Not Before: Sep 14 17:23:18 2015 GMT
Not After : Sep 13 17:23:18 2016 GMT
Subject: CN=dim.magnicomp.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)

我有一个 X509Certificate 对象,我已经尝试过通过 getPublicKey() 返回的 PublicKey 值,但我似乎无法弄清楚如何从中确定 key 长度。

最佳答案

片段来自 EJBCA源代码org.ejbca.util.keystore.KeyTools #getKeyLength 从各种算法的公钥计算 key 长度:

/**
* Gets the key length of supported keys
* @param pk PublicKey used to derive the keysize
* @return -1 if key is unsupported, otherwise a number >= 0. 0 usually means the length can not be calculated,
* for example if the key is an EC key and the "implicitlyCA" encoding is used.
*/
public static int getKeyLength(final PublicKey pk) {
int len = -1;
if (pk instanceof RSAPublicKey) {
final RSAPublicKey rsapub = (RSAPublicKey) pk;
len = rsapub.getModulus().bitLength();
} else if (pk instanceof JCEECPublicKey) {
final JCEECPublicKey ecpriv = (JCEECPublicKey) pk;
final org.bouncycastle.jce.spec.ECParameterSpec spec = ecpriv.getParameters();
if (spec != null) {
len = spec.getN().bitLength();
} else {
// We support the key, but we don't know the key length
len = 0;
}
} else if (pk instanceof ECPublicKey) {
final ECPublicKey ecpriv = (ECPublicKey) pk;
final java.security.spec.ECParameterSpec spec = ecpriv.getParams();
if (spec != null) {
len = spec.getOrder().bitLength(); // does this really return something we expect?
} else {
// We support the key, but we don't know the key length
len = 0;
}
} else if (pk instanceof DSAPublicKey) {
final DSAPublicKey dsapub = (DSAPublicKey) pk;
if ( dsapub.getParams() != null ) {
len = dsapub.getParams().getP().bitLength();
} else {
len = dsapub.getY().bitLength();
}
}
return len;
}

关于java - 如何确定X509公钥的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com