package com.nbad.push.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class EncryptDecrypt {
private static final String IV_PARAMETER_SPEC = "weJiSEvR5yAC5ftB";
static final String SECRET_KEY_SPEC = "weJiSEvR5yAC5ftB";
public static String encrypt(String toBeEncrypt) throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER_SPEC.getBytes("UTF-8"));
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY_SPEC.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(toBeEncrypt.getBytes("UTF-8"));
return Base64.encodeBase64String(encrypted);
}
public static String decrypt(String encrypted) throws InvalidAlgorithmParameterException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER_SPEC.getBytes("UTF-8"));
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY_SPEC.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(decryptedBytes,"UTF-8");
}
public static void main(String[] args) throws NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
String encrypt = encrypt("woaini");
System.out.println(encrypt);
String decrypt = decrypt(encrypt);
System.out.println(decrypt);
}
}