Skip to content

Instantly share code, notes, and snippets.

@mf81bln
Last active December 27, 2017 14:46
Show Gist options
  • Save mf81bln/6be42cc53f442bd105b8ee2dc007cac4 to your computer and use it in GitHub Desktop.
Save mf81bln/6be42cc53f442bd105b8ee2dc007cac4 to your computer and use it in GitHub Desktop.
encrypt / decrypt with RSA in JAVA
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
// to generate a KeyPair use
// KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
// PrivateKey privKey = keys.getPrivate();
// PublicKey pubKey = keys.getPublic();
final public class CryptoUtility
{
public static String encrypt(final String clearText, final String base64EncodedRSAPublicKey) throws GeneralSecurityException
{
final byte[] publicKey = DatatypeConverter.parseBase64Binary(base64EncodedRSAPublicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pk = kf.generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
final byte[] encrypted = cipher.doFinal(clearText.getBytes());
return DatatypeConverter.printBase64Binary(encrypted);
}
public static String decrypt(final String encryptedText, final String base64EncodedRSAPrivateKey) throws GeneralSecurityException
{
final byte[] privateKey = DatatypeConverter.parseBase64Binary(base64EncodedRSAPrivateKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pk);
final byte[] decrypted = cipher.doFinal(DatatypeConverter.parseBase64Binary(encryptedText));
return new String(decrypted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment