· 6 years ago · Feb 12, 2019, 04:54 PM
1public static String encrypt(String plainPasword)
2 {
3 String password = "";
4 try
5 {
6 SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");
7 IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US-ASCII"));
8
9 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
10
11 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
12
13 byte[] encoded = cipher.doFinal(plainPasword.getBytes());
14 password = new String(Base64.encodeBase64(encoded));
15
16 }
17 catch (Exception ex)
18 {
19 System.err.println("Encryption Exception: " + ex.toString());
20 }
21 return password;
22 }
23
24Encryption Exception: java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding
25
26Encryption Exception: java.security.InvalidKeyException: Illegal key size
27
28public static String encryptWithAES256(String strToEncrypt) throws Exception
29{
30 MessageDigest digest = MessageDigest.getInstance("SHA-256");
31 byte[] encodedhash = digest.digest(KEY.getBytes(StandardCharsets.UTF_8));
32 IvParameterSpec ivspec = new IvParameterSpec(Arrays.copyOf(KEY.getBytes(),16));
33 SecretKeySpec secretKey = new SecretKeySpec(encodedhash, AES_ENCRYPTION_ALGORITHM);
34 Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
35 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
36 return new String(Base64.encodeBase64(cipher.doFinal(strToEncrypt.getBytes(CHARACTER_ENCODING))));
37}