001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.util; 018 019import java.lang.reflect.Method; 020 021import org.apache.logging.log4j.LoggingException; 022 023/** 024 * Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and 025 * the original method was removed in Java 9. 026 */ 027public final class Base64Util { 028 029 private static Method encodeMethod = null; 030 private static Object encoder = null; 031 032 static { 033 try { 034 Class<?> clazz = LoaderUtil.loadClass("java.util.Base64"); 035 Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder"); 036 Method method = clazz.getMethod("getEncoder"); 037 encoder = method.invoke(null); 038 encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class); 039 } catch (Exception ex) { 040 try { 041 Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter"); 042 encodeMethod = clazz.getMethod("printBase64Binary"); 043 } catch (Exception ex2) { 044 LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2); 045 } 046 } 047 } 048 049 private Base64Util() { 050 } 051 052 public static String encode(String str) { 053 if (str == null) { 054 return null; 055 } 056 byte [] data = str.getBytes(); 057 if (encodeMethod != null) { 058 try { 059 return (String) encodeMethod.invoke(encoder, data); 060 } catch (Exception ex) { 061 throw new LoggingException("Unable to encode String", ex); 062 } 063 } 064 throw new LoggingException("No Encoder, unable to encode string"); 065 } 066}