Skip to content

Instantly share code, notes, and snippets.

@tassioauad
Created November 14, 2016 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tassioauad/c97ed6f7a2edf84dc1e87b981f6c23d1 to your computer and use it in GitHub Desktop.
Save tassioauad/c97ed6f7a2edf84dc1e87b981f6c23d1 to your computer and use it in GitHub Desktop.
public class RsaCipher {
private PublicKey publicKey;
private PrivateKey privateKey;
public RsaCipher(PublicKey publicKey, PrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public static KeyPair genKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(512);
KeyPair keyPair = generator.generateKeyPair();
return keyPair;
}
public String encrypt(String string) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return new String(cipher.doFinal(string.getBytes()));
}
public String decrypt(String string) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(string.getBytes()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment