-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA
More file actions
28 lines (24 loc) · 1.05 KB
/
RSA
File metadata and controls
28 lines (24 loc) · 1.05 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
public class RSAUtil {
private static final int KEY_SIZE = 2048;
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(KEY_SIZE, SecureRandom.getInstanceStrong());
return keyPairGen.generateKeyPair();
}
public static String encrypt(String plainText, PublicKey publicKey)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.getEncoder().encodeToString(
cipher.doFinal(plainText.getBytes())
);
}
public static String decrypt(String cipherText, PrivateKey privateKey)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(
Base64.getDecoder().decode(cipherText)
));
}
}