牛骨文教育服务平台(让学习变的简单)
博文笔记

Base64Utils

创建时间:2015-04-21 投稿人: 浏览次数:8372
import java.nio.charset.Charset;

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

public class Base64Utils {

    private static final Base64 BASE64 = new Base64();
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private static final String PREFIX = "XXXXX";

    public static String encode(String source) {
        if (!isEmpty(source)) {
            new Base64();
            String target = PREFIX + source;
            byte[] bytes = BASE64.encode(target.getBytes(DEFAULT_CHARSET));
            return new String(bytes, DEFAULT_CHARSET);
        }

        return source;
    }

    public static String decode(String source) {
        if (!isEmpty(source)) {
            byte[] bytes = BASE64.decode(source.getBytes(DEFAULT_CHARSET));
            String target = new String(bytes, DEFAULT_CHARSET);
            return target.startsWith(PREFIX) ? target.substring(PREFIX.length()) : target;
        }

        return source;
    }

    private static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static void main(String[] args) {
        String target = Base64Utils.encode("admin");
        System.out.println("encode : " + target);
        String source = Base64Utils.decode("WlRFSUNUbWF4eWFuZw==");
        System.out.println("source : " + source);
    }

}

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。