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.core.config.plugins.convert; 018 019import java.lang.reflect.InvocationTargetException; 020import java.lang.reflect.Method; 021 022import org.apache.logging.log4j.Logger; 023import org.apache.logging.log4j.status.StatusLogger; 024import org.apache.logging.log4j.util.LoaderUtil; 025 026/** 027 * @Since 2.9 028 */ 029public class Base64Converter { 030 031 private static final Logger LOGGER = StatusLogger.getLogger(); 032 private static Method method = null; 033 private static Object decoder = null; 034 035 static { 036 try { 037 // Base64 is available in Java 8 and up. 038 Class<?> clazz = LoaderUtil.loadClass("java.util.Base64"); 039 final Method getDecoder = clazz.getMethod("getDecoder", (Class[]) null); 040 decoder = getDecoder.invoke(null, (Object[]) null); 041 clazz = decoder.getClass(); 042 method = clazz.getMethod("decode", String.class); 043 } catch (final ClassNotFoundException ex) { 044 045 } catch (final NoSuchMethodException ex) { 046 047 } catch (final IllegalAccessException ex) { 048 049 } catch (final InvocationTargetException ex) { 050 051 } 052 if (method == null) { 053 try { 054 // DatatypeConverter is not in the default module in Java 9. 055 final Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DatatypeConverter"); 056 method = clazz.getMethod("parseBase64Binary", String.class); 057 } catch (final ClassNotFoundException ex) { 058 LOGGER.error("No Base64 Converter is available"); 059 } catch (final NoSuchMethodException ex) { 060 061 } 062 } 063 } 064 065 public static byte[] parseBase64Binary(final String encoded) { 066 if (method == null) { 067 LOGGER.error("No base64 converter"); 068 } else { 069 try { 070 return (byte[]) method.invoke(decoder, encoded); 071 } catch (final IllegalAccessException ex) { 072 LOGGER.error("Error decoding string - " + ex.getMessage()); 073 } catch (final InvocationTargetException ex) { 074 LOGGER.error("Error decoding string - " + ex.getMessage()); 075 } 076 } 077 return new byte[0]; 078 } 079}