从ECPrivateKey生成ECPublicKey

我正在尝试在给定私钥和已知曲线的情况下生成公钥。下面是我的代码:

// Generate Keys

ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", "BC");

keyPairGenerator.initialize(ecGenSpec, new SecureRandom());

java.security.KeyPair pair = keyPairGenerator.generateKeyPair();

ECPrivateKey privateKey = (ECPrivateKey) pair.getPrivate();

ECPublicKey publicKeyExpected = (ECPublicKey) pair.getPublic();

// Expected public key

System.out.print("Expected Public Key: " +

BaseEncoding.base64Url().encode(publicKeyExpected.getEncoded()));

// Generate public key from private key

X9ECParameters ecp = SECNamedCurves.getByName("secp256r1");

ECDomainParameters domainParams = new ECDomainParameters(ecp.getCurve(),

ecp.getG(), ecp.getN(), ecp.getH(),

ecp.getSeed());

ECPoint Q = domainParams.getG().multiply(privateKey.getS()); // is this correct?

KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC");

ECPublicKey publicKeyGenerated =

(ECPublicKey) kf.generatePublic(new X509EncodedKeySpec(Q.getEncoded(false))); // exception here

// Generated public key from private key

System.out.print("Generated Public Key: " +

BaseEncoding.base64Url().encode(publicKeyGenerated.getEncoded()));

但是,当我打电话给kf.generatePublic(new X509EncodedKeySpec(Q.getEncoded(false)))

我时:我得到了例外:(java.security.spec.InvalidKeySpecException: encoded key spec not

recognised不是我的拼写错误)

我似乎在计算错误Q,但是我不确定错误在哪里。

谢谢您的帮助!

回答:

如果我未来的自己需要解决方案:

// Generate Keys

ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", "BC");

keyPairGenerator.initialize(ecGenSpec, new SecureRandom());

java.security.KeyPair pair = keyPairGenerator.generateKeyPair();

ECPrivateKey privateKey = (ECPrivateKey) pair.getPrivate();

ECPublicKey publicKeyExpected = (ECPublicKey) pair.getPublic();

// Expected public key

System.out.print("Expected Public Key: " +

BaseEncoding.base64Url().encode(publicKeyExpected.getEncoded()));

// Generate public key from private key

KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");

ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");

ECPoint Q = ecSpec.getG().multiply(privateKey.getD());

byte[] publicDerBytes = Q.getEncoded(false);

ECPoint point = ecSpec.getCurve().decodePoint(publicDerBytes);

ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

ECPublicKey publicKeyGenerated = (ECPublicKey) keyFactory.generatePublic(pubSpec);

// Generated public key from private key

System.out.print("Generated Public Key: " +

BaseEncoding.base64Url().encode(publicKeyGenerated.getEncoded()));

以上是 从ECPrivateKey生成ECPublicKey 的全部内容, 来源链接: utcz.com/qa/423194.html

回到顶部