-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoRSA.java
More file actions
89 lines (73 loc) · 2.23 KB
/
Copy pathCryptoRSA.java
File metadata and controls
89 lines (73 loc) · 2.23 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package atChat;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class CryptoRSA extends Crypt {
private final Cipher encryptor;
private final Cipher decryptor;
protected final byte[] pubKey;
protected CryptoRSA() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair pair = kpg.genKeyPair();
KeyFactory kFact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKeySpec = kFact.getKeySpec(pair.getPublic(), RSAPublicKeySpec.class);
PublicKey pKey = kFact.generatePublic(pubKeySpec);
pubKey = pair.getPublic().getEncoded();
encryptor = Cipher.getInstance("RSA");
encryptor.init(Cipher.ENCRYPT_MODE, pKey);
decryptor = Cipher.getInstance("RSA");
decryptor.init(Cipher.DECRYPT_MODE, kFact.generatePrivate(kFact.getKeySpec(pair.getPrivate(), RSAPrivateKeySpec.class)));
}
protected CryptoRSA(byte[] pubKey) throws Exception {
this.pubKey = pubKey;
KeyFactory kFact = KeyFactory.getInstance("RSA");
PublicKey pKey = kFact.generatePublic(new X509EncodedKeySpec(pubKey));
encryptor = Cipher.getInstance("RSA");
encryptor.init(Cipher.ENCRYPT_MODE, pKey);
decryptor = null;
}
@Override
protected byte[] encrypt(final String text) {
try {
return encryptor.doFinal(text.getBytes());
} catch (Exception e) {
return null;
}
}
@Override
protected byte[] encrypt(final byte[] bytes) {
try {
return encryptor.doFinal(bytes);
} catch (Exception e) {
return null;
}
}
@Override
protected String decrypt(final byte[] bytes) {
if (decryptor != null) {
try {
return new String(decryptor.doFinal(bytes));
} catch (Exception e) {
return null;
}
}
return null;
}
@Override
protected byte[] decryptBytes(final byte[] bytes) {
if (decryptor != null) {
try {
return decryptor.doFinal(bytes);
} catch (Exception e) {
return null;
}
}
return null;
}
}