-
Notifications
You must be signed in to change notification settings - Fork 1
/
RSA.java
49 lines (40 loc) · 1.85 KB
/
RSA.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.*;
public class RSA {
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
System.out.println("Enter message");
Scanner sc =new Scanner(System.in);
String msg=sc.next();
byte [] encrypted = encrypt(privateKey,msg);
System.out.println("Encrypted String: "+new String(encrypted)); // <<encrypted message>>
// decrypt the message
byte[] secret = decrypt(pubKey, encrypted);
System.out.println("decrypted String: "+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);
}
}