-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAES_in_Java
More file actions
41 lines (35 loc) · 1.43 KB
/
AES_in_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
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.util.Base64;
public class AESUtil {
private static final int KEY_SIZE = 256;
private static final int IV_SIZE = 16;
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
public static String encrypt(String plainText, SecretKey key, IvParameterSpec iv)
throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String cipherText, SecretKey key, IvParameterSpec iv)
throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainText = cipher.doFinal(
Base64.getDecoder().decode(cipherText)
);
return new String(plainText);
}
public static SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(KEY_SIZE, SecureRandom.getInstanceStrong());
return keyGen.generateKey();
}
public static IvParameterSpec generateIv() {
byte[] iv = new byte[IV_SIZE];
SecureRandom.getInstanceStrong().nextBytes(iv);
return new IvParameterSpec(iv);
}
}