get Private Key from key store path and password - Java Security

Java examples for Security:Key

Description

get Private Key from key store path and password

Demo Code


//package com.java2s;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;

public class Main {


    public static final String KEY_STORE = "JKS";

    public static PrivateKey getPrivateKey(String keyStorePath,
            String alias, String passwd) {
        try {/* www.  ja v  a2s  . c  om*/
            KeyStore ks = getKeyStore(keyStorePath, passwd);
            if (ks.containsAlias(alias)) {
                Key key = ks.getKey(alias, passwd.toCharArray());
                return (PrivateKey) key;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static KeyStore getKeyStore(String keyStorePath, String passwd) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(keyStorePath);
            KeyStore ks = KeyStore.getInstance(KEY_STORE);
            ks.load(fis, passwd.toCharArray());
            return ks;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Related Tutorials