· 7 years ago · Feb 06, 2018, 03:48 PM
1CryptoUtils.removeCryptoRestriction();
2
3String string = "Hello world! This is a test string. Have a nice day!";
4byte[] iv = CryptoUtils.generateIv();
5byte[] key = CryptoUtils.generateKey();
6
7byte[] encrypted = CryptoUtils.doCrypto(Cipher.ENCRYPT_MODE, key, iv, string.getBytes("UTF-8"));
8System.out.println(new String(encrypted));
9
10byte[] decrypted = CryptoUtils.doCrypto(Cipher.DECRYPT_MODE, key, iv, encrypted);
11System.out.println(new String(decrypted));
12
13��zI Fğ��O>��_�@3�ܷ+|ZI�m���M�4�;���ygr8G�ܪ8�6u���M
14Hello world! This is a test string. Have a nice day!
15
16public static byte[] doCrypto(int mode, byte[] keyBytes, byte[] ivBytes, byte[] bytes) throws GeneralSecurityException {
17 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
18 SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
19 IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
20 cipher.init(mode, secretKeySpec, ivParameterSpec);
21 return cipher.doFinal(bytes);
22}
23
24public static byte[] generateIv() {
25 SecureRandom secureRandom = new SecureRandom();
26 byte[] iv = new byte[16];
27 secureRandom.nextBytes(iv);
28 return iv;
29}
30
31public static byte[] generateKey() throws NoSuchAlgorithmException {
32 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
33 keyGenerator.init(256);
34 SecretKey secretKey = keyGenerator.generateKey();
35 return secretKey.getEncoded();
36}
37
38public static void removeCryptoRestriction() {
39 Security.setProperty("crypto.policy", "unlimited");
40}