package com.revenuecat.purchases.common.verification;

import E3.v;
import S4.a;
import S4.p;
import android.util.Base64;
import com.revenuecat.purchases.LogHandler;
import com.revenuecat.purchases.LogLevel;
import com.revenuecat.purchases.PurchasesError;
import com.revenuecat.purchases.VerificationResult;
import com.revenuecat.purchases.common.AppConfig;
import com.revenuecat.purchases.common.Config;
import com.revenuecat.purchases.common.Constants;
import com.revenuecat.purchases.common.LogWrapperKt;
import com.revenuecat.purchases.common.networking.Endpoint;
import com.revenuecat.purchases.strings.NetworkStrings;
import com.revenuecat.purchases.utils.Result;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import kotlin.jvm.internal.h;
import kotlin.jvm.internal.o;
import q.AbstractC2761L;
import w4.C3137A;
import w4.k;
import x4.AbstractC3250p;
import x4.AbstractC3251q;
import x4.AbstractC3252r;
import x4.AbstractC3253s;

/* JADX INFO: loaded from: classes3.dex */
public final class SigningManager {
    private static final Companion Companion = new Companion(null);

    @Deprecated
    public static final int NONCE_BYTES_SIZE = 12;

    @Deprecated
    public static final String POST_PARAMS_ALGORITHM = "sha256";

    @Deprecated
    public static final byte POST_PARAMS_SEPARATOR = 0;
    private final String apiKey;
    private final AppConfig appConfig;
    private final SignatureVerificationMode signatureVerificationMode;

    public static final class Companion {
        public /* synthetic */ Companion(h hVar) {
            this();
        }

        private Companion() {
        }
    }

    public static final class Parameters {
        private final String apiKey;
        private final String body;
        private final String eTag;
        private final String nonce;
        private final String postParamsHashHeader;
        private final String requestTime;
        private final byte[] salt;
        private final String urlPath;

        public Parameters(byte[] salt, String apiKey, String str, String urlPath, String str2, String requestTime, String str3, String str4) {
            o.h(salt, "salt");
            o.h(apiKey, "apiKey");
            o.h(urlPath, "urlPath");
            o.h(requestTime, "requestTime");
            this.salt = salt;
            this.apiKey = apiKey;
            this.nonce = str;
            this.urlPath = urlPath;
            this.postParamsHashHeader = str2;
            this.requestTime = requestTime;
            this.eTag = str3;
            this.body = str4;
        }

        public static /* synthetic */ Parameters copy$default(Parameters parameters, byte[] bArr, String str, String str2, String str3, String str4, String str5, String str6, String str7, int i6, Object obj) {
            if ((i6 & 1) != 0) {
                bArr = parameters.salt;
            }
            if ((i6 & 2) != 0) {
                str = parameters.apiKey;
            }
            if ((i6 & 4) != 0) {
                str2 = parameters.nonce;
            }
            if ((i6 & 8) != 0) {
                str3 = parameters.urlPath;
            }
            if ((i6 & 16) != 0) {
                str4 = parameters.postParamsHashHeader;
            }
            if ((i6 & 32) != 0) {
                str5 = parameters.requestTime;
            }
            if ((i6 & 64) != 0) {
                str6 = parameters.eTag;
            }
            if ((i6 & 128) != 0) {
                str7 = parameters.body;
            }
            String str8 = str6;
            String str9 = str7;
            String str10 = str4;
            String str11 = str5;
            return parameters.copy(bArr, str, str2, str3, str10, str11, str8, str9);
        }

        public final byte[] component1() {
            return this.salt;
        }

        public final String component2() {
            return this.apiKey;
        }

        public final String component3() {
            return this.nonce;
        }

        public final String component4() {
            return this.urlPath;
        }

        public final String component5() {
            return this.postParamsHashHeader;
        }

        public final String component6() {
            return this.requestTime;
        }

        public final String component7() {
            return this.eTag;
        }

        public final String component8() {
            return this.body;
        }

        public final Parameters copy(byte[] salt, String apiKey, String str, String urlPath, String str2, String requestTime, String str3, String str4) {
            o.h(salt, "salt");
            o.h(apiKey, "apiKey");
            o.h(urlPath, "urlPath");
            o.h(requestTime, "requestTime");
            return new Parameters(salt, apiKey, str, urlPath, str2, requestTime, str3, str4);
        }

        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!Parameters.class.equals(obj != null ? obj.getClass() : null)) {
                return false;
            }
            o.f(obj, "null cannot be cast to non-null type com.revenuecat.purchases.common.verification.SigningManager.Parameters");
            Parameters parameters = (Parameters) obj;
            return Arrays.equals(this.salt, parameters.salt) && o.c(this.apiKey, parameters.apiKey) && o.c(this.nonce, parameters.nonce) && o.c(this.urlPath, parameters.urlPath) && o.c(this.postParamsHashHeader, parameters.postParamsHashHeader) && o.c(this.requestTime, parameters.requestTime) && o.c(this.eTag, parameters.eTag) && o.c(this.body, parameters.body);
        }

        public final String getApiKey() {
            return this.apiKey;
        }

        public final String getBody() {
            return this.body;
        }

        public final String getETag() {
            return this.eTag;
        }

        public final String getNonce() {
            return this.nonce;
        }

        public final String getPostParamsHashHeader() {
            return this.postParamsHashHeader;
        }

        public final String getRequestTime() {
            return this.requestTime;
        }

        public final byte[] getSalt() {
            return this.salt;
        }

        public final String getUrlPath() {
            return this.urlPath;
        }

        public int hashCode() {
            int iB = AbstractC2761L.b(Arrays.hashCode(this.salt) * 31, 31, this.apiKey);
            String str = this.nonce;
            int iB2 = AbstractC2761L.b((iB + (str != null ? str.hashCode() : 0)) * 31, 31, this.urlPath);
            String str2 = this.postParamsHashHeader;
            int iB3 = AbstractC2761L.b((iB2 + (str2 != null ? str2.hashCode() : 0)) * 31, 31, this.requestTime);
            String str3 = this.eTag;
            int iHashCode = (iB3 + (str3 != null ? str3.hashCode() : 0)) * 31;
            String str4 = this.body;
            return iHashCode + (str4 != null ? str4.hashCode() : 0);
        }

        public final byte[] toSignatureToVerify() {
            byte[] bytes;
            byte[] bytes2;
            byte[] bytes3;
            byte[] bArr = this.salt;
            String str = this.apiKey;
            Charset charset = a.f6257a;
            byte[] bytes4 = str.getBytes(charset);
            o.g(bytes4, "getBytes(...)");
            byte[] bArrT = AbstractC3250p.T(bArr, bytes4);
            String str2 = this.nonce;
            byte[] bArrDecode = str2 != null ? Base64.decode(str2, 0) : null;
            if (bArrDecode == null) {
                bArrDecode = new byte[0];
            }
            byte[] bArrT2 = AbstractC3250p.T(bArrT, bArrDecode);
            byte[] bytes5 = this.urlPath.getBytes(charset);
            o.g(bytes5, "getBytes(...)");
            byte[] bArrT3 = AbstractC3250p.T(bArrT2, bytes5);
            String str3 = this.postParamsHashHeader;
            if (str3 != null) {
                bytes = str3.getBytes(charset);
                o.g(bytes, "getBytes(...)");
            } else {
                bytes = new byte[0];
            }
            byte[] bArrT4 = AbstractC3250p.T(bArrT3, bytes);
            byte[] bytes6 = this.requestTime.getBytes(charset);
            o.g(bytes6, "getBytes(...)");
            byte[] bArrT5 = AbstractC3250p.T(bArrT4, bytes6);
            String str4 = this.eTag;
            if (str4 != null) {
                bytes2 = str4.getBytes(charset);
                o.g(bytes2, "getBytes(...)");
            } else {
                bytes2 = new byte[0];
            }
            byte[] bArrT6 = AbstractC3250p.T(bArrT5, bytes2);
            String str5 = this.body;
            if (str5 != null) {
                bytes3 = str5.getBytes(charset);
                o.g(bytes3, "getBytes(...)");
            } else {
                bytes3 = new byte[0];
            }
            return AbstractC3250p.T(bArrT6, bytes3);
        }

        public String toString() {
            StringBuilder sb = new StringBuilder("Parameters(salt=");
            sb.append(Arrays.toString(this.salt));
            sb.append(", apiKey=");
            sb.append(this.apiKey);
            sb.append(", nonce=");
            sb.append(this.nonce);
            sb.append(", urlPath=");
            sb.append(this.urlPath);
            sb.append(", postParamsHashHeader=");
            sb.append(this.postParamsHashHeader);
            sb.append(", requestTime=");
            sb.append(this.requestTime);
            sb.append(", eTag=");
            sb.append(this.eTag);
            sb.append(", body=");
            return Z0.o.r(sb, this.body, ')');
        }
    }

    public SigningManager(SignatureVerificationMode signatureVerificationMode, AppConfig appConfig, String apiKey) {
        o.h(signatureVerificationMode, "signatureVerificationMode");
        o.h(appConfig, "appConfig");
        o.h(apiKey, "apiKey");
        this.signatureVerificationMode = signatureVerificationMode;
        this.appConfig = appConfig;
        this.apiKey = apiKey;
    }

    public final String createRandomNonce() {
        byte[] bArr = new byte[12];
        new SecureRandom().nextBytes(bArr);
        byte[] bArrEncode = Base64.encode(bArr, 0);
        o.g(bArrEncode, "encode(bytes, Base64.DEFAULT)");
        return p.o1(new String(bArrEncode, a.f6257a)).toString();
    }

    public final String getPostParamsForSigningHeaderIfNeeded(Endpoint endpoint, List<k> list) {
        o.h(endpoint, "endpoint");
        if (list == null || list.isEmpty() || !shouldVerifyEndpoint(endpoint)) {
            return null;
        }
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        ArrayList arrayList = new ArrayList(AbstractC3253s.G(list, 10));
        int i6 = 0;
        for (Object obj : list) {
            int i7 = i6 + 1;
            if (i6 < 0) {
                AbstractC3252r.F();
                throw null;
            }
            k kVar = (k) obj;
            if (i6 > 0) {
                messageDigest.update((byte) 0);
            }
            byte[] bytes = ((String) kVar.f25470b).getBytes(a.f6257a);
            o.g(bytes, "getBytes(...)");
            messageDigest.update(bytes);
            arrayList.add(C3137A.f25453a);
            i6 = i7;
        }
        byte[] bArrDigest = messageDigest.digest();
        o.g(bArrDigest, "sha256Digest.digest()");
        String strQ = "";
        for (byte b5 : bArrDigest) {
            strQ = A0.a.q(new Object[]{Byte.valueOf(b5)}, 1, "%02x", Z0.o.t(strQ));
        }
        return AbstractC3251q.m0(AbstractC3252r.B(AbstractC3251q.m0(list, ",", null, null, SigningManager$getPostParamsForSigningHeaderIfNeeded$header$1.INSTANCE, 30), POST_PARAMS_ALGORITHM, strQ), Constants.SUBS_ID_BASE_PLAN_ID_SEPARATOR, null, null, null, 62);
    }

    public final SignatureVerificationMode getSignatureVerificationMode() {
        return this.signatureVerificationMode;
    }

    public final boolean shouldVerifyEndpoint(Endpoint endpoint) {
        o.h(endpoint, "endpoint");
        return endpoint.getSupportsSignatureVerification() && this.signatureVerificationMode.getShouldVerify();
    }

    public final VerificationResult verifyResponse(String urlPath, String str, String str2, String str3, String str4, String str5, String str6) {
        o.h(urlPath, "urlPath");
        if (this.appConfig.getForceSigningErrors()) {
            LogLevel logLevel = LogLevel.WARN;
            LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
            if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                currentLogHandler.w(com.google.android.recaptcha.internal.a.j(logLevel, new StringBuilder("[Purchases] - ")), "Forcing signing error for request with path: ".concat(urlPath));
            }
            return VerificationResult.FAILED;
        }
        IntermediateSignatureHelper intermediateSignatureHelper = this.signatureVerificationMode.getIntermediateSignatureHelper();
        if (intermediateSignatureHelper == null) {
            return VerificationResult.NOT_REQUESTED;
        }
        if (str == null) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_MISSING_SIGNATURE, Arrays.copyOf(new Object[]{urlPath}, 1)), null);
            return VerificationResult.FAILED;
        }
        if (str4 == null) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_MISSING_REQUEST_TIME, Arrays.copyOf(new Object[]{urlPath}, 1)), null);
            return VerificationResult.FAILED;
        }
        if (str3 == null && str5 == null) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_MISSING_BODY_OR_ETAG, Arrays.copyOf(new Object[]{urlPath}, 1)), null);
            return VerificationResult.FAILED;
        }
        try {
            Signature signatureFromString$purchases_defaultsBc8Release = Signature.Companion.fromString$purchases_defaultsBc8Release(str);
            Result<SignatureVerifier, PurchasesError> resultCreateIntermediateKeyVerifierIfVerified = intermediateSignatureHelper.createIntermediateKeyVerifierIfVerified(signatureFromString$purchases_defaultsBc8Release);
            if (resultCreateIntermediateKeyVerifierIfVerified instanceof Result.Error) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_INTERMEDIATE_KEY_FAILED, Arrays.copyOf(new Object[]{urlPath, ((PurchasesError) ((Result.Error) resultCreateIntermediateKeyVerifierIfVerified).getValue()).getUnderlyingErrorMessage()}, 2)), null);
                return VerificationResult.FAILED;
            }
            if (!(resultCreateIntermediateKeyVerifierIfVerified instanceof Result.Success)) {
                throw new v();
            }
            if (!((SignatureVerifier) ((Result.Success) resultCreateIntermediateKeyVerifierIfVerified).getValue()).verify(signatureFromString$purchases_defaultsBc8Release.getPayload(), new Parameters(signatureFromString$purchases_defaultsBc8Release.getSalt(), this.apiKey, str2, urlPath, str6, str4, str5, str3).toSignatureToVerify())) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_ERROR, Arrays.copyOf(new Object[]{urlPath}, 1)), null);
                return VerificationResult.FAILED;
            }
            LogLevel logLevel2 = LogLevel.VERBOSE;
            LogHandler currentLogHandler2 = LogWrapperKt.getCurrentLogHandler();
            if (Config.INSTANCE.getLogLevel().compareTo(logLevel2) <= 0) {
                currentLogHandler2.v(com.google.android.recaptcha.internal.a.j(logLevel2, new StringBuilder("[Purchases] - ")), String.format(NetworkStrings.VERIFICATION_SUCCESS, Arrays.copyOf(new Object[]{urlPath}, 1)));
            }
            return VerificationResult.VERIFIED;
        } catch (InvalidSignatureSizeException e6) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", String.format(NetworkStrings.VERIFICATION_INVALID_SIZE, Arrays.copyOf(new Object[]{urlPath, e6.getMessage()}, 2)), null);
            return VerificationResult.FAILED;
        }
    }
}
