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
23
24
25
26
27 public final class Base64Util {
28
29 private static Method encodeMethod = null;
30 private static Object encoder = null;
31
32 static {
33 try {
34 Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
35 Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
36 Method method = clazz.getMethod("getEncoder");
37 encoder = method.invoke(null);
38 encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
39 } catch (Exception ex) {
40 try {
41 Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
42 encodeMethod = clazz.getMethod("printBase64Binary");
43 } catch (Exception ex2) {
44 LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2);
45 }
46 }
47 }
48
49 private Base64Util() {
50 }
51
52 public static String encode(String str) {
53 if (str == null) {
54 return null;
55 }
56 byte [] data = str.getBytes();
57 if (encodeMethod != null) {
58 try {
59 return (String) encodeMethod.invoke(encoder, data);
60 } catch (Exception ex) {
61 throw new LoggingException("Unable to encode String", ex);
62 }
63 }
64 throw new LoggingException("No Encoder, unable to encode string");
65 }
66 }