简体   繁体   中英

Storing key using Keystore

I am using keystore to protect private key in a file(with a password for that file).I did not understand this code

// save my secret key
javax.crypto.SecretKey mySecretKey;
KeyStore.SecretKeyEntry skEntry =
    new KeyStore.SecretKeyEntry(mySecretKey);
ks.setEntry("secretKeyAlias", skEntry, 
    new KeyStore.PasswordProtection(password));

// store away the keystore
java.io.FileOutputStream fos = null;
try {
    fos = new java.io.FileOutputStream("newKeyStoreName");
    ks.store(fos, password);
} finally {
    if (fos != null) {
        fos.close();
    }
}

What is setEntry doing?? Are we saving private key through fileoutputstream ??If it is true where is the password for the file??? What is the extention of the file??Is it .jks??

A Java keystore is a container for cryptographic objects. It can contain symmetric keys, private keys and certificates. The setEntry() method adds another entry to the keystore. In your case it adds a symmetric key identified by "secretKeyAlias" with protected by a password to the key store. If you wanted to save a private key, you should have created a KeyStore.PrivateKeyEntry instead.

After you have created a keystore in memory, you can store it on the disk. The keystore has a store() -method , which writes the keystore to a Stream . In this case a FileOutputStream . A MAC is also added to the keystore, protected by a password. In your case the password is the same as the one used above, but that is not necessary.

The usual extension for a Java keystore is .jks, but your code just stores it in a file named "newKeyStoreName".

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