加密解密-AesUtil

AesUitl方法01:

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * AES工具
 */
public class AesUtil {
    private final static String secretKey = "s2_I$-!#eu_3y2*4D-8^2{A3R_E}I5%&U#I@-O;!";
    private final static String encoding = "UTF-8";
    /**
     * AES加密为base 64 code
     * 
     * @param content
     *            待加密的内容
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content) throws Exception {
        return encryptAES(content, secretKey);
    }
    /**
     * 将base 64 code AES解密
     * 
     * @param encryptStr
     *            待解密的base 64 code
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, secretKey);
    }
    /**
     * AES加密
     * 
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String encryptAES(String content, String password)
            throws Exception {
        byte[] encryptResult = encrypt(content, password);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        // BASE64位加密
        encryptResultStr = ebotongEncrypto(encryptResultStr);
        return encryptResultStr;
    }
    /**
     * AES解密
     * 
     * @param encryptResultStr
     * @param password
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptResultStr, String password)
            throws Exception {
        // BASE64位解密
        String decrpt = ebotongDecrypto(encryptResultStr);
        byte[] decryptFrom = parseHexStr2Byte(decrpt);
        byte[] decryptResult = decrypt(decryptFrom, password);
        return new String(decryptResult);
    }
    /**
     * AES解密
     * 
     * @param encryptResultStr
     * @param password
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptResultStr) throws Exception {
        // BASE64位解密
        String decrpt = ebotongDecrypto(encryptResultStr);
        byte[] decryptFrom = parseHexStr2Byte(decrpt);
        byte[] decryptResult = decrypt(decryptFrom, secretKey);
        return new String(decryptResult);
    }
    /**
     * 加密字符串
     */
    public static String ebotongEncrypto(String str) {
        BASE64Encoder base64encoder = new BASE64Encoder();
        String result = str;
        if (str != null && str.length() > 0) {
            try {
                byte[] encodeByte = str.getBytes(encoding);
                result = base64encoder.encode(encodeByte);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // base64加密超过一定长度会自动换行 需要去除换行符
        return result.replaceAll("\r\n", "").replaceAll("\r", "")
                .replaceAll("\n", "");
    }
    /**
     * 解密字符串
     */
    public static String ebotongDecrypto(String str) throws Exception {
        BASE64Decoder base64decoder = new BASE64Decoder();
        byte[] encodeByte = base64decoder.decodeBuffer(str);
        return new String(encodeByte, encoding);
    }
    /**
     * 加密
     * 
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    private static byte[] encrypt(String content, String password)
            throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);
        // kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        byte[] byteContent = content.getBytes(encoding);
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }
    /**
     * 解密
     * 
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    private static byte[] decrypt(byte[] content, String password)
            throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);
        // kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    }
    /**
     * 将二进制转换成16进制
     * 
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    /**
     * 将16进制转换为二进制
     * 
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        // String content = Calendar.getInstance().getTimeInMillis();
        // System.out.println(aesEncrypt(content));
        // System.out.println(aesDecrypt(aesEncrypt(content)));
        // Thread.sleep(100);
        // content = Calendar.getInstaance().getTime().toLocaleString();
        // System.out.println(aesEncrypt(content));
        // System.out.println(aesDecrypt(aesEncrypt(content)));
        System.out.println(aesEncrypt("1234567890"));
        System.out.println(aesDecrypt( "RTEwN0NGMDE4MjExOTM2QTJGMzJFQjA1NkVDQzlGREQ=") );
    }
}

AesUitl方法02:import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;当加密解密失败时,猜测是因为导入文件内容不一样,改为第三种方法;

import java.security.SecureRandom;
import java.util.Calendar;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * AES工具
 */
public class AesUtil {
    private final static String encoding = "UTF-8";
    private static String PASSWORD = "s2_I$-!#eu_3y2*4D-8^2{A3R_E}I5%&U#I@-O;!";
    // static {
    // ResourceBundle resource = ResourceBundle.getBundle("config");
    // PASSWORD = resource.getString("PASSWORD");
    // }
    /**
     * AES加密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String aesEncrypt(String content) throws Exception {
        byte[] encryptResult = encrypt(content);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        // BASE64位加密
        encryptResultStr = ebotongEncrypto(encryptResultStr);
        return encryptResultStr;
    }
    /**
     * AES解密
     * 
     * @Author 科帮网
     * @param encryptResultStr
     * @param password
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String aesDecrypt(String encryptResultStr) throws Exception {
        // BASE64位解密
        String decrpt = ebotongDecrypto(encryptResultStr);
        byte[] decryptFrom = parseHexStr2Byte(decrpt);
        byte[] decryptResult = decrypt(decryptFrom);
        return new String(decryptResult);
    }
    /**
     * 加密字符串
     * 
     * @Author 科帮网
     * @param str
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String ebotongEncrypto(String str) throws Exception {
        BASE64Encoder base64encoder = new BASE64Encoder();
        String result = str;
        if (str != null && str.length() > 0) {
            byte[] encodeByte = str.getBytes(encoding);
            result = base64encoder.encode(encodeByte);
        }
        // base64加密超过一定长度会自动换行 需要去除换行符
        return result.replaceAll("\r\n", "").replaceAll("\r", "")
                .replaceAll("\n", "");
    }
    /**
     * 解密字符串
     * 
     * @Author 科帮网
     * @param str
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String ebotongDecrypto(String str) throws Exception {
        BASE64Decoder base64decoder = new BASE64Decoder();
        byte[] encodeByte = base64decoder.decodeBuffer(str);
        return new String(encodeByte);
    }
    /**
     * 加密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    private static byte[] encrypt(String content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }
    /**
     * 解密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    private static byte[] decrypt(byte[] content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    }
    /**
     * 将二进制转换成16进制
     * 
     * @Author 科帮网
     * @param buf
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    /**
     * 将16进制转换为二进制
     * 
     * @Author 科帮网
     * @param hexStr
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        String member = "CAT0001";
        String content = String.valueOf(Calendar.getInstance()
                .getTimeInMillis());
        String token = member + "," + content;
        System.out.println(aesEncrypt(token));
        System.out.println(aesDecrypt(aesEncrypt(token)));
    }
}

AesUitl方法03:import org.apache.commons.codec.binary.Base64;

commons-codec-1.9.jar  可以用就好,我的jar(http://pan.baidu.com/s/1geZndCJ)

import java.security.SecureRandom;
import java.util.Calendar;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
 * AES工具
 */
public class AesUtil {
    private final static String encoding = "UTF-8";
    private static String PASSWORD = "s2_I$-!#eu_3y2*4D-8^2{A3R_E}I5%&U#I@-O;!";
    // static {
    // ResourceBundle resource = ResourceBundle.getBundle("config");
    // PASSWORD = resource.getString("PASSWORD");
    // }
    /**
     * AES加密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String aesEncrypt(String content) throws Exception {
        byte[] encryptResult = encrypt(content);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        // BASE64位加密
        encryptResultStr = ebotongEncrypto(encryptResultStr);
        return encryptResultStr;
    }
    /**
     * AES解密
     * 
     * @Author 科帮网
     * @param encryptResultStr
     * @param password
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String aesDecrypt(String encryptResultStr) throws Exception {
        // BASE64位解密
        String decrpt = ebotongDecrypto(encryptResultStr);
        byte[] decryptFrom = parseHexStr2Byte(decrpt);
        byte[] decryptResult = decrypt(decryptFrom);
        return new String(decryptResult);
    }
    /**
     * 加密字符串
     * 
     * @Author 科帮网
     * @param str
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String ebotongEncrypto(String str) throws Exception {
        String result = str;
        if (str != null && str.length() > 0) {
            byte[] encodeByte = str.getBytes(encoding);
            byte[] debytes = Base64.encodeBase64Chunked(encodeByte);
            return new String(debytes);
        }
        // base64加密超过一定长度会自动换行 需要去除换行符
        return result.replaceAll("\r\n", "").replaceAll("\r", "")
                .replaceAll("\n", "");
    }
    /**
     * 解密字符串
     * 
     * @Author 科帮网
     * @param str
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String ebotongDecrypto(String str) throws Exception {
        byte[] encodeByte = Base64.decodeBase64(str);
        return new String(encodeByte);
    }
    /**
     * 加密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    private static byte[] encrypt(String content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }
    /**
     * 解密
     * 
     * @Author 科帮网
     * @param content
     * @param password
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    private static byte[] decrypt(byte[] content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    }
    /**
     * 将二进制转换成16进制
     * 
     * @Author 科帮网
     * @param buf
     * @return String
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    /**
     * 将16进制转换为二进制
     * 
     * @Author 科帮网
     * @param hexStr
     * @return byte[]
     * @Date 2015年2月7日 更新日志 2015年2月7日 科帮网 首次创建
     * 
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        String me = "CAT0001";
        String content = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String token = me + "," + content;
        token = "CAT0001,1478842909958";
        System.out.println("加密字符:" + token);
        System.out.println("加密后的字符:" + aesEncrypt(token));
        System.out.println("解密后的字符:" + aesDecrypt(aesEncrypt(token)));
        System.out.println("加密后的字符:MkYxMTc4QzQ5NjI0NUZGMzhDNzhGMzlDMDMzMDAyODUwNUZGRUQ4RkMyMzE2QzREREQyODU2RTVG加密后的字符:MkYxMTc4QzQ5NjI0NUZGMzhDNzhGMzlDMDMzMDAyODUwNUZGRUQ4RkMyMzE2QzREREQyODU2RTVG");
    }
}

希望对你有帮助,祝你有一个好心情,加油!

若有错误、不全、可优化的点,欢迎纠正与补充;转载请注明出处!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值