1 package com.skynet.common; 2 3 import java.net.URLDecoder; 4 import java.net.URLEncoder; 5 import javax.crypto.Cipher; 6 import javax.crypto.spec.SecretKeySpec; 7 import org.apache.commons.codec.binary.Base64; 8 9 /** 10 * 11 * <p>Title: 天网HIS提供的加密要求实现类</p> 12 * <p>Description: </p> 13 * 14 * @author Torlay 15 * @version 1.00.00 16 * <pre> 17 * 修改记录: 18 * 版本号 修改人 修改日期 修改内容 19 * 20 * 21 */ 22 23 @SuppressWarnings("restriction") 24 public class EncryptUtil { 25 26 /** 27 * aes加密 28 * @param str 29 * @param key 30 * @return 31 * @throws Exception 32 */ 33 public static String aesEncrypt(String str, String key) throws Exception { 34 if (str == null || key == null) return null; 35 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 36 cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); 37 byte[] bytes = cipher.doFinal(str.getBytes("utf-8")); 38 //注意不要采用,会出现回车换行 new BASE64Encoder().encode(bytes); 39 return Base64.encodeBase64String(bytes); 40 } 41 42 /** 43 * aes解密 44 * @param str 45 * @param key 46 * @return 47 * @throws Exception 48 */ 49 public static String aesDecrypt(String str, String key) throws Exception { 50 if (str == null || key == null) return null; 51 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 52 cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); 53 byte[] bytes = Base64.decodeBase64(str); 54 bytes = cipher.doFinal(bytes); 55 return new String(bytes, "utf-8"); 56 } 57 58 59 public static void main(String[] args) { 60 String content = "{'cardID':'000064755961172','modeType':'1','money':'1000','serialNumber':'1011010000'}"; 61 System.out.println("加密前:" + content); 62 63 String key = "YF}+efcaj{+oESb9"; 64 System.out.println("加密密钥和解密密钥:" + key); 65 66 try { 67 String encrypt = aesEncrypt(content, key); 68 System.out.println("加密后:" + encrypt); 69 70 System.out.println(URLEncoder.encode(encrypt)); 71 72 System.out.println(URLDecoder.decode(encrypt)); 73 74 String decrypt = aesDecrypt(encrypt, key); 75 System.out.println("解密后:" + decrypt); 76 } catch (Exception e) { 77 // TODO Auto-generated catch block 78 e.printStackTrace(); 79 } 80 } 81 }
加密工具类