一、前言
基于spring-core(4.1.4)对java.util.Base64.Encoder、java.util.Base64.Decoder基于Base64算法进行加解密操作,具体实现参考org.springframework.util.Base64Utils下面源码。
二、源码说明
1.Base64Utils,其中org.springframework.util.ClassUtils参考其他文章
package org.springframework.util;@b@@b@import java.nio.charset.Charset;@b@import java.util.Base64.Decoder;@b@import java.util.Base64.Encoder;@b@import org.springframework.lang.UsesJava8;@b@@b@public abstract class Base64Utils@b@{@b@ private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");@b@ private static final Base64Delegate delegate;@b@@b@ private static void assertSupported()@b@ {@b@ Assert.state(delegate != null, "Neither Java 8 nor Apache Commons Codec found - Base64 encoding not supported");@b@ }@b@@b@ public static byte[] encode(byte[] src)@b@ {@b@ assertSupported();@b@ return delegate.encode(src);@b@ }@b@@b@ public static String encodeToString(byte[] src)@b@ {@b@ assertSupported();@b@ if (src == null)@b@ return null;@b@@b@ if (src.length == 0)@b@ return "";@b@@b@ return new String(delegate.encode(src), DEFAULT_CHARSET);@b@ }@b@@b@ public static byte[] decode(byte[] src)@b@ {@b@ assertSupported();@b@ return delegate.decode(src);@b@ }@b@@b@ public static byte[] decodeFromString(String src)@b@ {@b@ assertSupported();@b@ if (src == null)@b@ return null;@b@@b@ if (src.length() == 0)@b@ return new byte[0];@b@@b@ return delegate.decode(src.getBytes(DEFAULT_CHARSET));@b@ }@b@@b@ static@b@ {@b@ Base64Delegate delegateToUse = null;@b@@b@ if (ClassUtils.isPresent("java.util.Base64", Base64Utils.class.getClassLoader())) {@b@ delegateToUse = new JdkBase64Delegate(null);@b@ }@b@ else if (ClassUtils.isPresent("org.apache.commons.codec.binary.Base64", Base64Utils.class.getClassLoader()))@b@ delegateToUse = new CommonsCodecBase64Delegate(null);@b@@b@ delegate = delegateToUse;@b@ }@b@@b@ private static class CommonsCodecBase64Delegate@b@ implements Base64Utils.Base64Delegate@b@ {@b@ private final org.apache.commons.codec.binary.Base64 base64;@b@@b@ private CommonsCodecBase64Delegate()@b@ {@b@ this.base64 = new org.apache.commons.codec.binary.Base64(); }@b@@b@ public byte[] encode(byte[] src) {@b@ return this.base64.encode(src);@b@ }@b@@b@ public byte[] decode(byte[] src) {@b@ return this.base64.decode(src);@b@ }@b@ }@b@@b@ @UsesJava8@b@ private static class JdkBase64Delegate@b@ implements Base64Utils.Base64Delegate@b@ {@b@ public byte[] encode(byte[] src)@b@ {@b@ if ((src == null) || (src.length == 0))@b@ return src;@b@@b@ return java.util.Base64.getEncoder().encode(src);@b@ }@b@@b@ public byte[] decode(byte[] src) {@b@ if ((src == null) || (src.length == 0))@b@ return src;@b@@b@ return java.util.Base64.getDecoder().decode(src);@b@ }@b@ }@b@@b@ private static abstract interface Base64Delegate@b@ {@b@ public abstract byte[] encode(byte[] paramArrayOfByte);@b@@b@ public abstract byte[] decode(byte[] paramArrayOfByte);@b@ }@b@}