May 18, 2017

How to Generate Elliptic Curve Keys in Java 8

// Supported Providers in Java 8
for (Provider provider : Security.getProviders()) {
    System.out.println("Provider : " + provider);
}

// Supported Algorithm in Java: "DiffieHellman", "DSA", "RSA" and "EC"
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyPairGenerator

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC", "SunEC");
// SecureRandom.getInstanceStrong() (Java 8) is the Recommended way to use initialize random,
// it chooses automatically the strongest algorithm for your OS
keyGen.initialize(256, SecureRandom.getInstanceStrong());
KeyPair kp = keyGen.genKeyPair();
PrivateKey privateKey = kp.getPrivate();
PublicKey publicKey = kp.getPublic();
System.out.println("PrivateKey : " + privateKey);
System.out.println("PublicKey : " + publicKey);
// the key in its primary encoding format
byte[] publicKeyInfo = publicKey.getEncoded();

No comments: