存储使用密钥库在Android的关键(Storing key using KeyStore in A

2019-07-20 04:31发布

我使用的密钥库来保护我的私人密钥,但是当行:

FileOutputStream fos = ctx.openFileOutput("bs.keystore", Context.MODE_PRIVATE);

执行我有这样的例外:

'java.lang.NullPointerException'.

我不明白问题出在哪里。

码:

    private Context ctx;

    public DataSec(Context ctx) 
    {
    ctx = this.ctx;
    }

    public void genKey() throws Exception
    {
    SecretKey key = KeyGenerator.getInstance("AES").generateKey();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, "clavedekey".toCharArray());

    PasswordProtection pass = new PasswordProtection("fedsgjk".toCharArray());
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key);
    ks.setEntry("secretKeyAlias", skEntry, pass);

    FileOutputStream fos = ctx.openFileOutput("bs.keystore", Context.MODE_PRIVATE);
    ks.store(fos, "clavedekey".toCharArray());
    fos.close();        
    }

谢谢您的帮助!

Answer 1:

更改:

public DataSec(Context ctx) 
{
ctx = this.ctx;
}

public DataSec(Context ctx) 
{
    this.ctx = ctx;
}

现在,你指定的方法相同的值作为全局的,这是空的上下文参数。 由于这个原因,你的情况下实际上没有得到保存。



文章来源: Storing key using KeyStore in Android