aes - < 4.3 的 Android KeyStore 实现

标签 aes android rsa keystore

我计划在我的 Android 应用程序中使用 KeyStore 来使用存储在 KeyStore 中的 KeyPair 来加密 AES key 。 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);
    }
}

此实现可以wrapunwrap SecretKey,在我的例子中是 AES key 。

但是,此 KeyStore 仅在 4.3 及更高版本中受支持。请参阅 Jelly Bean 注释。

关于我的问题,对于低于 4.3 的类似实现的可能性有哪些?

提前致谢

最佳答案

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

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

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

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

关于aes - < 4.3 的 Android KeyStore 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27911746/

相关文章:

android - 通知点击 - 如果应用程序关闭打开 Activity ,如果应用程序打开显示当前 Activity

java - 无法将 OnLongClickListener 设置为 ExpandableListView 组

cryptography - 为什么 RSA 解密过程比加密过程需要更长的时间?

java - 将 rsa 私钥分成两半

javascript - AES 加密/解密对于相同的输入、相同的 iv、pad 和模式给出不同的结果

javascript - 仅使用 WebCrypto API 使用密码加密私钥

encryption - 具有任意长度明文的 AES 测试向量

c - C 中 main() 执行一半后输出消失

java - 将值作为对象获取如何将其转换为字符串并检索其值

go - 如何从文件中读取 RSA key