Search code examples
javaencryptionrsadigital-signaturediffie-hellman

Cannot sign with DH key, cannot perform KeyAgreement with others


I would like to know whether there exists a public/private key specification (preferrably in Java itself, no external libs) that can do both a KeyAgreement and Signature.


Solution

  • Try elliptic curves:

    KeyPairGenerator eckpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec p256 = new ECGenParameterSpec("secp256r1");
    eckpg.initialize(p256);
    KeyPair doubleUseKeyPair = eckpg.generateKeyPair();
    KeyAgreement ecdh = KeyAgreement.getInstance("ECDH");
    ecdh.init(doubleUseKeyPair.getPrivate());
    // ...
    
    Signature ecdsa = Signature.getInstance("SHA256withECDSA");
    ecdsa.initSign(doubleUseKeyPair.getPrivate());
    // ...
    
    System.out.println(eckpg.getProvider());
    System.out.println(ecdh.getProvider());
    System.out.println(ecdsa.getProvider());
    

    Should return:

    SunEC version 1.7

    SunEC version 1.7

    SunEC version 1.7

    This is on Java 7 from Sun/Oracle of course.

    Note that using the same key (pair) two different purposes is considered bad key management by most. It may allow for attacks that uses vulnerabilities in either or a combination in both the algorithms and the protocol. Using the same key type / strength is of course fine.