如何使用Android KeyStore安全地存储任意字符串? [英] How Can I Use the Android KeyStore to securely store arbitrary strings?

查看:92
本文介绍了如何使用Android KeyStore安全地存储任意字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在Android KeyStore中安全地存储一些敏感字符串.我从服务器上获得了字符串,但是我有一个用例,需要我对其进行持久化. KeyStore仅允许使用与分配给我的应用程序相同的UID进行访问,并且它将使用设备主密码来加密数据,因此据我了解,我不必进行任何其他加密来保护我的数据.我的麻烦是,我缺少有关如何写入数据的信息.只要省略对KeyStore.store(null)的调用,我下面的代码就可以完美地工作.该代码将失败,并且只要将数据放入KeyStore后就无法存储,就无法持久保存.

I would like to be able securely store some sensitive strings in the Android KeyStore. I get the strings from the server but I have a use case which requires me to persist them. KeyStore will only allow access from the same UID as that assigned to my app, and it will encrypt the data with the device master password, so it's my understanding that I don't have to do any additional encryption to protect my data. My trouble is, I'm missing something about how to write the data. The code I have below works perfectly, as long as the call to KeyStore.store(null) is omitted. That code fails, and as long as I can't store the data after putting it to the KeyStore, then I can't persist it.

我认为我缺少有关KeyStore API的信息,但我不知道是什么.任何帮助表示赞赏!

I think I'm missing something about the KeyStore API, but I don't know what. Any help appreciated!

String metaKey = "ourSecretKey";
String encodedKey = "this is supposed to be a secret";
byte[] encodedKeyBytes = new byte[(int)encodedKey.length()];
encodedKeyBytes = encodedKey.getBytes("UTF-8");
KeyStoreParameter ksp = null;

//String algorithm = "DES";
String algorithm = "DESede";
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKeySpec secretKeySpec = new SecretKeySpec(encodedKeyBytes, algorithm);
SecretKey secretKey = secretKeyFactory.generateSecret(secretKeySpec);

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

keyStore.load(null);

KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
keyStore.setEntry(metaKey, secretKeyEntry, ksp);

keyStore.store(null);

String recoveredSecret = "";
if (keyStore.containsAlias(metaKey)) {
    KeyStore.SecretKeyEntry recoveredEntry = (KeyStore.SecretKeyEntry)keyStore.getEntry(metaKey, ksp);
    byte[] bytes = recoveredEntry.getSecretKey().getEncoded();
    for (byte b : bytes) {
        recoveredSecret += (char)b;
     }
}
Log.v(TAG, "recovered " + recoveredSecret);

推荐答案

我重新设计了Patrick Brennan接受的答案.在Android 9上,它产生了NoSuchAlgorithmException.不推荐使用的KeyPairGeneratorSpec已替换为KeyPairGenerator.解决填充方面的异常还需要做一些工作.

I have reworked the accepted answer by Patrick Brennan. on Android 9, it was yielding a NoSuchAlgorithmException. The deprecated KeyPairGeneratorSpec has been replaced with KeyPairGenerator. There was also some work required to address an exception regarding the padding.

代码带有所做的更改:"***"

The code is annotated with the changes made: "***"

@RequiresApi(api = Build.VERSION_CODES.M)
public static void storeExistingKey(Context context) {

    final String TAG = "KEY-UTIL";

    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        String alias = "key11";
        int nBefore = keyStore.size();

        // Create the keys if necessary
        if (!keyStore.containsAlias(alias)) {

            Calendar notBefore = Calendar.getInstance();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.YEAR, 1);


            // *** Replaced deprecated KeyPairGeneratorSpec with KeyPairGenerator
            KeyPairGenerator spec = KeyPairGenerator.getInstance(
                    // *** Specified algorithm here
                    // *** Specified: Purpose of key here
                    KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
            spec.initialize(new KeyGenParameterSpec.Builder(
                    alias, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) 
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) //  RSA/ECB/PKCS1Padding
                    .setKeySize(2048)
                    // *** Replaced: setStartDate
                    .setKeyValidityStart(notBefore.getTime())
                    // *** Replaced: setEndDate
                    .setKeyValidityEnd(notAfter.getTime())
                    // *** Replaced: setSubject
                    .setCertificateSubject(new X500Principal("CN=test"))
                    // *** Replaced: setSerialNumber
                    .setCertificateSerialNumber(BigInteger.ONE)
                    .build());
            KeyPair keyPair = spec.generateKeyPair();
            Log.i(TAG, keyPair.toString());
        }

        int nAfter = keyStore.size();
        Log.v(TAG, "Before = " + nBefore + " After = " + nAfter);

        // Retrieve the keys
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
        PrivateKey privateKey = privateKeyEntry.getPrivateKey();
        PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();


        Log.v(TAG, "private key = " + privateKey.toString());
        Log.v(TAG, "public key = " + publicKey.toString());

        // Encrypt the text
        String plainText = "This text is supposed to be a secret!";
        String dataDirectory = context.getApplicationInfo().dataDir;
        String filesDirectory = context.getFilesDir().getAbsolutePath();
        String encryptedDataFilePath = filesDirectory + File.separator + "keep_yer_secrets_here";

        Log.v(TAG, "plainText = " + plainText);
        Log.v(TAG, "dataDirectory = " + dataDirectory);
        Log.v(TAG, "filesDirectory = " + filesDirectory);
        Log.v(TAG, "encryptedDataFilePath = " + encryptedDataFilePath);

        // *** Changed the padding type here and changed to AndroidKeyStoreBCWorkaround
        Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround");
        inCipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // *** Changed the padding type here and changed to AndroidKeyStoreBCWorkaround
        Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround");
        outCipher.init(Cipher.DECRYPT_MODE, privateKey);

        CipherOutputStream cipherOutputStream =
                new CipherOutputStream(
                        new FileOutputStream(encryptedDataFilePath), inCipher);
        // *** Replaced string literal with StandardCharsets.UTF_8
        cipherOutputStream.write(plainText.getBytes(StandardCharsets.UTF_8));
        cipherOutputStream.close();

        CipherInputStream cipherInputStream =
                new CipherInputStream(new FileInputStream(encryptedDataFilePath),
                        outCipher);
        byte[] roundTrippedBytes = new byte[1000]; // TODO: dynamically resize as we get more data

        int index = 0;
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            roundTrippedBytes[index] = (byte) nextByte;
            index++;
        }

        // *** Replaced string literal with StandardCharsets.UTF_8
        String roundTrippedString = new String(roundTrippedBytes, 0, index, StandardCharsets.UTF_8);
        Log.v(TAG, "round tripped string = " + roundTrippedString);

    } catch (NoSuchAlgorithmException | UnsupportedOperationException | InvalidKeyException | NoSuchPaddingException | UnrecoverableEntryException | NoSuchProviderException | KeyStoreException | CertificateException | IOException e | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
}

注意:"AndroidKeyStoreBCWorkaround"允许代码在不同的API之间工作.

Note: "AndroidKeyStoreBCWorkaround" allows the code to work across different APIs.

如果有人可以评论此更新解决方案中的任何缺点,我将不胜感激.否则,如果任何具有更多加密知识的人有信心更新Patrick的答案,那么我将删除此答案.

I would be grateful if anyone can comment on any shortcomings in this updated solution. Else if anyone with more Crypto knowledge feels confident to update Patrick's answer then I will remove this one.

这篇关于如何使用Android KeyStore安全地存储任意字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆