Skip to content

Instantly share code, notes, and snippets.

@zihluwang
Last active July 6, 2024 01:30
Show Gist options
  • Save zihluwang/bba262a56f155de648d4c89cd08d678e to your computer and use it in GitHub Desktop.
Save zihluwang/bba262a56f155de648d4c89cd08d678e to your computer and use it in GitHub Desktop.
A loader for EC Key Pair
public class KeyLoader {
private static ECPrivateKey loadPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// generate key: openssl ecparam -genkey -name secp521r1 -noout -out private_key.pem
// parse key: openssl pkcs8 -topk8 -in .\private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
var privateKey = "key string";
var keyBytes = Base64.getDecoder().decode(privateKey);
var spec = new PKCS8EncodedKeySpec(keyBytes);
var kf = KeyFactory.getInstance("EC");
var key = kf.generatePrivate(spec);
if (key instanceof ECPrivateKey pk) {
return pk;
} else {
throw new RuntimeException("Type error!");
}
}
private static ECPublicKey loadPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// get public key: openssl ec -in private_key.pem -pubout -out public_key.pem
var publicKey = "key string";
var keyBytes = Base64.getDecoder().decode(publicKey);
var spec = new X509EncodedKeySpec(keyBytes);
var keyFactory = KeyFactory.getInstance("EC");
var key = keyFactory.generatePublic(spec);
if (key instanceof ECPublicKey ecPk) {
return ecPk;
} else {
throw new RuntimeException("Type Error!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment