下面列出了java.security.KeyStore#isKeyEntry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected Object execute0() throws Exception {
KeyStore ks = getKeyStore();
String keyname = null;
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (ks.isKeyEntry(alias)) {
keyname = alias;
break;
}
}
if (keyname == null) {
throw new CmdFailure("could not find private key");
}
X509Certificate cert = (X509Certificate) ks.getCertificate(keyname);
saveVerbose("saved certificate to file", outFile, encodeCert(cert.getEncoded(), outform));
return null;
}
private boolean verifyKeyEntry(KeyStore ks) {
boolean isKeyEntry = false;
String alias = "";
Enumeration<String> e;
try {
e = ks.aliases();
while (e.hasMoreElements()) {
alias = e.nextElement();
if(ks.isKeyEntry(alias)) {
isKeyEntry = true;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return isKeyEntry;
}
private ApkSigner.SignerConfig loadKeyStore(String keyStoreType, String keyStorePassword) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
KeyStore keyStoreEntity = KeyStore.getInstance(keyStoreType == null ? KeyStore.getDefaultType() : keyStoreType);
char[] password = getPassword(keyStorePassword);
keyStoreEntity.load(null, password);
Enumeration<String> aliases = keyStoreEntity.aliases();
String keyAlias = null;
while (aliases != null && aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStoreEntity.isKeyEntry(alias)) {
keyAlias = alias;
break;
}
}
if (keyAlias == null) {
throw new IllegalArgumentException("Keystore has no key entries!");
}
PrivateKey privateKey = (PrivateKey) keyStoreEntity.getKey(keyAlias, password);
Certificate[] certificates = keyStoreEntity.getCertificateChain(keyAlias);
if (certificates == null || certificates.length == 0) {
throw new IllegalArgumentException("Unable to load certificates!");
}
List<X509Certificate> results = new LinkedList<>();
for (Certificate certificate : certificates) {
results.add((X509Certificate)certificate);
}
return new ApkSigner.SignerConfig.Builder("Signal Signer", privateKey, results).build();
}
SunX509KeyManagerImpl(KeyStore ks, char[] password)
throws KeyStoreException,
NoSuchAlgorithmException, UnrecoverableKeyException {
credentialsMap = new HashMap<String,X509Credentials>();
serverAliasCache = Collections.synchronizedMap(
new HashMap<String,String[]>());
if (ks == null) {
return;
}
for (Enumeration<String> aliases = ks.aliases();
aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
if (!ks.isKeyEntry(alias)) {
continue;
}
Key key = ks.getKey(alias, password);
if (key instanceof PrivateKey == false) {
continue;
}
Certificate[] certs = ks.getCertificateChain(alias);
if ((certs == null) || (certs.length == 0) ||
!(certs[0] instanceof X509Certificate)) {
continue;
}
if (!(certs instanceof X509Certificate[])) {
Certificate[] tmp = new X509Certificate[certs.length];
System.arraycopy(certs, 0, tmp, 0, certs.length);
certs = tmp;
}
X509Credentials cred = new X509Credentials((PrivateKey)key,
(X509Certificate[])certs);
credentialsMap.put(alias, cred);
if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) {
SSLLogger.fine("found key for : " + alias, (Object[])certs);
}
}
}
/**
* Create new ClientKey instance based on data provided in the stream together with the password
* @deprecated use
* @param inputStream expects a stream to the pk12 keystore with one pair of key/cert. Will be closed automatically
*/
public ClientKey(final InputStream inputStream, final String password) throws InvalidKeystoreException {
if(inputStream == null) {
throw new InvalidKeystoreException("Input stream of ClientKey cannot be NULL");
}
JavaCryptographyExtension.validateInstallation();
this.password = password;
String tempAlias = null;
final KeyStore keystore = getKeyStore(inputStream, password);
final Enumeration<String> aliases = getAliases(keystore);
while (aliases.hasMoreElements()) {
final String alias = aliases.nextElement();
try {
if (keystore.isKeyEntry(alias)) {
tempAlias = alias;
String certificateInfo = CertificateUtils.getCertificateInfo(keystore, alias);
logger.info(certificateInfo);
CertExpirationChecker.of(keystore, alias)
.whenExpiresIn(30, TimeUnit.DAYS)
.printWarningTo(logger);
}
} catch (final KeyStoreException e) {
logger.error(String.format("cannot check isKeyEntry(%s) - %s : %s", alias, e.getClass().getName(), e.getMessage()));
}
}
if (tempAlias == null) {
throw new InvalidKeystoreException("Keystore doesn't contain any keys!");
}
this.alias = tempAlias;
this.keyStore = keystore;
this.clientPasswordCallback = new ClientPasswordCallback(alias, password);
}
private void assertContainsKey(final KeyStore keyStore) throws StartException, KeyStoreException {
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
if (keyStore.isKeyEntry(aliases.nextElement())) {
return;
}
}
throw DomainManagementLogger.ROOT_LOGGER.noKey(path);
}
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
String inKeyPass, String outKeyPass) throws Exception {
Enumeration<String> e = inputKeyStore.aliases();
String alias;
while (e.hasMoreElements()) {
alias = e.nextElement();
Certificate[] certs = inputKeyStore.getCertificateChain(alias);
boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
// Test KeyStore only contain key pair entries.
if (isCertEntry == true) {
throw new RuntimeException(
"inputKeystore should not be certEntry because test"
+ " keystore only contain key pair entries"
+ " for alias:" + alias);
}
boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
Key key = null;
if (isKeyEntry) {
key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
} else {
throw new RuntimeException("Entry type unknown for alias:"
+ alias);
}
outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
certs);
}
}
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
String inKeyPass, String outKeyPass) throws Exception {
Enumeration<String> e = inputKeyStore.aliases();
String alias;
while (e.hasMoreElements()) {
alias = e.nextElement();
Certificate[] certs = inputKeyStore.getCertificateChain(alias);
boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
// Test KeyStore only contain key pair entries.
if (isCertEntry == true) {
throw new RuntimeException(
"inputKeystore should not be certEntry because test"
+ " keystore only contain key pair entries"
+ " for alias:" + alias);
}
boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
Key key = null;
if (isKeyEntry) {
key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
} else {
throw new RuntimeException("Entry type unknown for alias:"
+ alias);
}
outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
certs);
}
}
private static String findAlias(KeyStore ks) throws KeyStoreException {
Enumeration<String> e = ks.aliases();
while (e.hasMoreElements()) {
String entry = e.nextElement();
if (ks.isKeyEntry(entry)) {
return entry;
}
}
throw new KeyStoreException("Cannot find a private key entry");
}
private KeyCert readPfx(String path, String password) throws NoSuchProviderException, KeyStoreException,
IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
try (FileInputStream stream = new FileInputStream(path)) {
KeyCert keyCert = new KeyCert();
boolean isAliasWithPrivateKey = false;
final KeyStore store = KeyStore.getInstance("pkcs12", "SunJSSE");
store.load((InputStream) stream, password.toCharArray());
// Iterate over all aliases to find the private key
Enumeration<String> aliases = store.aliases();
String alias = "";
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
// Break if alias refers to a private key because we want to use that
// certificate
if (isAliasWithPrivateKey = store.isKeyEntry(alias)) {
break;
}
}
if (isAliasWithPrivateKey) {
// Retrieves the certificate from the Java keystore
X509Certificate certificate = (X509Certificate) store.getCertificate(alias);
PrivateKey key = (PrivateKey) store.getKey(alias, password.toCharArray());
keyCert.setCertificate(certificate);
keyCert.setKey(key);
}
return keyCert;
}
}
public static RSAPublicKey getPublicKey(KeyStore keyStore) throws Exception {
String key_aliases = null;
Enumeration<String> enumeration = keyStore.aliases();
key_aliases = enumeration.nextElement();
if (keyStore.isKeyEntry(key_aliases)) {
RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate(key_aliases).getPublicKey();
return publicKey;
}
return null;
}
private String[] getAliases(KeyStore ks) {
List aliases = new ArrayList();
try {
Enumeration en = ks.aliases();
while (en.hasMoreElements()) {
String alias = (String) en.nextElement();
if (ks.isKeyEntry(alias))
aliases.add(alias);
}
} catch (KeyStoreException kse) {
kse.printStackTrace();
}
return (String[]) aliases.toArray(new String[0]);
}
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
String inKeyPass, String outKeyPass) throws Exception {
Enumeration<String> e = inputKeyStore.aliases();
String alias;
while (e.hasMoreElements()) {
alias = e.nextElement();
Certificate[] certs = inputKeyStore.getCertificateChain(alias);
boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
// Test KeyStore only contain key pair entries.
if (isCertEntry == true) {
throw new RuntimeException(
"inputKeystore should not be certEntry because test"
+ " keystore only contain key pair entries"
+ " for alias:" + alias);
}
boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
Key key = null;
if (isKeyEntry) {
key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
} else {
throw new RuntimeException("Entry type unknown for alias:"
+ alias);
}
outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
certs);
}
}
/**
* Gets the initialized key managers.
*/
protected KeyManager[] getKeyManagers(String keystoreType,
String keystoreProvider,
String algorithm,
String keyAlias)
throws Exception {
KeyManager[] kms = null;
String keystorePass = getKeystorePassword();
KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
throw new IOException(
sm.getString("jsse.alias_no_key_entry", keyAlias));
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
String keyPass = endpoint.getKeyPass();
if (keyPass == null) {
keyPass = keystorePass;
}
kmf.init(ks, keyPass.toCharArray());
kms = kmf.getKeyManagers();
if (keyAlias != null) {
String alias = keyAlias;
if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
alias = alias.toLowerCase(Locale.ENGLISH);
}
for(int i=0; i<kms.length; i++) {
kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
}
}
return kms;
}
/**
* Get the keystore entry's head certificate.
*
* @param sEntryAlias Entry alias
* @return The keystore entry's head certificate
* @throws CryptoException Problem getting head certificate
*/
private X509Certificate getHeadCert(String sEntryAlias)
throws CryptoException
{
try
{
// Get keystore
KeyStore keyStore = m_keyStoreWrap.getKeyStore();
// Get the entry's head certificate
X509Certificate cert;
if (keyStore.isKeyEntry(sEntryAlias))
{
cert = X509CertUtil.orderX509CertChain(
X509CertUtil.convertCertificates(keyStore.getCertificateChain(sEntryAlias)))[0];
}
else
{
cert = X509CertUtil.convertCertificate(keyStore.getCertificate(sEntryAlias));
}
return cert;
}
catch (KeyStoreException ex)
{
String sMessage = MessageFormat.format(RB.getString("FPortecle.NoAccessEntry.message"), sEntryAlias);
throw new CryptoException(sMessage, ex);
}
}
public void runTest(Provider p) throws Exception {
try (FileOutputStream fos = new FileOutputStream("jceks");
FileInputStream fis = new FileInputStream("jceks");) {
KeyStore ks = KeyStore.getInstance("jceks", p);
// create an empty key store
ks.load(null, null);
// store the secret keys
String aliasHead = new String("secretKey");
for (int j = 0; j < NUM_ALGOS; j++) {
ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
}
// write the key store out to a file
ks.store(fos, PASSWDF);
// wipe clean the existing key store
for (int k = 0; k < NUM_ALGOS; k++) {
ks.deleteEntry(aliasHead + k);
}
if (ks.size() != 0) {
throw new RuntimeException("ERROR: re-initialization failed");
}
// reload the key store with the file
ks.load(fis, PASSWDF);
// check the integrity/validaty of the key store
Key temp = null;
String alias = null;
if (ks.size() != NUM_ALGOS) {
throw new RuntimeException("ERROR: wrong number of key"
+ " entries");
}
for (int m = 0; m < ks.size(); m++) {
alias = aliasHead + m;
temp = ks.getKey(alias, PASSWDK);
// compare the keys
if (!temp.equals(sks[m])) {
throw new RuntimeException("ERROR: key comparison (" + m
+ ") failed");
}
// check the type of key
if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
throw new RuntimeException("ERROR: type identification ("
+ m + ") failed");
}
}
}
}
private void readTest(String inKeyStore) throws Exception {
KeyStore inputKeyStore;
// Initialize KeyStore
String dir = System.getProperty("test.src", ".");
String keystorePath = dir + File.separator + "certs" + File.separator
+ "readP12";
inputKeyStore = KeyStore
.getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
// KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
// first.
byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
.getMimeDecoder().decode(input));
inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
out.println("Initialize KeyStore : " + inKeyStore + " success");
out.println("getProvider : " + inputKeyStore.getProvider());
out.println("getType : " + inputKeyStore.getType());
out.println("getDefaultType : " + KeyStore.getDefaultType());
int idx = 0;
Enumeration<String> e = inputKeyStore.aliases();
String alias;
while (e.hasMoreElements()) {
alias = e.nextElement();
out.println("Alias " + idx + " : " + alias);
if (inputKeyStore.containsAlias(alias) == false) {
throw new RuntimeException("Alias not found");
}
out.println("getCreationDate : "
+ inputKeyStore.getCreationDate(alias));
X509Certificate cert = (X509Certificate) inputKeyStore
.getCertificate(alias);
out.println("getCertificate : " + cert.getSubjectDN());
String retAlias = inputKeyStore.getCertificateAlias(cert);
if (!retAlias.equals(alias)) {
throw new RuntimeException("Alias mismatch");
}
out.println("getCertificateAlias : " + retAlias);
Certificate[] certs = inputKeyStore.getCertificateChain(alias);
for (int i = 0; i < certs.length; i++) {
out.println("getCertificateChain " + i + " : "
+ ((X509Certificate) certs[i]).getSubjectDN());
}
boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
// test KeyStore only contain key pair entries.
if (isCertEntry == true) {
throw new RuntimeException(
"inputKeystore should not be certEntry because test keystore only contain key pair entries.");
}
boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
if (isKeyEntry) {
Key key = inputKeyStore.getKey(alias,
IN_STORE_PASS.toCharArray());
out.println("Key : " + key.toString());
} else {
throw new RuntimeException("Entry type unknown\n");
}
idx++;
}
int size = inputKeyStore.size();
if (idx != size) {
throw new RuntimeException("Size not match");
}
}
public static KeypairWithCert fromKeystore(KeyStore keystore,
String keyname, char[] keyPassword, X509Cert[] certchain)
throws XiSecurityException {
Args.notNull(keyPassword, "keyPassword");
try {
String tmpKeyname = keyname;
if (tmpKeyname == null) {
Enumeration<String> aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keystore.isKeyEntry(alias)) {
tmpKeyname = alias;
break;
}
}
} else {
if (!keystore.isKeyEntry(tmpKeyname)) {
throw new XiSecurityException("unknown key named " + tmpKeyname);
}
}
PrivateKey key = (PrivateKey) keystore.getKey(tmpKeyname, keyPassword);
if (!(key instanceof RSAPrivateKey || key instanceof DSAPrivateKey
|| key instanceof ECPrivateKey
|| key instanceof EdDSAKey || key instanceof XDHKey)) {
throw new XiSecurityException("unsupported key " + key.getClass().getName());
}
Set<X509Cert> caCerts = new HashSet<>();
X509Cert cert;
if (certchain != null && certchain.length > 0) {
cert = certchain[0];
final int n = certchain.length;
if (n > 1) {
for (int i = 1; i < n; i++) {
caCerts.add(certchain[i]);
}
}
} else {
cert = new X509Cert((X509Certificate) keystore.getCertificate(tmpKeyname));
}
Certificate[] certsInKeystore = keystore.getCertificateChain(tmpKeyname);
if (certsInKeystore.length > 1) {
for (int i = 1; i < certsInKeystore.length; i++) {
caCerts.add(new X509Cert((X509Certificate) certsInKeystore[i]));
}
}
X509Cert[] certificateChain = X509Util.buildCertPath(cert, caCerts);
return new KeypairWithCert(key, certificateChain);
} catch (KeyStoreException | NoSuchAlgorithmException
| UnrecoverableKeyException | ClassCastException | CertPathBuilderException ex) {
throw new XiSecurityException(ex.getMessage(), ex);
}
}
private static void createKeyStoreFromPemKey(
String clientCert,
String clientPass,
KeyStore store ) throws Exception {
try {
// Load CA Chain file
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// X509Certificate cert = (X509Certificate) cf.generateCertificate(new FileInputStream(caCert));
store.load(null);
// Load client's public and private keys from PKCS12 certificate
KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(clientCert);
char[] nPassword = null;
if ( (clientPass == null) || "".equals(clientPass.trim())) {
nPassword = null;
} else {
nPassword = clientPass.toCharArray();
}
inputKeyStore.load(fis, nPassword);
fis.close();
store.load(null, ( (clientPass != null)
? clientPass.toCharArray()
: null));
Enumeration<String> en = inputKeyStore.aliases();
while (en.hasMoreElements()) { // we are reading just one certificate.
String keyAlias = en.nextElement();
if (inputKeyStore.isKeyEntry(keyAlias)) {
Key key = inputKeyStore.getKey(keyAlias, nPassword);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
store.setKeyEntry("outkey",
key,
( (clientPass != null)
? clientPass.toCharArray()
: null),
certChain);
}
}
} catch (Exception e) {
throw new RuntimeException("Error creating keystore from Pem key", e);
}
}
/**
* Is the named entry in the KeyStore a key pair entry?
*
* @param alias
* Alias
* @param keyStore
* KeyStore
* @return True if it is, false otherwise
* @throws KeyStoreException
* If there was a problem accessing the KeyStore.
*/
public static boolean isKeyPairEntry(String alias, KeyStore keyStore) throws KeyStoreException {
return keyStore.isKeyEntry(alias)
&& keyStore.getCertificateChain(alias) != null && keyStore.getCertificateChain(alias).length != 0;
}