Android密钥库不保存密钥

时间:2019-02-09 11:39:07

标签: java android android-studio encryption keystore

我有一个问题,每次我执行keyGenerator.generateKey();然后keyStore.containsAlias(KEY_NAME)返回falsekeyStore.getKey(KEY_NAME, null)时,android密钥库都不想保存我生成的密钥null。当然,cipher.init(Cipher.ENCRYPT_MODE, key);然后会返回错误。

此代码对我有用,但是一旦我尝试从密钥库中将密钥删除为keyStore.deleteEntry(KEY_NAME),然后它停止工作。

我正在调试Samsung Galaxy S9 +上的代码,无法理解,为什么生成的密钥未保存到密钥库中。附加我的MainActivity.java代码。

public class MainActivity extends AppCompatActivity
{
    //Key details
    private KeyStore keyStore;
    private static final String KEY_NAME = "Test123";

    //Cipher details
    private Cipher cipher;

    //Error info at intro activity
    private TextView errorText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        errorText = (TextView) findViewById(R.id.errorText);

        //Init check
        checkPermissions();
    }

    //Init check
    protected void checkPermissions() {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

        if(!fingerprintManager.isHardwareDetected()){
            errorText.setText("Your Device does not have a Fingerprint Sensor!");

            //App killing if needed
            //android.os.Process.killProcess(android.os.Process.myPid());
            //System.exit(1);
        }
        else {
            if (!Objects.equals(ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT), PackageManager.PERMISSION_GRANTED)) {
                errorText.setText("Fingerprint authentication permission not enabled!");
            }
            else {
                if (!fingerprintManager.hasEnrolledFingerprints()) {
                    errorText.setText("Register at least one fingerprint in Settings!");
                }
                else {
                    if (!keyguardManager.isKeyguardSecure()) {
                        errorText.setText("Lock screen security not enabled in Settings!");
                    }
                    else {
                        generateKey();

                        if (cipherInit()) {
                            FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
                            FingerprintHandler helper = new FingerprintHandler(this);
                            helper.startAuth(fingerprintManager, cryptoObject);
                        }
                    }
                }
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    protected void generateKey() {
        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to get AndroidKeyStore instance", e);
        }

        KeyGenerator keyGenerator;
        try {
            keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        }
        catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to get KeyGenerator instance", e);
        }

        try {
            keyStore.load(null);

            keyGenerator.init(
                    new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
//                    .setKeySize(256) //TODO: CHANGE THIS TO 256-bit
                    .build()
            );

            keyGenerator.generateKey();
        }
        catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public boolean cipherInit() {
        try {
            cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        }
        catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("Failed to get Cipher", e);
        }

        try {
            keyStore.load(null);
            SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
            cipher.init(Cipher.ENCRYPT_MODE, key);

            return true;
        }
        catch (KeyPermanentlyInvalidatedException e) {
            return false;
        }
        catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to init Cipher", e);
        }
    }
}

谢谢。

0 个答案:

没有答案