RSA加密解密以及秘钥的生成

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
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class Demo {

public static void main(String... args) throws Exception {
d();
}

public static void d() throws Exception {

//生成密钥对
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair key = keyGen.generateKeyPair();

// 公钥
byte[] pub = key.getPublic().getEncoded();
// 私钥
byte[] pri = key.getPrivate().getEncoded();

// 原文
byte[] plainText = "你看看".getBytes();

//加密工具
Cipher c1 = Cipher.getInstance("RSA");
c1.init(Cipher.ENCRYPT_MODE, key.getPrivate());
byte[] cipherText = c1.doFinal(plainText);

c1.init(Cipher.DECRYPT_MODE, key.getPublic());
byte[] output = c1.doFinal(cipherText);
}
}