package com.gwcworld.util;
import java.security.Key;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class SymmetricCipher {
private static final String ALGORITHM = "AES";
public static String encrypt(String salt, String content) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(salt));
byte[] encryptedBytes = cipher.doFinal(content.getBytes());
return new BASE64Encoder().encode(encryptedBytes);
}
public static String decrypt(String salt, String content) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey(salt));
byte[] decryptedBytes = cipher.doFinal(new BASE64Decoder().decodeBuffer(content));
return new String(decryptedBytes);
}
private static Key generateKey(String keyValue) throws Exception {
Key key = new SecretKeySpec(keyValue.getBytes(), ALGORITHM);
return key;
}
}