Dav*_*ead 8 java encryption bouncycastle elliptic-curve
在Java中,我有一个ECDH公钥,我将其作为字节数组发送.
收到字节数组后,如何将其重新转换为公钥?
我正在使用Bouncy Castle,但Java解决方案同样有用.
谢谢
当你得到编码密钥时,假设你使用了默认的"[your keyPair] .getPublic().getEncoded()"方法,这将有效.
X509EncodedKeySpec ks = new X509EncodedKeySpec(pubKeyByteString.toByteArray());
KeyFactory kf;
try {
kf = java.security.KeyFactory.getInstance("ECDH");
} catch (NoSuchAlgorithmException e) {
log.error("Cryptography error: could not initialize ECDH keyfactory!", e);
return;
}
ECPublicKey remotePublicKey;
try {
remotePublicKey = (ECPublicKey)kf.generatePublic(ks);
} catch (InvalidKeySpecException e) {
log.warn("Received invalid key specification from client",e);
return;
} catch (ClassCastException e) {
log.warn("Received valid X.509 key from client but it was not EC Public Key material",e);
return;
}
Run Code Online (Sandbox Code Playgroud)
我发现@LaceCard 的上述解决方案对我不起作用。一般来说,这并不明显,但密码学中没有什么是;)
String key = "MihU9ztW9sEvkBL6BxyaOMgkSbodNS8yoHaHcio+WE...blahblah"
byte[] keyBytes = Base64.decode(key);
//If using Android and Spongycastle provider should be "SC"
KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
//CURVE_NAME e.g prime192v1
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_NAME);
ECPoint point = ecSpec.getCurve().decodePoint(keyBytes);
ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);
ECPublicKey myECPublicKey = (ECPublicKey) kf.generatePublic(pubSpec);
Run Code Online (Sandbox Code Playgroud)
注意:您需要适当地处理潜在的异常
| 归档时间: |
|
| 查看次数: |
5416 次 |
| 最近记录: |