Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8323999

KeyAgreement cannot be initiated again after a failed initialization

XMLWordPrintable

      public class KeyAgreementReinit {

          public static void main(String[] args) throws Exception {
              KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
              kpg.initialize(256);
              KeyPair kp = kpg.generateKeyPair();
              ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate();

              KeyFactory keyFactory = KeyFactory.getInstance("EC");
              ECPrivateKey invalidPrivateKey
                      = (ECPrivateKey) keyFactory.generatePrivate(
                              new ECPrivateKeySpec(BigInteger.ZERO,
                                      privateKey.getParams()));

              KeyAgreement ka = KeyAgreement.getInstance("ECDH");

              try {
                  // The first initialization with invalid key should fail.
                  ka.init(invalidPrivateKey);
              } catch (InvalidKeyException e) {
                  // Do nothing
              }

              // The second initialization with valid key still fail.
              ka.init(privateKey);
          }
      }

      The above test raises the below error,
      Exception in thread "main" java.security.InvalidKeyException: No installed provider supports this key: sun.security.ec.ECPrivateKeyImpl
      at java.base/javax.crypto.KeyAgreement.chooseProvider(KeyAgreement.java:414)
      at java.base/javax.crypto.KeyAgreement.init(KeyAgreement.java:481)
      at java.base/javax.crypto.KeyAgreement.init(KeyAgreement.java:452)
      at KeyAgreementReinit.main(KeyAgreementReinit.java:34)

      If the first initialization succeeds, the KeyAgreement can be re-initialized.

            jjiang John Jiang
            jjiang John Jiang
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: