forked from guweichun/UtilsCollection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSAUtil.java
More file actions
70 lines (59 loc) · 2.37 KB
/
Copy pathRSAUtil.java
File metadata and controls
70 lines (59 loc) · 2.37 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
public final class RSAUtil {
private RSAUtil() {}
public static PrivateKey getPrivateKey(String key) {
try {
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(
Base64Util.decode(key).getBytes()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encrypt(String value, String key, String charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
Base64Util.decode(key).getBytes());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(privateKey);
signature.update(value.getBytes(charset));
return Base64Util.encode(signature.sign());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decrypt(String value, String key, String charset) {
try {
PrivateKey privateKey = getPrivateKey(key);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
InputStream stream = new ByteArrayInputStream(Base64Util.decode(value).getBytes());
ByteArrayOutputStream writer = new ByteArrayOutputStream();
byte[] buffer = new byte[128];
int size;
while ((size = stream.read(buffer)) != -1) {
byte[] block = null;
if (buffer.length == size) {
block = buffer;
} else {
block = new byte[size];
for (int i = 0; i < size; i++) {
block[i] = buffer[i];
}
}
writer.write(cipher.doFinal(block));
}
return new String(writer.toByteArray(), charset);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}