我使用generateKeyPair()
方法使用ECDSA算法生成2个不同的KeyPair
。
public KeyPair generateKeyPair(){
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp192r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(spec, new SecureRandom());
return g.generateKeyPair();
}
然后我使用PrivateKey
和PublicKey
分开KeyPair
来合并SecretKey
:
private SecretKey generateSecretKey(PrivateKey privateKey, PublicKey publicKey) {
KeyAgreement ka = KeyAgreement.getInstance("ECDH");
ka.init(privateKey);
ka.doPhase(publicKey),
true);
return ka.generateSecret("AES");
}
但是我到了ka.generateSecret("AES")
:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at org.bouncycastle.jcajce.provider.asymmetric.util.BaseAgreementSpi.engineGenerateSecret(Unknown Source)
at javax.crypto.KeyAgreement.generateSecret(KeyAgreement.java:648)
如果我使用ECDSA,我会得到:
Exception in thread "main" java.security.NoSuchAlgorithmException: Algorithm ECDSA not available
at javax.crypto.KeyAgreement.getInstance(KeyAgreement.java:184)
使用DH投掷:
Exception in thread "main" java.security.InvalidKeyException: DHKeyAgreement requires DHPrivateKey
at org.bouncycastle.jcajce.provider.asymmetric.dh.KeyAgreementSpi.engineInit(Unknown Source)
at javax.crypto.KeyAgreement.implInit(KeyAgreement.java:346)
at javax.crypto.KeyAgreement.chooseProvider(KeyAgreement.java:378)
at javax.crypto.KeyAgreement.init(KeyAgreement.java:470)
如何从使用ECDSA算法生成的SecretKey
和PrivateKey
合并PublicKey
?
答案 0 :(得分:1)
它正常工作,并在删除" AES"后返回曲线大小共享密钥。来自return ka.generateSecret();
的论据:
private SecretKey generateSecretKey(PrivateKey privateKey, PublicKey publicKey) {
KeyAgreement ka = KeyAgreement.getInstance("ECDH");
ka.init(privateKey);
ka.doPhase(publicKey, true);
return ka.generateSecret();
}
答案 1 :(得分:0)
密钥协商协议通常在双方之间工作,每个方都有自己的ECDS公钥和私钥(因此我们有四个不同的密钥)。你确定那是你想要的吗?
因此,当您同意某个密钥时,您需要甲方的私钥和乙方的公钥。在连接的另一端,您使用B方的私钥和A方的公钥。
您选择的ECDH密钥协商算法在RFC3278中有所描述 - 详细信息请参阅。