简体   繁体   中英

Storing key using KeyStore in Android

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM