Skip to content

Instantly share code, notes, and snippets.

@arunpjohny
Last active September 5, 2015 09:45
Show Gist options
  • Save arunpjohny/28edef37a0539f573dfe to your computer and use it in GitHub Desktop.
Save arunpjohny/28edef37a0539f573dfe to your computer and use it in GitHub Desktop.
Methods to create a KeyPair dynamically and to convert to string and back to private/public keys
protected static void generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair genKeyPair = keyGen.genKeyPair();
String publicKey = Base64.encodeBase64String(genKeyPair.getPublic().getEncoded());
String privateKey = Base64.encodeBase64String(genKeyPair.getPrivate().getEncoded());
System.out.println(publicKey);
System.out.println(privateKey);
}
private static PrivateKey createPrivateKey(String string) throws InvalidKeySpecException, NoSuchAlgorithmException {
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(string)));
}
private static PublicKey createPublicKey(String string) throws InvalidKeySpecException, NoSuchAlgorithmException {
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(string)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment