sha2 java_在Java Security中使用openssh公钥(ecdsa-sha2-nistp256)

本文介绍了如何在Java中使用JCE和Bouncyycastle库处理ecdsa-sha2-nistp256类型的公钥。通过解析公钥的Q值和标识符,创建并生成适用于ECPublicKeySpec的ECPoint。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

为了完整起见,这是我使用的代码。它是几乎纯的JCE,在帮助器方法中散布了Bouncycastle(这会更新Java安全中的“使用authorized_keys中的公共密钥”中的示例代码):

...

} else if (type.startsWith("ecdsa-sha2-") &&

(type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {

// Based on RFC 5656, section 3.1 (https://tools.ietf.org/html/rfc5656#section-3.1)

String identifier = decodeType();

BigInteger q = decodeBigInt();

ECPoint ecPoint = getECPoint(q, identifier);

ECParameterSpec ecParameterSpec = getECParameterSpec(identifier);

ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParameterSpec);

return KeyFactory.getInstance("EC").generatePublic(spec);

} ...

/**

* Provides a means to get from a parsed Q value to the X and Y point values.

* that can be used to create and ECPoint compatible with ECPublicKeySpec.

*

* @param q According to RFC 5656:

* "Q is the public key encoded from an elliptic curve point into an octet string"

* @param identifier According to RFC 5656:

* "The string [identifier] is the identifier of the elliptic curve domain parameters."

* @return An ECPoint suitable for creating a JCE ECPublicKeySpec.

*/

ECPoint getECPoint(BigInteger q, String identifier) {

String name = identifier.replace("nist", "sec") + "r1";

ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);

org.bouncycastle.math.ec.ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());

BigInteger x = point.getAffineXCoord().toBigInteger();

BigInteger y = point.getAffineYCoord().toBigInteger();

System.out.println("BC x = " + x);

System.out.println("BC y = " + y);

return new ECPoint(x, y);

}

/**

* Gets the curve parameters for the given key type identifier.

*

* @param identifier According to RFC 5656:

* "The string [identifier] is the identifier of the elliptic curve domain parameters."

* @return An ECParameterSpec suitable for creating a JCE ECPublicKeySpec.

*/

ECParameterSpec getECParameterSpec(String identifier) {

try {

// http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)

String name = identifier.replace("nist", "sec") + "r1";

AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");

parameters.init(new ECGenParameterSpec(name));

return parameters.getParameterSpec(ECParameterSpec.class);

} catch (InvalidParameterSpecException | NoSuchAlgorithmException e) {

throw new IllegalArgumentException("Unable to get parameter spec for identifier " + identifier, e);

}

}

2020-11-26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值