forked from hacker85/JavaLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSALesson.java
More file actions
41 lines (35 loc) · 1.43 KB
/
Copy pathRSALesson.java
File metadata and controls
41 lines (35 loc) · 1.43 KB
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
package security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
/**
* Created by max on 2/18/17.
*/
public class RSALesson {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("RSA");
int mode = Cipher.ENCRYPT_MODE;
KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
// SecureRandom random = new SecureRandom();
// pairgen.initialize(512, random);
KeyPair keyPair = pairgen.generateKeyPair();
Key publicKey = keyPair.getPublic();
Key privateKey = keyPair.getPrivate();
cipher.init(mode, publicKey);
String hello = "hello world";
byte[] bytes = cipher.doFinal(hello.getBytes(), 0, hello.length());
for(byte b : bytes) {
System.out.print(b);
}
System.out.println("\n----------");
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes2 = decryptCipher.doFinal(bytes, 0, bytes.length);
for(byte b : bytes2) {
System.out.print((char)b);
}
}
}