Java利用 AES/ECB/PKCS5Padding 算法加解密。
- package com.newland.njwpayment.utils;
-
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
-
- import Decoder.BASE64Decoder;
- import Decoder.BASE64Encoder;
-
-
-
-
-
-
- public class AESUtils {
-
-
-
-
- private static final String ALGORITHM = "AES";
-
-
-
- private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
-
-
-
-
- private SecretKeySpec key;
-
- public AESUtils(String hexKey) {
- key = new SecretKeySpec(hexKey.getBytes(), ALGORITHM);
- }
-
-
-
-
-
-
-
- public String encryptData(String data) throws Exception {
- Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
- cipher.init(Cipher.ENCRYPT_MODE, key);
- return new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
- }
-
-
-
-
-
-
-
- public String decryptData(String base64Data) throws Exception{
- Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
- cipher.init(Cipher.DECRYPT_MODE, key);
- return new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(base64Data)));
- }
-
-
-
-
-
-
- private static byte[] hex2byte(String s) {
- if (s.length() % 2 == 0) {
- return hex2byte (s.getBytes(), 0, s.length() >> 1);
- } else {
- return hex2byte("0"+s);
- }
- }
-
- private static byte[] hex2byte (byte[] b, int offset, int len) {
- byte[] d = new byte[len];
- for (int i=0; i<len*2; i++) {
- int shift = i%2 == 1 ? 0 : 4;
- d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift;
- }
- return d;
- }
-
- public static void main(String[] args) throws Exception {
- AESUtil util = new AESUtil("abcdefghijklmnop");
- System.out.println("cardNo:"+util.encryptData("1234"));
- System.out.println("exp:"+util.decryptData("34+Jzs4KkwaCQWVyyAgwLA=="));
- }
- }
其中,BASE64Decoder与BASE64Encoder这两个类可以通过Jre System Library下面的rt.jar找到,这里顺便提及一下,sun.misc.BASE64Encoder找不到jar包的两种解决方法:
1、直接添加JRE System Library,在Eclipse里面项目右击->Java build path->JRE System Library...
2、导入已提取封装好的jar包。下载地址:sun.misc.BASE64Decoder.jar 下载
另外,还需要注意的是,AES密钥一般是16个字节为一块,然后对这一整块进行加密,如果不够16个字节,就需要补位,也就是16字节对齐。