Java Base64 加密 解密

时间:2020-05-21
本文章向大家介绍Java Base64 加密 解密,主要包括Java Base64 加密 解密使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

基于 java.util.Base64(java8以上)

package pink.isky.cactus.utils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @Author
 * @Date 2020/5/21 9:46
 */
public class Base64Util {

    public static String encodeStr(String str) {
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] textByte;
        String encodedText = null;
        try {
            textByte = str.getBytes("UTF-8");
            encodedText = encoder.encodeToString(textByte);
            return encodedText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedText;
    }

    public static String decodeStr(String encodedStr) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] textBytes = decoder.decode(encodedStr);
        String decodedStr = null;
        try {
            decodedStr = new String(textBytes,"UTF-8");
            return decodedStr;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return decodedStr;
    }

}

基于 org.apache.commons.codec.binary.Base64;

package pink.isky.cactus.utils;

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

import java.io.UnsupportedEncodingException;

/**
 * @Author
 * @Date 2020/5/21 10:05
 */
public class CodeUtil {

    public static String encodeText(String text) {
        Base64 base64 = new Base64();
        String encodedText = null;
        try {
            byte[] textByte = text.getBytes("UTF-8");
            encodedText = base64.encodeToString(textByte);
            return encodedText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedText;
    }

    public static String decodeText(String encodedText) {
        final Base64 base64 = new Base64();
        byte[] textByte = base64.decode(encodedText);
        String decodedText = null;
        try {
            decodedText = new String(textByte,"UTf-8");
            return decodedText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return decodedText;
    }

}

原文链接 https://www.cnblogs.com/alter888/p/9140732.html

原文地址:https://www.cnblogs.com/lovleo/p/12928959.html