Last active
September 5, 2015 09:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static PrivateKey createPrivateKey(String string) throws InvalidKeySpecException, NoSuchAlgorithmException { | |
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(string))); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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