001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package org.pgpainless.util;
006
007import java.io.BufferedInputStream;
008import java.io.IOException;
009import java.io.InputStream;
010
011import org.bouncycastle.openpgp.PGPUtil;
012
013public final class PGPUtilWrapper {
014
015    private PGPUtilWrapper() {
016
017    }
018
019    /**
020     * {@link PGPUtil#getDecoderStream(InputStream)} sometimes mistakens non-base64 data for base64 encoded data.
021     *
022     * This method expects a {@link BufferedInputStream} which is being reset in case an {@link IOException} is encountered.
023     * Therefore, we can properly handle non-base64 encoded data.
024     *
025     * @param buf buffered input stream
026     * @return input stream
027     * @throws IOException in case of an io error which is unrelated to base64 encoding
028     */
029    public static InputStream getDecoderStream(BufferedInputStream buf) throws IOException {
030        buf.mark(512);
031        try {
032            return PGPUtil.getDecoderStream(buf);
033        } catch (IOException e) {
034            if (e.getMessage().contains("invalid characters encountered at end of base64 data")) {
035                buf.reset();
036                return buf;
037            }
038            throw e;
039        }
040    }
041}