< 4.3 的 Android KeyStore 实现

Posted

技术标签:

【中文标题】< 4.3 的 Android KeyStore 实现【英文标题】:Android KeyStore implementation for < 4.3 【发布时间】:2015-01-12 19:37:27 【问题描述】:

我打算在我的 android 应用程序中使用 KeyStore 来使用存储在 KeyStore 中的 KeyPair 加密 AES 密钥。 KeyStore 的 Android 文档:

https://developer.android.com/training/articles/keystore.html

在互联网上搜索后,我找到了一个 AOSP 示例,我对此进行了编辑:

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal;


/**
 * Wraps @link SecretKey instances using a public/private key pair stored in
 * the platform @link KeyStore. This allows us to protect symmetric keys with
 * hardware-backed crypto, if provided by the device.
 * <p>
 * See <a href="http://en.wikipedia.org/wiki/Key_Wrap">key wrapping</a> for more
 * details.
 * <p>
 * Not inherently thread safe.
 *
 * Some explanations:
 * http://nelenkov.blogspot.nl/2013/08/credential-storage-enhancements-android-43.html
 */
public class SecretKeyWrapper 
    private final Cipher mCipher;
    private final KeyPair mPair;
    /**
     * Create a wrapper using the public/private key pair with the given alias.
     * If no pair with that alias exists, it will be generated.
     */
    public SecretKeyWrapper(Context context, String alias)
            throws GeneralSecurityException, IOException 
        mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (!keyStore.containsAlias(alias)) 
            generateKeyPair(context, alias);
        
        // Even if we just generated the key, always read it back to ensure we
        // can read it successfully.
        final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
                alias, null);
        mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
    
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private static void generateKeyPair(Context context, String alias)
            throws GeneralSecurityException 
        final Calendar start = new GregorianCalendar();
        final Calendar end = new GregorianCalendar();
        end.add(Calendar.YEAR, 100);
        final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(alias)
                .setSubject(new X500Principal("CN=" + alias))
                .setSerialNumber(BigInteger.ONE)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
        final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        gen.initialize(spec);
        gen.generateKeyPair();
    

    /**
     * Wrap a @link SecretKey using the public key assigned to this wrapper.
     * Use @link #unwrap(byte[]) to later recover the original
     * @link SecretKey.
     *
     * @return a wrapped version of the given @link SecretKey that can be
     *         safely stored on untrusted storage.
     */
    public byte[] wrap(SecretKey key) throws GeneralSecurityException 
        mCipher.init(Cipher.WRAP_MODE, mPair.getPublic());
        return mCipher.wrap(key);
    
    /**
     * Unwrap a @link SecretKey using the private key assigned to this
     * wrapper.
     *
     * @param blob a wrapped @link SecretKey as previously returned by
     *            @link #wrap(SecretKey).
     */
    public SecretKey unwrap(byte[] blob) throws GeneralSecurityException 
        mCipher.init(Cipher.UNWRAP_MODE, mPair.getPrivate());
        return (SecretKey) mCipher.unwrap(blob, "AES", Cipher.SECRET_KEY);
    

这个实现 kan wrapunwrap SecretKey 在我的例子中是一个 AES 密钥。

但是,仅从 4.3 及更高版本开始支持此 KeyStore。请参阅 Jelly Bean 注释。

回答我的问题,4.3 以下的同样实现的可能性是什么?

提前致谢,

【问题讨论】:

【参考方案1】:

密钥库从 1.6 开始可用,但早期版本没有官方 API。您仍然可以通过私有 API 使用它,但您可能会遇到各种问题。

可以在您引用的同一博客上找到一个示例:

http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html

实现可能会有些棘手,因为密钥库需要独立于设备锁屏解锁。对早期版本考虑基于密码的加密可能会更好,博客上有一篇关于它的帖子。

【讨论】:

【参考方案2】:

Android KeyStore 中的对称密钥生成和存储从 Android 6.0(API 级别 23)开始受支持。

Android KeyStore 中的非对称密钥生成和存储从 Android 4.3(API 级别 18)开始受支持。

有关详细信息,请参阅此文档: http://developer.android.com/training/articles/keystore.html

【讨论】:

以上是关于< 4.3 的 Android KeyStore 实现的主要内容,如果未能解决你的问题,请参考以下文章

为啥这个 XML 代码不为 Android 4.3 中溢出菜单的背景着色?

XML drawable 在 4.3 和 4.1.2 上具有不同的行为

ActionBarSherlock Item Icon 奇怪的宽度与Android 4.3

Android 4.3上的javax.net.ssl.SSLHandshakeException

Galaxy S3 Android 4.3 上 BLE 的连接间隔

[Android4.4.3] Nubia Z5S Mokee4.4.3 RC2.0 by syhost