1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.util;
18
19 import java.lang.reflect.Method;
20
21 import org.apache.logging.log4j.LoggingException;
22 import org.apache.logging.log4j.status.StatusLogger;
23
24
25
26
27
28 public final class Base64Util {
29
30 private static Method encodeMethod = null;
31 private static Object encoder = null;
32
33 static {
34 try {
35 Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
36 Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
37 Method method = clazz.getMethod("getEncoder");
38 encoder = method.invoke(null);
39 encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
40 } catch (Exception ex) {
41 try {
42 Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
43 encodeMethod = clazz.getMethod("printBase64Binary");
44 } catch (Exception ex2) {
45 LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2);
46 }
47 }
48 }
49
50 private Base64Util() {
51 }
52
53 public static String encode(String str) {
54 if (str == null) {
55 return null;
56 }
57 byte [] data = str.getBytes();
58 if (encodeMethod != null) {
59 try {
60 return (String) encodeMethod.invoke(encoder, data);
61 } catch (Exception ex) {
62 throw new LoggingException("Unable to encode String", ex);
63 }
64 }
65 throw new LoggingException("No Encoder, unable to encode string");
66 }
67 }