Created
November 14, 2016 12:35
-
-
Save tassioauad/c97ed6f7a2edf84dc1e87b981f6c23d1 to your computer and use it in GitHub Desktop.
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
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