如何在Android应用程序上存储RSA私钥

时间:2015-07-23 14:22:45

标签: java android encryption cryptography keystore

我确实看过这篇文章:Cannot generate RSA private Key on Android但它对我不起作用。

我的想法是使用RSA加密对访问令牌进行加密,并将私钥存储在设备上。我已经使用RSA成功加密了令牌,但我遗失了存储此密钥的最佳位置。我尝试使用KeyStore存储它,但我不知道这个调试为什么它不工作。继续收到错误:java.security.UnrecoverableKeyException:不匹配。

我的钥匙确实匹配,但是再次,不知道什么是错的,因为我对此并不了解。我正在使用setEntry并以奇怪和奇妙的方式存储私钥,我确定,如果它在返回时工作时不会是相同的密钥。

存储此私钥的最佳方法是什么?

我不是安全专家,所以对此有任何建议,我是否应该使用AES?

我的代码如下,我只使用了1个活动。

package com.example.rsatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStore.LoadStoreParameter;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.ProtectionParameter;
import java.security.KeyStore.SecretKeyEntry;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.DropBoxManager.Entry;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity {
String keyStoreFile;
Key privateKey = null;
boolean isUnlocked = false;
KeyStore keyStore = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    keyStoreFile = this.getFilesDir() + "/bpstore.keystore";
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            startActivity(new Intent("android.credentials.UNLOCK"));
            isUnlocked = true;
        } else {
            startActivity(new Intent("com.android.credentials.UNLOCK"));
            isUnlocked = true;
        }
    } catch (ActivityNotFoundException e) {
        Log.e("TAG", "No UNLOCK activity: " + e.getMessage(), e);
        isUnlocked = false;
    }

    if(isUnlocked){
        privateKey = GetPrivateKey();

        try{
            char[] pw =("123").toCharArray();
            keyStore = createKeyStore(this,keyStoreFile, pw);
            PasswordProtection keyPassword = new PasswordProtection("pw-secret".toCharArray());

            SecretKey sk = new SecretKey() {

                @Override
                public String getFormat() {
                    // TODO Auto-generated method stub
                    return privateKey.getFormat();
                }

                @Override
                public byte[] getEncoded() {
                    // TODO Auto-generated method stub
                    return privateKey.getEncoded();
                }

                @Override
                public String getAlgorithm() {
                    // TODO Auto-generated method stub
                    return privateKey.getAlgorithm();
                }
            };
            System.out.println(sk.getEncoded());
            System.out.println(privateKey.getEncoded());
            KeyStore.SecretKeyEntry ent = new SecretKeyEntry(sk);
            keyStore.setEntry("pk", ent, keyPassword);
            keyStore.store(new FileOutputStream(keyStoreFile), pw);

            KeyStore keyStore2;
            keyStore2 = KeyStore.getInstance("BKS");
            keyStore2.load(new FileInputStream(keyStoreFile), pw);
            KeyStore.Entry entry = keyStore2.getEntry("pk", keyPassword);
            KeyStore.SecretKeyEntry entOut = (KeyStore.SecretKeyEntry)entry;
        }catch(Exception ex){
            System.out.println("Error: " + ex.toString());
        }

    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private KeyStore createKeyStore(Context context, String fileName, char[] pw) throws Exception {
    System.out.println("[DIR]:" + fileName);
    File file = new File(fileName);

    keyStore = KeyStore.getInstance("BKS");

    if (file.exists()) 
    {
        keyStore.load(new FileInputStream(file), pw);
    } else 
    {
        keyStore.load(null, null);
        keyStore.store(new FileOutputStream(fileName), pw);
    }

    return keyStore;
}

private Key GetPrivateKey(){
    String theTestText = "This is just a simple test!";

    Key publicKey = null;

    Key privateKey = null;
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();
        publicKey = kp.getPublic();
        privateKey = kp.getPrivate();
    } catch (Exception e) {
        Log.e("", "RSA key pair error");
    }

    // Encode the original data with RSA private key
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("RSA");
        c.init(Cipher.ENCRYPT_MODE, privateKey);
        encodedBytes = c.doFinal(theTestText.getBytes());
    } catch (Exception e) {
        Log.e("", "RSA encryption error");
    }

    // Decode the encoded data with RSA public key
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("RSA");
        c.init(Cipher.DECRYPT_MODE, publicKey);
        decodedBytes = c.doFinal(encodedBytes);
    } catch (Exception e) {
        Log.e("", "RSA decryption error");
    }
    return privateKey;
}
}

提前致谢, 沃伦

1 个答案:

答案 0 :(得分:0)

我们最终使用AES代替尝试将RSA私钥添加到密钥库,而是使用密码将其包装起来。我们还为我们的Android项目添加了ProGuard,以便更难对我们的APK进行反编译。

感谢Maarten Bodewes的回答和帮助。

  

其他帖子是一个非常具体的错误。它没有正确的标签,所以每个人都错过了它。关于你的代码;为什么要尝试将非对称密钥存储为对称密钥(SecretKey)?那当然行不通。请注意,Java密钥库接口几乎旨在存储密钥+证书。您可能希望仅为RSA私钥使用另一种存储方法(例如,使用Cipher自己包装它们)。