package io.trustbuilder.mfa.android.demoapp.security;

import android.os.Build;
import android.security.keystore.StrongBoxUnavailableException;

import androidx.annotation.RequiresApi;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Security;

public class CryptoUtils {
    {
        Security.addProvider(new BouncyCastleProvider());
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    public static byte[] generateRsaKeyForBio(String keyStoreAlias, KeystoreService keystoreService) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        try {
            KeyPair pair = keystoreService.generateKeys(keyStoreAlias, true);
            PublicKey publicKey = pair.getPublic();
            return publicKey.getEncoded();
        } catch (StrongBoxUnavailableException e) {
            KeyPair pair = keystoreService.generateKeys(keyStoreAlias, false);
            PublicKey publicKey = pair.getPublic();
            return publicKey.getEncoded();
        }
    }

    public static byte[] generateRsaKeyForBioForOldAndroid(String keyStoreAlias, KeystoreService keystoreService) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        KeyPair pair = keystoreService.generateKeys(keyStoreAlias, true);
        PublicKey publicKey = pair.getPublic();
        return publicKey.getEncoded();
    }
}
