package com.dcit.common.utils;

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

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Base64Util {
	
	/**
	 * Base64编码
	 * @param str
	 * @return
	 */
	public static String StringEncoder(String str){
		Base64.Encoder encoder = Base64.getEncoder();
		String encodedText = null;
		try {
			byte[] textByte = str.getBytes("UTF-8");
			//编码
			encodedText = encoder.encodeToString(textByte);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("【Base64编码失败】str={}",str);
		}
		return encodedText;
	}
	
	/**
	 * Base64解码
	 * @param str
	 * @return
	 */
	public static String StringDecoder(String encodedStr){
		
		Base64.Decoder decoder = Base64.getDecoder();
		String decoderStr = null;
		try {
			byte[] textByte = decoder.decode(encodedStr);
			//解码
			decoderStr = new String(textByte, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("【Base64解码失败】encodedStr={}",encodedStr);
		}
		return decoderStr;
	}
	
	
	public static void main(String[] args) throws UnsupportedEncodingException{
		final Base64.Decoder decoder = Base64.getDecoder();
		final Base64.Encoder encoder = Base64.getEncoder();
		final String text = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJuYmYiOjE1NjI0NzkyMjEsInJvbGVzIjpudWxsLCJleHAiOjE1NjI0ODY0MjEsInVzZXJJZCI6IjEyMDQ1OTAwMDUiLCJpYXQiOjE1NjI0NzkyMjF9.vFFJbUB1Zcku9UkUL2J_XipRrnfLvkxSZDrhq977jXrS0KPlLuuZsG51BoXvqsM3m-E8TGOAYdQviqfb8EZnGw";
		final byte[] textByte = text.getBytes("UTF-8");
		//编码
		final String encodedText = encoder.encodeToString(textByte);
		System.out.println(encodedText);
		//解码
		System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
	}

}
