Java store keys in keystore

Java Cryptography — Storing keys

The Keys and certificates used/generated are stored in a data base called as keystore. By default this database is stored in a file named .keystore.

You can access the contents of this database using the KeyStore class of the java.security package. This manages three different entries namely, PrivateKeyEntry, SecretKeyEntry, TrustedCertificateEntry.

Storing a Key in keystore

In this section, we will learn how to store a key in a keystore. To store a key in the keystore, follow the steps given below.

Step 1: Create a KeyStore object

The getInstance() method of the KeyStore class of the java.security package accepts a string value representing the type of the keystore and returns a KeyStore object.

Create an object of the KeyStore class using the getInstance() method as shown below.

//Creating the KeyStore object KeyStore keyStore = KeyStore.getInstance("JCEKS");

Step 2: Load the KeyStore object

The load() method of the KeyStore class accepts a FileInputStream object representing the keystore file and a String parameter specifying the password of the KeyStore.

In general, the KeyStore is stored in the file named cacerts, in the location C:/Program Files/Java/jre1.8.0_101/lib/security/ and its default password is changeit, load it using the load() method as shown below.

//Loading the KeyStore object char[] password = "changeit".toCharArray(); String path = "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts"; java.io.FileInputStream fis = new FileInputStream(path); keyStore.load(fis, password);

Step 3: Create the KeyStore.ProtectionParameter object

Instantiate the KeyStore.ProtectionParameter as shown below.

//Creating the KeyStore.ProtectionParameter object KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);

Step 4: Create a SecretKey object

Create the SecretKey (interface) object by instantiating its Sub class SecretKeySpec. While instantiating you need to pass password and algorithm as parameters to its constructor as shown below.

//Creating SecretKey object SecretKey mySecretKey = new SecretKeySpec(new String(keyPassword).getBytes(), "DSA");

Step 5: Create a SecretKeyEntry object

Create an object of the SecretKeyEntry class by passing the SecretKey object created in the above step as shown below.

//Creating SecretKeyEntry object KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey);

Step 6: Set an entry to the KeyStore

The setEntry() method of the KeyStore class accepts a String parameter representing the keystore entry alias, a SecretKeyEntry object, a ProtectionParameter object and, stores the entry under the given alias.

Set the entry to the keystore using the setEntry() method as shown below.

//Set the entry to the keystore keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);

The following example stores keys into the keystore existing in the “cacerts” file (windows 10 operating system).

import java.io.FileInputStream; import java.security.KeyStore; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class StoringIntoKeyStore < public static void main(String args[]) throws Exception < //Creating the KeyStore object KeyStore keyStore = KeyStore.getInstance("JCEKS"); //Loading the KeyStore object char[] password = "changeit".toCharArray(); String path = "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts"; java.io.FileInputStream fis = new FileInputStream(path); keyStore.load(fis, password); //Creating the KeyStore.ProtectionParameter object KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password); //Creating SecretKey object SecretKey mySecretKey = new SecretKeySpec("myPassword".getBytes(), "DSA"); //Creating SecretKeyEntry object KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey); keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam); //Storing the KeyStore object java.io.FileOutputStream fos = null; fos = new java.io.FileOutputStream("newKeyStoreName"); keyStore.store(fos, password); System.out.println("data stored"); >>

The above program generates the following output −

System.out.println("data stored");

Источник

Class KeyStore

  • KeyStore.PrivateKeyEntry This type of entry holds a cryptographic PrivateKey , which is optionally stored in a protected format to prevent unauthorized access. It is also accompanied by a certificate chain for the corresponding public key. Private keys and certificate chains are used by a given entity for self-authentication. Applications for this authentication include software distribution organizations which sign JAR files as part of releasing and/or licensing software.
  • KeyStore.SecretKeyEntry This type of entry holds a cryptographic SecretKey , which is optionally stored in a protected format to prevent unauthorized access.
  • KeyStore.TrustedCertificateEntry This type of entry contains a single public key Certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate. This type of entry can be used to authenticate other parties.

Each entry in a keystore is identified by an «alias» string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether aliases are case sensitive is implementation dependent. In order to avoid problems, it is recommended not to use aliases in a KeyStore that only differ in case.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

    To specify an existing keystore file:

// get keystore password char[] password = getPassword(); // probe the keystore file and load the keystore entries KeyStore ks = KeyStore.getInstance(new File("keyStoreName"), password);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore ks = KeyStore.getInstance("JKS");

Before a keystore can be accessed, it must be loaded (unless it was already loaded during instantiation).

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // get user password and file input stream char[] password = getPassword(); try (FileInputStream fis = new FileInputStream(«keyStoreName»))

Once the keystore has been loaded, it is possible to read existing entries from the keystore, or to write new entries into the keystore:

KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(password); // get my private key KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(«privateKeyAlias», protParam); PrivateKey myPrivateKey = pkEntry.getPrivateKey(); // save my secret key javax.crypto.SecretKey mySecretKey; KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mySecretKey); ks.setEntry(«secretKeyAlias», skEntry, protParam); // store away the keystore try (FileOutputStream fos = new FileOutputStream(«newKeyStoreName»))

Note that although the same password may be used to load the keystore, to protect the private key entry, to protect the secret key entry, and to store the keystore (as is shown in the sample code above), different passwords or other protection parameters may also be used.

Источник

Class KeyStore

  • KeyStore.PrivateKeyEntry This type of entry holds a cryptographic PrivateKey , which is optionally stored in a protected format to prevent unauthorized access. It is also accompanied by a certificate chain for the corresponding public key. Private keys and certificate chains are used by a given entity for self-authentication. Applications for this authentication include software distribution organizations which sign JAR files as part of releasing and/or licensing software.
  • KeyStore.SecretKeyEntry This type of entry holds a cryptographic SecretKey , which is optionally stored in a protected format to prevent unauthorized access.
  • KeyStore.TrustedCertificateEntry This type of entry contains a single public key Certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate. This type of entry can be used to authenticate other parties.

Each entry in a keystore is identified by an «alias» string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether aliases are case-sensitive is implementation dependent. In order to avoid problems, it is recommended not to use aliases in a KeyStore that only differ in case.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

    To specify an existing keystore file:

// get keystore password char[] password = getPassword(); // probe the keystore file and load the keystore entries KeyStore ks = KeyStore.getInstance(new File("keyStoreName"), password);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore ks = KeyStore.getInstance("JKS");

Before a keystore can be accessed, it must be loaded (unless it was already loaded during instantiation).

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // get user password and file input stream char[] password = getPassword(); try (FileInputStream fis = new FileInputStream(«keyStoreName»))

Once the keystore has been loaded, it is possible to read existing entries from the keystore, or to write new entries into the keystore:

KeyStore.PasswordProtection protParam = new KeyStore.PasswordProtection(password); try (FileOutputStream fos = new FileOutputStream(«newKeyStoreName»)) < // get my private key KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry("privateKeyAlias", protParam); PrivateKey myPrivateKey = pkEntry.getPrivateKey(); // save my secret key javax.crypto.SecretKey mySecretKey; KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mySecretKey); ks.setEntry("secretKeyAlias", skEntry, protParam); // store away the keystore ks.store(fos, password); >finally

Note that although the same password may be used to load the keystore, to protect the private key entry, to protect the secret key entry, and to store the keystore (as is shown in the sample code above), different passwords or other protection parameters may also be used.

Источник

Читайте также:  Php convert file encoding
Оцените статью