Key storage with KeyStore on Android

I use KeyStore to protect my private key, but when the line is:

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

I have this exception:

'java.lang.NullPointerException'.

I do not understand where the problem is.

the 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!

+5
source share
1 answer

Edit:

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

For

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

You are currently assigning a context parameter in a method of the same value as the global one, which is null. Because of this, your context is not actually saved.

+4
source

All Articles