package com.ydtech.utils; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * 2021/6/4 **/ public class Base64Utils { /** * 判断图片base64字符串的文件格式 * * @param base64ImgData * @return */ public static String checkImageBase64Format(String base64ImgData) { byte[] b = base64ImgData.getBytes(); String type = ""; if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) { type = "bmp"; } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) { type = "png"; } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) { type = "jpg"; } else { type = "jpeg"; } return type; } // 加密 public static String getBase64Encode(String str) { byte[] b = null; String s = null; b = str.getBytes(StandardCharsets.UTF_8); s = Base64.getEncoder().encodeToString(b); // s = new BASE64Encoder().encode(b); return s; } // 解密 public static String getBase64Decode(String s) { byte[] b = null; String result = null; if (s != null) { // BASE64Decoder decoder = new BASE64Decoder(); try { // b = decoder.decodeBuffer(s); b = Base64.getDecoder().decode(s); result = new String(b, StandardCharsets.UTF_8); } catch (Exception e) { e.printStackTrace(); } } return result; } }