Created
May 16, 2018 21:07
-
-
Save filiperfernandes/bc5f06316fcd8a309b0e88eb1da80044 to your computer and use it in GitHub Desktop.
how to encrypt & decrypt with RSA in Java
This file contains hidden or 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
| import java.security.KeyPair; | |
| import java.security.KeyPairGenerator; | |
| import java.security.NoSuchAlgorithmException; | |
| import java.security.PrivateKey; | |
| import java.security.PublicKey; | |
| import javax.crypto.Cipher; | |
| public class Sample { | |
| public static void main(String [] args) throws Exception { | |
| // generate public and private keys | |
| KeyPair keyPair = buildKeyPair(); | |
| PublicKey pubKey = keyPair.getPublic(); | |
| PrivateKey privateKey = keyPair.getPrivate(); | |
| // encrypt the message | |
| byte [] encrypted = encrypt(privateKey, "This is a secret message"); | |
| System.out.println(new String(encrypted)); // <<encrypted message>> | |
| // decrypt the message | |
| byte[] secret = decrypt(pubKey, encrypted); | |
| System.out.println(new String(secret)); // This is a secret message | |
| } | |
| public static KeyPair buildKeyPair() throws NoSuchAlgorithmException { | |
| final int keySize = 2048; | |
| KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); | |
| keyPairGenerator.initialize(keySize); | |
| return keyPairGenerator.genKeyPair(); | |
| } | |
| public static byte[] encrypt(PrivateKey privateKey, String message) throws Exception { | |
| Cipher cipher = Cipher.getInstance("RSA"); | |
| cipher.init(Cipher.ENCRYPT_MODE, privateKey); | |
| return cipher.doFinal(message.getBytes()); | |
| } | |
| public static byte[] decrypt(PublicKey publicKey, byte [] encrypted) throws Exception { | |
| Cipher cipher = Cipher.getInstance("RSA"); | |
| cipher.init(Cipher.DECRYPT_MODE, publicKey); | |
| return cipher.doFinal(encrypted); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment