Base64加密解密工具类

使用Apache commons codec类Base64进行加密解密

maven依赖

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.6</version>
</dependency>

 

代码实现

package com.ljq.durian.common.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 *    Base64加密解密工具类
 *
 * @author jqlin
 */
public class Base64Util {
    private static final Logger logger = Logger.getLogger(Base64Util.class);
    private static final String charset = "utf-8";

    /**
     * 解密
     * 
     * @param data
     * @return
     * @author jqlin
     */
    public static String decode(String data) {
        try {
            if (null == data) {
                return null;
            }
            
            return new String(Base64.decodeBase64(data.getBytes(charset)), charset);
        } catch (UnsupportedEncodingException e) {
            logger.error(String.format("字符串:%s,解密异常", data), e);
        }

        return null;
    }

    /**
     * 加密
     * 
     * @param data
     * @return
     * @author jqlin
     */
    public static String encode(String data) {
        try {
            if (null == data) {
                return null;
            }
            return new String(Base64.encodeBase64(data.getBytes(charset)), charset);
        } catch (UnsupportedEncodingException e) {
            logger.error(String.format("字符串:%s,加密异常", data), e);
        }

        return null;
    }

}

 

posted on 2017-03-22 11:21  Ruthless  阅读(4418)  评论(0编辑  收藏  举报