Michu93
Michu93

Reputation: 5745

Can't read the key from KeyStore

I have some problems with KeyStore. I added key to KeyStore and can't get it from there. My code:

        try 
        {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(128, random);
            SecretKey key = keygen.generateKey();
            KeyStore ks = KeyStore.getInstance("UBER", "BC");
            ks.load(null, pass);
            ks.store(new FileOutputStream(path), pass);
            ks.setKeyEntry(keyName, key, pass, null);
            System.out.println(ks.containsAlias(keyName));
            key = null;
            KeyStore ks1 = KeyStore.getInstance("UBER", "BC");
            ks1.load(new FileInputStream(path), pass);
            System.out.println(ks1.containsAlias(keyName));
        }

the output is:

true
false

seems like key disapper or I can't load the KeyStore corectly. Do you see any bugs here?

Upvotes: 1

Views: 303

Answers (1)

Pace
Pace

Reputation: 43957

You are saving your keystore before adding keys to it. Swap these two lines:

        ks.store(new FileOutputStream(path), pass);
        ks.setKeyEntry(keyName, key, pass, null);

So that they are:

        ks.setKeyEntry(keyName, key, pass, null);
        ks.store(new FileOutputStream(path), pass);

Upvotes: 3

Related Questions