Java KeyStore Use

Source: Internet
Author: User

public class KeyStore

Extends Object

This class represents the storage facility for keys and certificates.

KeyStore manage different types of entries. Each type of entry implements the Keystore.entry interface. Provides three basic keystore.entry implementations: keystore.privatekeyentry

This type of entry holds an encrypted privatekey and optionally stores the private key in a protected format to prevent unauthorized access. It also comes with a certificate chain with the corresponding public key.

The given entry uses the private key and the certificate chain for Self authentication (self-authentication). This validation is applied to include software publishing organizations that sign JAR files as part of the publishing and/or licensing software. Keystore.secretkeyentry

This type of entry holds an encrypted secretkey and optionally stores the key in a protected format to prevent unauthorized access. Keystore.trustedcertificateentry

An entry of this type contains a single public key certificate that belongs to the other party. It is called a trusted certificate because the owner of the KeyStore believes that the public key in the certificate does belong to the identity identified by the subject (owner) of the certificate.

Entries of this type can be used to authenticate other parties.

Each entry in the KeyStore is identified with an "alias" string. For private keys and their associated certificate chains, these strings are used to differentiate between the different ways in which entity validation can be used. For example, entities can authenticate themselves by using different certificate authorizations or different public-key algorithms.

Whether the alias is case-sensitive is related to the implementation. To avoid problems, it is recommended that you do not use aliases that are only case-sensitive in KeyStore.

It is not specified here whether the KeyStore is persistent or the mechanism used when the keystore is persisted. This allows the use of various techniques to protect sensitive (for example, private or secret) keys. One option is to use a smart card or other integrated encryption engine (SAFEKEYPER) or simpler mechanisms such as files (in various formats).

Typical ways to request KeyStore objects include using the default type and providing a specific KeyStore type. Use default type:

· KeyStore ks = Keystore.getinstance (Keystore.getdefaulttype ());

The system will return the default type of KeyStore implementation. Provide a specific KeyStore type:

· KeyStore KS = keystore.getinstance ("JKS");

The system returns the preferred implementation of the specified KeyStore type available in the environment.

KeyStore must be loaded before it can be accessed.

KeyStore ks = Keystore.getinstance (Keystore.getdefaulttype ());

Get user password and file input stream

char[] Password = GetPassword ();

Java.io.FileInputStream FIS = null;

try {

FIS = new Java.io.FileInputStream ("Keystorename");

Ks.load (FIS, password);

finally {

if (FIS!= null) {

Fis.close ();

}

}

To create an empty keystore using the Load method above, pass NULL as the InputStream parameter.

Once KeyStore is loaded, you can read existing entries from KeyStore, or write new entries to KeyStore:

Get my private key

Keystore.privatekeyentry pkentry = (keystore.privatekeyentry)

Ks.getentry ("Privatekeyalias", password);

Privatekey Myprivatekey = Pkentry.getprivatekey ();

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 ();

}

}

Note that you can use the same password to load KeyStore, protect private key entries, protect secret key entries, and store KeyStore (as shown in the example code above), or you can use different passwords or other protection parameters.

Example

Import Java.io.FileInputStream;

Import java.io.IOException;

Import Java.io.InputStream;

Import java.security.InvalidKeyException;

Import Java.security.KeyStore;

Import java.security.KeyStoreException;

Import java.security.NoSuchAlgorithmException;

Import java.security.NoSuchProviderException;

Import Java.security.PrivateKey;

Import java.security.SignatureException;

Import java.security.UnrecoverableKeyException;

Import Java.security.cert.Certificate;

Import java.security.cert.CertificateException;

Import Java.security.cert.CertificateFactory;

public class Keyreader {

public static void Main (string[] args) throws Keystoreexception,

Nosuchproviderexception, NoSuchAlgorithmException,

Certificateexception, IOException, Unrecoverablekeyexception,

InvalidKeyException, Signatureexception {

Open an input stream on the KeyStore file

String cerfilename = "D:/certa.cer";

String p12filename = "D:/CERTA.P12";

String Pfxpassword = "OpenSSL";

InputStream fis = new FileInputStream (p12filename);

Create a KeyStore Object

KeyStore KeyStore = keystore.getinstance ("PKCS12", "BC");

Load the file into the KeyStore

Keystore.load (FIS, Pfxpassword.tochararray ());

String aliaesname = "ABCD";

Privatekey Prikey = (Privatekey) (Keystore.getkey (aliaesname, null));

System.out.println ("Private key:/n" + Prikey);

Public key

InputStream is = new FileInputStream (cerfilename);

Certificatefactory CF = Certificatefactory.getinstance ("X509");

Certificate Cercert = Cf.generatecertificate (IS);

System.out.println ("Public key:/n" + Cercert);

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.