Storing key using KeyStore in Android

被刻印的时光 ゝ 提交于 2019-11-30 17:03:12

问题


I am using KeyStore to protect my private key but when the line:

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

is executed I have this exception:

'java.lang.NullPointerException'.

I don't understand where is the problem.

Code:

    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();        
    }

Thanks for the Help!


回答1:


Change:

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

To

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

Right now, you're assigning the context parameter in the method to the same value as the global one, which is null. Due to this, your context doesn't actually get stored.



来源:https://stackoverflow.com/questions/14972316/storing-key-using-keystore-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!