import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; public class Security { public static final String KEY = "1234567XDE234lom"; // private final static Log log = LogFactory.getLog(Security.class); public static String encrypt(String input, String key) { byte[] crypted = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); } catch (Exception e) { } return new String(Base64.encodeBase64(crypted)); } public static String decrypt(String input, String key) { byte[] output = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey); output = cipher.doFinal(Base64.decodeBase64(input)); } catch (Exception e) { System.out.println(e.toString()); } return new String(output); } public static String encryptWithUTF8(String input, String key) { byte[] crypted = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(crypted)); } /** * Encrypt with any of tools. * * @param string * -Need encrypt string. * @param encryptName * -Encrypt tools,can be null or "",default SHA-256. * @author EX-ZHOUKAI003 * @date 2013.12.09 * **/ public static String encryptWithAny(String string, String encryptName) { MessageDigest md; StringBuffer sb = new StringBuffer(); if (StringUtils.isBlank(encryptName)) { encryptName = "SHA-256"; } try { md = MessageDigest.getInstance(encryptName); md.update(string.getBytes("UTF-8")); for (byte b : md.digest()) { sb.append(String.format("%02X", b)); } } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return sb.toString(); } }