AES加密

来源:互联网 发布:阿里云腾讯云对比报告 编辑:程序博客网 时间:2024/04/29 18:38


public class AESUtils {public final static String pwd = "1234567890";public static String encode(String in) {String hex = "";try {byte[] bytIn = in.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(pwd .getBytes(), "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] bytOut = cipher.doFinal(bytIn);hex = byte2hexString(bytOut);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return hex;}public static String decode(String hex)  {String rr = "";byte[] bytIn = hex2Bin(hex);SecretKeySpec skeySpec = new SecretKeySpec(pwd.getBytes(),"AES");Cipher cipher;try {cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] bytOut = cipher.doFinal(bytIn);rr = new String(bytOut, "utf-8");} catch (NoSuchAlgorithmException e1) {e1.printStackTrace();} catch (NoSuchPaddingException e1) {e1.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return rr;}private static byte[] hex2Bin(String src) {if (src.length() < 1)return null;byte[] encrypted = new byte[src.length() / 2];for (int i = 0; i < src.length() / 2; i++) {int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);encrypted[i] = (byte) (high * 16 + low);}return encrypted;}private static String byte2hexString(byte buf[]) {StringBuffer strbuf = new StringBuffer(buf.length * 2);int i;for (i = 0; i < buf.length; i++) {strbuf.append(Integer.toString((buf[i] >> 4) & 0xf, 16)+ Integer.toString(buf[i] & 0xf, 16));}return strbuf.toString();}}


0 0