1
+ import java .security .KeyPair ;
2
+ import java .security .KeyPairGenerator ;
3
+ import java .security .NoSuchAlgorithmException ;
4
+ import java .security .PrivateKey ;
5
+ import java .security .PublicKey ;
6
+
7
+ import javax .crypto .Cipher ;
8
+ import java .util .*;
9
+ public class RSA {
10
+
11
+ public static void main (String [] args ) throws Exception {
12
+ // generate public and private keys
13
+ KeyPair keyPair = buildKeyPair ();
14
+ PublicKey pubKey = keyPair .getPublic ();
15
+ PrivateKey privateKey = keyPair .getPrivate ();
16
+
17
+ // encrypt the message
18
+ System .out .println ("Enter message" );
19
+ Scanner sc =new Scanner (System .in );
20
+ String msg =sc .next ();
21
+ byte [] encrypted = encrypt (privateKey ,msg );
22
+ System .out .println ("Encrypted String: " +new String (encrypted )); // <<encrypted message>>
23
+
24
+ // decrypt the message
25
+ byte [] secret = decrypt (pubKey , encrypted );
26
+ System .out .println ("decrypted String: " +new String (secret )); // This is a secret message
27
+ }
28
+
29
+ public static KeyPair buildKeyPair () throws NoSuchAlgorithmException {
30
+ final int keySize = 2048 ;
31
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator .getInstance ("RSA" );
32
+ keyPairGenerator .initialize (keySize );
33
+ return keyPairGenerator .genKeyPair ();
34
+ }
35
+
36
+ public static byte [] encrypt (PrivateKey privateKey , String message ) throws Exception {
37
+ Cipher cipher = Cipher .getInstance ("RSA" );
38
+ cipher .init (Cipher .ENCRYPT_MODE , privateKey );
39
+
40
+ return cipher .doFinal (message .getBytes ());
41
+ }
42
+
43
+ public static byte [] decrypt (PublicKey publicKey , byte [] encrypted ) throws Exception {
44
+ Cipher cipher = Cipher .getInstance ("RSA" );
45
+ cipher .init (Cipher .DECRYPT_MODE , publicKey );
46
+
47
+ return cipher .doFinal (encrypted );
48
+ }
49
+ }
0 commit comments