Skip to content

Instantly share code, notes, and snippets.

@karmanov
Created August 20, 2018 12:48
Show Gist options
  • Save karmanov/f18fe8b1e9c25cf66e709b4edc8fcaea to your computer and use it in GitHub Desktop.
Save karmanov/f18fe8b1e9c25cf66e709b4edc8fcaea to your computer and use it in GitHub Desktop.
Read RSA Private Key from String
private RSAPrivateKey readPrivateKey() throws Exception {
BufferedReader rdr = new BufferedReader(new StringReader(privateKeyString));
String pkcs8Pem = rdr.lines().collect(Collectors.joining());
pkcs8Pem = pkcs8Pem
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
byte[] pkcs8EncodedBytes = Base64.decode(pkcs8Pem);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
return (RSAPrivateKey) privKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment