Load EC public key / private key from String

private void loadPublicKey() {
try {
String pubKey = “MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEKAsFhBG7oJV7QDV7kh4PEEiBI6FghVPzh0Jiuc0Q/L4ZXRjIh8ZQl6EGUjBEgxz6h8dXe50e+DTotQnSiqs29A==”;
byte[] encoded = Base64.getDecoder().decode(pubKey);
KeyFactory kf = KeyFactory.getInstance(“EC”);
EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
publicKey = (ECPublicKey)kf.generatePublic(keySpec);
} catch (Exception e) {
logger.error(“Failed to load public key”, e);
}
}

private void loadPrivateKey() {
try {
String privKey = “MD4CAQAwEAYHKoZIzj0CAQYFK4EEAAoEJzAlAgEBBCAINorlHfu8FSQxtqvBLlk1R04P12uyVjyTY5OTWMX1Zw==”;
byte[] encoded = Base64.getDecoder().decode(privKey);
KeyFactory kf = KeyFactory.getInstance(“EC”);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
privateKey = (ECPrivateKey)kf.generatePrivate(keySpec);
} catch (Exception e) {
logger.error(“Failed to load private key”, e);
}
}

The public/private key are generated from https://mkjwk.org/ and the -----BEGIN PRIVATE KEY----- , -----END PRIVATE KEY----- , etc, are removed.

Image for post
Image for post

To use the keys to sign a JWT with auth0 JWT library:

private Optional<String> sign(String username) {
try {
Algorithm algorithm = Algorithm.ECDSA256(this.publicKey, this.privateKey);
String token = JWT.create()
.withIssuer(“LFF”)
.withExpiresAt(new Date(System.currentTimeMillis() + JWT_TTS))
.withClaim(“user”, username)
.sign(algorithm);
return Optional.of(token);
} catch (JWTCreationException ex){
logger.error(“Failed to create token”, ex);
}
return Optional.empty();
}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store