Created
October 27, 2017 12:16
-
-
Save muthugit/00886f5d17b37e532bd86e45a814ad46 to your computer and use it in GitHub Desktop.
how to encrypt & decrypt with RSA in Java
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
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