package a.b.a.h;

import a.a.a.b;
import a.c.b.v;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import androidx.room.Room;
import com.google.crypto.tink.subtle.Bytes;
import com.google.crypto.tink.subtle.Hkdf;
import com.share.connect.security.PeerDatabase;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONObject;

public class a {
    private static final String d = "KeyNegotiator";
    private static final String e = "session_key";
    private static final String f = "uibc_session_key";
    private static final int g = 16;
    private static final int h = 6;
    public static volatile PeerDatabase i;

    /* renamed from: a  reason: collision with root package name */
    private byte[] f24a;
    private byte[] b;
    private KeyPair c;

    /* renamed from: a.b.a.h.a$a  reason: collision with other inner class name */
    public static class C0002a {

        /* renamed from: a  reason: collision with root package name */
        public static final int f25a = 0;
        public static final int b = 1;
        public static final int c = 2;
        public static final int d = 3;
    }

    public a(Context context) {
        a(context);
    }

    private ECPublicKey a(String str, byte[] bArr) throws Exception {
        AlgorithmParameters instance = AlgorithmParameters.getInstance("EC");
        instance.init(new ECGenParameterSpec(str));
        ECParameterSpec eCParameterSpec = (ECParameterSpec) instance.getParameterSpec(ECParameterSpec.class);
        int bitLength = eCParameterSpec.getOrder().bitLength() / 8;
        if (bArr.length == bitLength * 2) {
            return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Arrays.copyOfRange(bArr, 0, bitLength)), new BigInteger(1, Arrays.copyOfRange(bArr, bitLength, bitLength + bitLength))), eCParameterSpec));
        }
        throw new RuntimeException("encoded key with wrong size");
    }

    public static void a(Context context) {
        if (i == null) {
            synchronized (a.class) {
                if (i == null) {
                    i = (PeerDatabase) Room.databaseBuilder(context, PeerDatabase.class, "peer.db").allowMainThreadQueries().build();
                }
            }
        }
    }

    public static void a(byte[] bArr, String str) {
        try {
            b(str);
            i.peerDao().delete(new String(bArr, StandardCharsets.UTF_8));
        } catch (Exception e2) {
            b.b(d, "removePeer Exception", e2);
        }
    }

    public static JSONObject b() throws Exception {
        return new JSONObject().put("ver", v.d);
    }

    public static void b(String str) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
        KeyStore instance = KeyStore.getInstance("AndroidKeyStore");
        instance.load(null);
        instance.deleteEntry(str);
    }

    public static int g() {
        return v.d;
    }

    public ECPublicKey a() throws Exception {
        KeyPairGenerator instance = KeyPairGenerator.getInstance("EC");
        instance.initialize(new ECGenParameterSpec("secp256r1"));
        KeyPair generateKeyPair = instance.generateKeyPair();
        this.c = generateKeyPair;
        return (ECPublicKey) generateKeyPair.getPublic();
    }

    public ECPublicKey a(byte[] bArr, byte[] bArr2, byte[] bArr3, PublicKey publicKey) throws Exception {
        if (publicKey == null) {
            return null;
        }
        Signature instance = Signature.getInstance("SHA256withECDSA");
        instance.initVerify(publicKey);
        instance.update(Bytes.concat(bArr, bArr2));
        if (instance.verify(bArr3)) {
            return a("secp256r1", bArr);
        }
        return null;
    }

    public ECPublicKey a(byte[] bArr, byte[] bArr2, byte[] bArr3, byte[] bArr4) throws Exception {
        if (Arrays.equals(bArr4, a(Bytes.concat(bArr, bArr2), bArr3))) {
            return a("secp256r1", bArr);
        }
        return null;
    }

    public void a(byte[] bArr) {
        i.peerDao().delete(new String(bArr, StandardCharsets.UTF_8));
    }

    public boolean a(Key key, byte[] bArr) throws Exception {
        if (this.c == null || key == null) {
            return false;
        }
        KeyAgreement instance = KeyAgreement.getInstance("ECDH");
        instance.init(this.c.getPrivate());
        instance.doPhase(key, true);
        byte[] computeHkdf = Hkdf.computeHkdf("HMACSHA256", instance.generateSecret(), MessageDigest.getInstance("SHA-256").digest(bArr), e(e), 16);
        a.c.b.b0.a.a(computeHkdf, e);
        a.c.b.b0.a.a(computeHkdf, f);
        return true;
    }

    public byte[] a(int i2) throws Exception {
        SecureRandom secureRandom = new SecureRandom();
        byte[] bArr = new byte[i2];
        this.b = bArr;
        secureRandom.nextBytes(bArr);
        return this.b;
    }

    public byte[] a(String str) {
        return Base64.getDecoder().decode(str);
    }

    public byte[] a(String str, byte[] bArr, byte[] bArr2) throws Exception {
        PrivateKey privateKey;
        KeyStore instance = KeyStore.getInstance("AndroidKeyStore");
        instance.load(null);
        if (Build.VERSION.SDK_INT <= 28) {
            privateKey = (PrivateKey) instance.getKey(str, null);
        } else {
            KeyStore.Entry entry = instance.getEntry(str, null);
            if (entry instanceof KeyStore.PrivateKeyEntry) {
                privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
            } else {
                throw new RuntimeException("sign key not exist or invalid : " + str);
            }
        }
        Signature instance2 = Signature.getInstance("SHA256withECDSA");
        instance2.initSign(privateKey);
        instance2.update(Bytes.concat(bArr, bArr2));
        return instance2.sign();
    }

    public byte[] a(ECPublicKey eCPublicKey) {
        int bitLength = eCPublicKey.getParams().getOrder().bitLength() / 8;
        byte[] bArr = new byte[(bitLength * 2)];
        byte[] byteArray = eCPublicKey.getW().getAffineX().toByteArray();
        if (byteArray.length <= bitLength) {
            System.arraycopy(byteArray, 0, bArr, bitLength - byteArray.length, byteArray.length);
        } else if (byteArray.length == bitLength + 1 && byteArray[0] == 0) {
            System.arraycopy(byteArray, 1, bArr, 0, bitLength);
        } else {
            throw new RuntimeException("x coordinate with wrong size: len=" + byteArray.length);
        }
        byte[] byteArray2 = eCPublicKey.getW().getAffineY().toByteArray();
        if (byteArray2.length <= bitLength) {
            System.arraycopy(byteArray2, 0, bArr, (bitLength + bitLength) - byteArray2.length, byteArray2.length);
        } else if (byteArray2.length == bitLength + 1 && byteArray2[0] == 0) {
            System.arraycopy(byteArray2, 1, bArr, bitLength, bitLength);
        } else {
            throw new RuntimeException("y coordinate with wrong size: len=" + byteArray2.length);
        }
        return bArr;
    }

    public byte[] a(byte[] bArr, byte[] bArr2) throws Exception {
        byte[] bArr3 = this.f24a;
        if (bArr3 == null || bArr3.length < 6) {
            throw new Exception("pin is empty or too short when requested");
        }
        Mac instance = Mac.getInstance("HmacSHA256");
        instance.init(new SecretKeySpec(MessageDigest.getInstance("SHA-256").digest(Bytes.concat(bArr2, this.f24a)), "HmacSHA256"));
        return instance.doFinal(bArr);
    }

    public String b(byte[] bArr) {
        return Base64.getEncoder().encodeToString(bArr);
    }

    public boolean b(byte[] bArr, byte[] bArr2) {
        b bVar = new b();
        bVar.f26a = new String(bArr, StandardCharsets.UTF_8);
        bVar.b = b(bArr2);
        bVar.c = System.currentTimeMillis() / 1000;
        i.peerDao().insert(bVar);
        return true;
    }

    public b c(byte[] bArr) {
        return i.peerDao().get(new String(bArr, StandardCharsets.UTF_8));
    }

    public ECPublicKey c() {
        return (ECPublicKey) this.c.getPublic();
    }

    public ECPublicKey c(String str) throws Exception {
        KeyPairGenerator instance = KeyPairGenerator.getInstance("EC", "AndroidKeyStore");
        instance.initialize(new KeyGenParameterSpec.Builder(str, 12).setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")).setDigests("SHA-256").build());
        return (ECPublicKey) instance.generateKeyPair().getPublic();
    }

    public b d() {
        return i.peerDao().getLast();
    }

    public ECPublicKey d(String str) throws Exception {
        KeyStore instance = KeyStore.getInstance("AndroidKeyStore");
        instance.load(null);
        KeyStore.Entry entry = instance.getEntry(str, null);
        if (entry instanceof KeyStore.PrivateKeyEntry) {
            return (ECPublicKey) ((KeyStore.PrivateKeyEntry) entry).getCertificate().getPublicKey();
        }
        throw new RuntimeException("sign key not exist or invalid : " + str);
    }

    public ECPublicKey d(byte[] bArr) throws Exception {
        return a("secp256r1", bArr);
    }

    public void e(byte[] bArr) {
        this.f24a = bArr;
    }

    public byte[] e() {
        return this.b;
    }

    public byte[] e(String str) {
        if (str == null) {
            return null;
        }
        return str.getBytes(StandardCharsets.UTF_8);
    }

    public boolean f(byte[] bArr) {
        return i.peerDao().updateLast(new String(bArr, StandardCharsets.UTF_8)) > 0;
    }

    public byte[] f() {
        return this.f24a;
    }
}
