存储RSA私钥Android

时间:2013-11-20 17:18:36

标签: android encryption storage private-key

在创建简单消息传递android应用程序,即加密/解密消息并通过互联网发送它们时,我决定使用RSA公钥/私钥加密。问题是如何存储私钥,这样即使手机被恶意植根,密钥也会保持安全?据我所知,KeyStore用于证书,不能用于此吗?我应该使用AES将私钥加密为文本文件吗?我对安全性的经验很少,所以请随时纠正我的想法,并发表意见!

亲切的问候。

4 个答案:

答案 0 :(得分:8)

我认为KeyStore可能适合您的使用。它能够存储RSA密钥并使用AES加密它们,因此即使使用root访问权限,也无法在没有密码或强制执行的情况下提取它们。

这里有关于使用KeyStore的好帖子:http://nelenkov.blogspot.fr/2012/05/storing-application-secrets-in-androids.html

答案 1 :(得分:4)

您可以在Android上使用SharedPreference持久保存您的RSA公钥/私钥。 为了在手机被恶意植根时保持您的密钥安全,您可以执行以下步骤:

1:当您想要生成任何数据时生成密钥对 2:提示用户输入密码 3:使用该密码生成对称密钥以加密您的私钥 4:您可以使用公钥加密数据并使用私钥解密 5:您可以为步骤2中提示的密码保留会话。在该会话期间,您可以使用对称密钥(从密码生成)来加密/解密私钥。

以下代码段显示了如何存储&获取公钥

public void setPublicKey(PublicKey publicKey, String key, Context context) {

    byte[] pubKey = publicKey.getEncoded();
    String pubKeyString = Base64.encodeBytes(pubKey);
    this.setString(key, pubKeyString, context);
}

public PublicKey getPublicKey(String key,Context context) {

    PublicKey pKey = null;
    try {

        String pubString = this.getString(key, context);

        if(pubString!=null) {
            byte[] binCpk = Base64.decode(pubString);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binCpk);
            pKey = keyFactory.generatePublic(publicKeySpec);
        }
        }catch(Exception e){
    }
    return pKey;
}

以下代码段显示了如何存储&获取私钥。

public void setPrivateKey(PrivateKey privateKey, String key, Context context) {

    byte[] priKey = privateKey.getEncoded();
    String priKeyString = Base64.encodeBytes(priKey);
    this.setString(key, priKeyString, context);
}

public PrivateKey getPrivateKey(String key, Context context) {

    PrivateKey privateKey = null;

    try {
        String privateString = this.getString(key, context);
        if(privateString!=null){
            byte[] binCpk = Base64.decode(privateString);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binCpk);
            privateKey = keyFactory.generatePrivate(privateKeySpec);
        }
    } 
    catch(Exception e){
    }
    return privateKey;
}

答案 2 :(得分:2)

文件系统中的任何密钥库(P12,JKS,AKS)都不足以保存RSA私钥。只有SmartCard或安全令牌才能提供高级别的安全性。阅读本书:“Android Security Internals”。在本书中,您将找到Android安全和JCA提供商的良好描述。

答案 3 :(得分:0)

是的,您可以使用KeyStore将RSA私钥保留在Android Studio中,并根据需要进行检索以进行签名。基本思想是在生成密钥时,将“ AndroidKeystore”用作提供程序。这个人:https://stackoverflow.com/questions/49410575/keystore-operation-failed-with-rsa-sign-and-verify#=的重点是确保您设置签名填充。这样做对我有用,如下所示:

public void storeKeyAsymmetric(){    //Generate the keys (public and private together) using KeyStore
KeyPairGenerator kpGenerator = null;
    try {
        kpGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
    try {
        kpGenerator.initialize(new KeyGenParameterSpec.Builder("aliasOfYourChoice", KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                .setDigests(KeyProperties.DIGEST_SHA512, KeyProperties.DIGEST_SHA256)
                .setKeySize(2048)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP, KeyProperties.ENCRYPTION_PADDING_NONE)
                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS)
                .build());
        keyPairAsymmetric = kpGenerator.generateKeyPair();
        devicePublic = keyPairAsymmetric.getPublic();
        byte[] encoding = devicePublic.getEncoded();
        strDevicePublicPEM = Crypto.writePEM(encoding);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
}

稍后,您可以使用该私钥对消息进行签名,如下所示:

public static String verifiedDeviceSignature(String dataToSign){
    boolean verified = false;
    String signature = null;
    MessageDigest digest = null;
    try {
        digest = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    digest.update(dataToSign.getBytes(StandardCharsets.UTF_8));
    byte[] hash = digest.digest();

    try {
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        //******This is a PrivateKeyEntry
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry("aliasOfYourChoice", null);  //null if you don't have key locked up with password
        PrivateKey privateKey = privateKeyEntry.getPrivateKey();
        Signature s = Signature.getInstance("SHA512withRSA");
        s.initSign(privateKey);
        s.update(dataToSign.getBytes(StandardCharsets.UTF_8));  //TODO:  Change this to hash
        byte[] sig = s.sign();

        PublicKey publicKey = ks.getCertificate("aliasOfYourChoice").getPublicKey();

        Signature v = Signature.getInstance("SHA512withRSA");
        v.initVerify(publicKey);
        v.update(dataToSign.getBytes(StandardCharsets.UTF_8));  //TODO:  Change this to hash
        verified = v.verify(sig);
        String strSig = new String(Base64.encode(sig, 2));
        signature = strSig;
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableEntryException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }

    if(verified){
        Log.d("***verifiedDeviceSignature*: ", "Signature Verified");
        //TODO:  URL encode
        return signature;
    }else {
        return "Not verified.";
    }
}