package org.bouncycastle.gpg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPExtendedKeyAttribute;
import org.bouncycastle.openpgp.PGPRuntimeOperationException;
import org.bouncycastle.util.Characters;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.io.Streams;

/* JADX INFO: loaded from: classes3.dex */
public class SExpression {
    private static final Set<Character> labelStop = new HashSet<Character>() { // from class: org.bouncycastle.gpg.SExpression.1
        {
            add(Characters.valueOf(' '));
            add(Characters.valueOf(')'));
            add(Characters.valueOf('('));
            add(Characters.valueOf('#'));
            add(Characters.valueOf('\"'));
            add(Characters.valueOf(':'));
        }
    };
    private static final Set<String> stringLabels = new HashSet<String>() { // from class: org.bouncycastle.gpg.SExpression.2
        {
            add("protected");
            add("protected-at");
            add("curve");
        }
    };
    private final ArrayList<Object> values = new ArrayList<>();
    private boolean canonical = false;
    private boolean parseCanonical = false;

    /* JADX INFO: loaded from: classes2.dex */
    public static class Builder {
        List<Object> values = new ArrayList();

        public Builder addContent(SExpression sExpression) {
            Iterator it = sExpression.values.iterator();
            while (it.hasNext()) {
                this.values.add(it.next());
            }
            return this;
        }

        public Builder addValue(Object obj) {
            this.values.add(obj);
            return this;
        }

        public SExpression build() {
            return new SExpression(this.values);
        }
    }

    public static class QuotedString {
        private final String value;

        public QuotedString(String str) {
            this.value = str;
        }

        public String toString() {
            return this.value;
        }
    }

    public SExpression() {
    }

    public SExpression(List<Object> list) {
        this.values.addAll(list);
    }

    static SExpression buildExpression(SExpression sExpression, SExpression sExpression2, String[] strArr) {
        SExpression sExpression3 = new SExpression();
        sExpression3.addValue(strArr[0]);
        for (int i = 1; i < strArr.length; i++) {
            SExpression expressionWithLabel = sExpression.getExpressionWithLabel(strArr[i]);
            if (expressionWithLabel != null || (expressionWithLabel = sExpression2.getExpressionWithLabel(strArr[i])) != null) {
                sExpression3.values.add(expressionWithLabel);
            }
        }
        return sExpression3;
    }

    static SExpression buildExpression(SExpression sExpression, String[] strArr) {
        SExpression sExpression2 = new SExpression();
        sExpression2.addValue(strArr[0]);
        for (int i = 1; i < strArr.length; i++) {
            SExpression expressionWithLabel = sExpression.getExpressionWithLabel(strArr[i]);
            if (expressionWithLabel != null) {
                sExpression2.values.add(expressionWithLabel);
            }
        }
        return sExpression2;
    }

    public static Builder builder() {
        return new Builder();
    }

    private static int consumeUntilSkipCRorLF(InputStream inputStream, ByteArrayOutputStream byteArrayOutputStream, char c) throws IOException {
        byteArrayOutputStream.reset();
        while (true) {
            boolean z = false;
            while (true) {
                int i = inputStream.read();
                if (i <= -1) {
                    return -1;
                }
                if (!z || i > 32) {
                    if (i == 10) {
                        z = true;
                    } else {
                        if (c == i) {
                            return i;
                        }
                        byteArrayOutputStream.write(i);
                    }
                }
            }
        }
    }

    private static int consumeUntilSkipCRorLF(InputStream inputStream, ByteArrayOutputStream byteArrayOutputStream, Set<Character> set) throws IOException {
        byteArrayOutputStream.reset();
        while (true) {
            boolean z = false;
            while (true) {
                int i = inputStream.read();
                if (i <= -1) {
                    return -1;
                }
                if (!z || i > 32) {
                    if (i == 10) {
                        z = true;
                    } else {
                        if (set.contains(Characters.valueOf((char) i))) {
                            return i;
                        }
                        byteArrayOutputStream.write(i);
                    }
                }
            }
        }
    }

    private static void consumeUntilSkipWhiteSpace(InputStream inputStream, ByteArrayOutputStream byteArrayOutputStream, char c) throws IOException {
        byteArrayOutputStream.reset();
        while (true) {
            int i = inputStream.read();
            if (i <= -1) {
                return;
            }
            if (i > 32) {
                if (i == c) {
                    return;
                } else {
                    byteArrayOutputStream.write(i);
                }
            }
        }
    }

    public static SExpression parse(InputStream inputStream, int i) throws IOException {
        return parseExpression(inputStream, null, new ByteArrayOutputStream(), i);
    }

    public static SExpression parse(byte[] bArr, int i) throws IOException {
        return parse(new ByteArrayInputStream(bArr), i);
    }

    static SExpression parseCanonical(InputStream inputStream, int i) throws IOException {
        SExpression sExpression = new SExpression();
        sExpression.parseCanonical = true;
        return parseExpression(inputStream, sExpression, new ByteArrayOutputStream(), i).getExpression(0);
    }

    /* JADX WARN: Code duplicated, block: B:17:0x0048 A[Catch: all -> 0x0058, NumberFormatException -> 0x005a, TryCatch #2 {NumberFormatException -> 0x005a, blocks: (B:9:0x0017, B:11:0x002c, B:13:0x0034, B:15:0x0040, B:18:0x004c, B:17:0x0048, B:19:0x0050), top: B:59:0x0017 }] */
    private static SExpression parseExpression(InputStream inputStream, SExpression sExpression, ByteArrayOutputStream byteArrayOutputStream, int i) throws IOException {
        Object byteArray;
        Object objFromUTF8ByteArray;
        if (byteArrayOutputStream == null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
        }
        int i2 = i - 1;
        if (i2 < 0) {
            throw new IllegalStateException("S-Expression exceeded maximum depth");
        }
        while (true) {
            int iConsumeUntilSkipCRorLF = consumeUntilSkipCRorLF(inputStream, byteArrayOutputStream, labelStop);
            if (iConsumeUntilSkipCRorLF != 58) {
                if (byteArrayOutputStream.size() > 0) {
                    if (sExpression == null) {
                        throw new IOException("invalid input stream");
                    }
                    sExpression.addValue(Strings.fromByteArray(byteArrayOutputStream.toByteArray()));
                }
                if (iConsumeUntilSkipCRorLF == 40) {
                    if (sExpression == null) {
                        SExpression sExpression2 = new SExpression();
                        parseExpression(inputStream, sExpression2, byteArrayOutputStream, i2);
                        return sExpression2;
                    }
                    SExpression sExpression3 = new SExpression();
                    sExpression3.parseCanonical = sExpression.parseCanonical;
                    byteArray = parseExpression(inputStream, sExpression3, byteArrayOutputStream, i2);
                } else if (iConsumeUntilSkipCRorLF == 35) {
                    if (sExpression == null) {
                        throw new IOException("invalid input stream at '#'");
                    }
                    consumeUntilSkipWhiteSpace(inputStream, byteArrayOutputStream, '#');
                    sExpression.addValue(Hex.decode(byteArrayOutputStream.toByteArray()));
                } else if (iConsumeUntilSkipCRorLF == 34) {
                    if (sExpression == null) {
                        throw new IOException("invalid input stream at '\"'");
                    }
                    consumeUntilSkipCRorLF(inputStream, byteArrayOutputStream, '\"');
                    byteArray = new QuotedString(Strings.fromByteArray(byteArrayOutputStream.toByteArray()));
                } else if (iConsumeUntilSkipCRorLF == 41 || iConsumeUntilSkipCRorLF == -1) {
                    return sExpression;
                }
                sExpression.addValue(byteArray);
            } else {
                if (sExpression == null) {
                    throw new IOException("invalid input stream at ':'");
                }
                try {
                    byte[] bArr = new byte[Integer.parseInt(Strings.fromByteArray(byteArrayOutputStream.toByteArray()))];
                    Streams.readFully(inputStream, bArr);
                    if (sExpression.parseCanonical) {
                        int size = sExpression.values.size();
                        if (size > 0) {
                            Object obj = sExpression.values.get(size - 1);
                            objFromUTF8ByteArray = bArr;
                            if (obj instanceof String) {
                                objFromUTF8ByteArray = bArr;
                                if (stringLabels.contains(obj)) {
                                    objFromUTF8ByteArray = Strings.fromUTF8ByteArray(bArr);
                                }
                            }
                        } else {
                            objFromUTF8ByteArray = Strings.fromUTF8ByteArray(bArr);
                        }
                        sExpression.addValue(objFromUTF8ByteArray);
                    } else {
                        sExpression.addValue(bArr);
                        sExpression.setCanonical(true);
                    }
                } catch (NumberFormatException e) {
                    byteArray = byteArrayOutputStream.toByteArray();
                    sExpression.addValue(byteArray);
                }
            }
        }
    }

    private void setCanonical(boolean z) {
        this.canonical = z;
    }

    public void addValue(Object obj) {
        this.values.add(obj);
    }

    public SExpression filterIn(String... strArr) {
        HashSet hashSet = new HashSet();
        hashSet.addAll(Arrays.asList(strArr));
        SExpression sExpression = new SExpression();
        for (Object obj : this.values) {
            if (obj instanceof SExpression) {
                SExpression sExpression2 = (SExpression) obj;
                if (sExpression2.values.isEmpty() || hashSet.contains(sExpression2.values.get(0).toString())) {
                    sExpression.values.add(obj);
                }
            } else if (hashSet.contains(obj.toString())) {
                sExpression.values.add(obj);
            }
        }
        return sExpression;
    }

    public SExpression filterOut(String... strArr) {
        ArrayList<Object> arrayList;
        HashSet hashSet = new HashSet();
        hashSet.addAll(Arrays.asList(strArr));
        SExpression sExpression = new SExpression();
        for (Object objFilterOut : this.values) {
            if (!hashSet.contains(objFilterOut.toString())) {
                if (objFilterOut instanceof SExpression) {
                    SExpression sExpression2 = (SExpression) objFilterOut;
                    if (sExpression2.values.isEmpty() || !hashSet.contains(sExpression2.values.get(0).toString())) {
                        arrayList = sExpression.values;
                        objFilterOut = sExpression2.filterOut(strArr);
                    }
                } else {
                    arrayList = sExpression.values;
                }
                arrayList.add(objFilterOut);
            }
        }
        return sExpression;
    }

    public byte[] getBytes(int i) {
        return (byte[]) this.values.get(i);
    }

    public SExpression getExpression(int i) {
        return (SExpression) this.values.get(i);
    }

    public SExpression getExpressionWithLabel(String str) {
        for (Object obj : this.values) {
            if (obj instanceof SExpression) {
                SExpression sExpression = (SExpression) obj;
                if (sExpression.hasLabel(str)) {
                    return sExpression;
                }
            }
        }
        return null;
    }

    public SExpression getExpressionWithLabelOrFail(String str) {
        for (Object obj : this.values) {
            if (obj instanceof SExpression) {
                SExpression sExpression = (SExpression) obj;
                if (sExpression.hasLabel(str)) {
                    return sExpression;
                }
            }
        }
        throw new IllegalArgumentException("label " + str + " was not found");
    }

    public int getInt(int i) {
        return Integer.parseInt(getString(i));
    }

    public String getString(int i) {
        Object obj = this.values.get(i);
        return obj instanceof byte[] ? Strings.fromUTF8ByteArray((byte[]) obj) : this.values.get(i).toString();
    }

    public Object getValue(int i) {
        return this.values.get(i);
    }

    public List<Object> getValues() {
        return this.values;
    }

    public boolean hasLabel(String str) {
        if (this.values.isEmpty()) {
            throw new IllegalArgumentException("S-Expression is empty");
        }
        Object obj = this.values.get(0);
        return (((obj instanceof String) || (obj instanceof QuotedString)) ? obj.toString() : Strings.fromByteArray((byte[]) obj)).equals(str);
    }

    public boolean isCanonical() {
        return this.canonical;
    }

    public PGPExtendedKeyAttribute toAttribute() {
        PGPExtendedKeyAttribute.Builder builder = PGPExtendedKeyAttribute.builder();
        Iterator<Object> it = this.values.iterator();
        while (it.hasNext()) {
            builder.addAttribute(it.next());
        }
        return builder.build();
    }

    public void toCanonicalForm(OutputStream outputStream) throws IOException {
        outputStream.write(40);
        for (Object obj : this.values) {
            if (obj instanceof QuotedString) {
                String str = ((QuotedString) obj).value;
                outputStream.write(Strings.toByteArray(Integer.toString(str.length())));
                outputStream.write(58);
                outputStream.write(Strings.toUTF8ByteArray(str));
            } else if (obj instanceof String) {
                String str2 = (String) obj;
                outputStream.write(Strings.toByteArray(Integer.toString(str2.length())));
                outputStream.write(58);
                outputStream.write(Strings.toUTF8ByteArray(str2));
            } else if (obj instanceof byte[]) {
                byte[] bArr = (byte[]) obj;
                outputStream.write(Strings.toByteArray(Integer.toString(bArr.length)));
                outputStream.write(58);
                outputStream.write(bArr);
            } else {
                if (!(obj instanceof SExpression)) {
                    throw new IllegalStateException("unhandled type " + obj.getClass().getName() + " in value list");
                }
                ((SExpression) obj).toCanonicalForm(outputStream);
            }
        }
        outputStream.write(41);
        outputStream.flush();
    }

    public byte[] toCanonicalForm() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            toCanonicalForm(byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new PGPRuntimeOperationException(e.getMessage(), e);
        }
    }
}
