· 6 years ago · Mar 30, 2019, 12:12 PM
1import javax.crypto.*;
2import javax.crypto.spec.SecretKeySpec;
3import java.nio.charset.StandardCharsets;
4import java.security.InvalidKeyException;
5import java.security.NoSuchAlgorithmException;
6
7public class Crypto
8{
9 public static final String ALGORITHM_DES = "DES";
10 public static final String ALGORITHM_3DES = "DESede";
11 public static final String ALGORITHM_AES = "AES";
12
13 public static Encrypted encrypt(String text, String encryption)
14 {
15 try
16 {
17 //Generate key
18 KeyGenerator keyGenerator = KeyGenerator.getInstance(encryption);
19 SecretKey desKey = keyGenerator.generateKey();
20
21 //Initialize cipher
22 Cipher desCipher = Cipher.getInstance(encryption);
23 desCipher.init(Cipher.ENCRYPT_MODE, desKey);
24
25 //Convert text to byte array
26 byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
27
28 //Encrypt
29 byte[] encryptedBytes = desCipher.doFinal(bytes);
30
31 return new Encrypted(encryptedBytes, desKey.getEncoded(), encryption);
32 }
33 catch(NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e)
34 {
35 e.printStackTrace();
36 }
37
38 return null;
39 }
40
41 public static String decrypt(byte[] encryptedText, byte[] key, String encryption)
42 {
43 try
44 {
45 //Convert key
46 SecretKey desKey = new SecretKeySpec(key, 0, key.length, encryption);
47
48 //Initialize cipher
49 Cipher desCipher = Cipher.getInstance(encryption);
50 desCipher.init(Cipher.DECRYPT_MODE, desKey);
51
52 //Decrypt
53 byte[] decryptedBytes = desCipher.doFinal(encryptedText);
54
55 return new String(decryptedBytes);
56 }
57 catch(NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e)
58 {
59 e.printStackTrace();
60 }
61
62 return null;
63 }
64}