package org.bouncycastle.gpg;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.bouncycastle.openpgp.OpenedPGPKeyData;
import org.bouncycastle.openpgp.PGPExtendedKeyHeader;
import org.bouncycastle.util.Strings;

/* JADX INFO: loaded from: classes3.dex */
public class PGPSecretKeyParser {
    private static void consumeUntil(InputStream inputStream, char c, ByteArrayOutputStream byteArrayOutputStream) throws IOException {
        byteArrayOutputStream.reset();
        while (true) {
            int i = inputStream.read();
            if (i <= -1 || i == c) {
                return;
            } else {
                byteArrayOutputStream.write(i);
            }
        }
    }

    public static boolean isExtendedSExpression(InputStream inputStream) throws IOException {
        if (!inputStream.markSupported()) {
            throw new IOException("input stream must support mark");
        }
        inputStream.mark(1);
        int i = inputStream.read();
        inputStream.reset();
        return i != 40;
    }

    private static int lastIndexOfWhitespace(String str) {
        if (str.length() == 0) {
            return -1;
        }
        for (int length = str.length() - 1; length >= 0; length--) {
            if (str.charAt(length) <= ' ') {
                return length;
            }
        }
        return -1;
    }

    public static OpenedPGPKeyData parse(InputStream inputStream, int i) throws IOException {
        OpenedPGPKeyData.Builder builder = OpenedPGPKeyData.builder();
        if (isExtendedSExpression(inputStream)) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            String strTrim = null;
            do {
                consumeUntil(inputStream, ':', byteArrayOutputStream);
                String strTrim2 = Strings.fromByteArray(byteArrayOutputStream.toByteArray()).trim();
                int iLastIndexOfWhitespace = lastIndexOfWhitespace(strTrim2);
                if (iLastIndexOfWhitespace == -1) {
                    strTrim = strTrim2;
                } else {
                    builder.add(new PGPExtendedKeyHeader(strTrim, strTrim2.substring(0, iLastIndexOfWhitespace)));
                    strTrim = strTrim2.substring(iLastIndexOfWhitespace).trim();
                }
            } while (!strTrim.equalsIgnoreCase("Key"));
        }
        builder.setKeyExpression(SExpression.parse(inputStream, i));
        return builder.build();
    }
}
