Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bogdannistorbogdan/7e169cf71f3706feb6b89e3910e719cb to your computer and use it in GitHub Desktop.
Save bogdannistorbogdan/7e169cf71f3706feb6b89e3910e719cb to your computer and use it in GitHub Desktop.
public static String signSha256WithRsa(String toSign, String privateKeyString) {
if (toSign == null || privateKeyString == null) {
return null;
}
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = new PKCS8EncodedKeySpec(org.apache.commons.codec.binary
.Base64.decodeBase64(privateKeyString.getBytes("utf-8")));
PrivateKey prvKey = kf.generatePrivate(keySpec);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(prvKey);
sig.update(toSign.getBytes());
byte[] sigBytes = sig.sign();
return new String(org.apache.commons.codec.binary.Base64.encodeBase64(sigBytes));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment