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; 022import org.apache.logging.log4j.status.StatusLogger; 023 024/** 025 * Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and 026 * the original method was removed in Java 9. 027 */ 028public final class Base64Util { 029 030 private static Method encodeMethod = null; 031 private static Object encoder = null; 032 033 static { 034 try { 035 Class<?> clazz = LoaderUtil.loadClass("java.util.Base64"); 036 Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder"); 037 Method method = clazz.getMethod("getEncoder"); 038 encoder = method.invoke(null); 039 encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class); 040 } catch (Exception ex) { 041 try { 042 Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter"); 043 encodeMethod = clazz.getMethod("printBase64Binary"); 044 } catch (Exception ex2) { 045 LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2); 046 } 047 } 048 } 049 050 private Base64Util() { 051 } 052 053 public static String encode(String str) { 054 if (str == null) { 055 return null; 056 } 057 byte [] data = str.getBytes(); 058 if (encodeMethod != null) { 059 try { 060 return (String) encodeMethod.invoke(encoder, data); 061 } catch (Exception ex) { 062 throw new LoggingException("Unable to encode String", ex); 063 } 064 } 065 throw new LoggingException("No Encoder, unable to encode string"); 066 } 067}