Java 类java.security.KeyStore.Entry 实例源码

项目:AgentWorkbench    文件:KeyStoreController.java   
public void printAliasesList(String keyPasswd) {
    try {
        System.out.println("trustStoreType=" + trustStore.getType());
        System.out.println("size=" + trustStore.size());

        // --- Get All TrustStore's Certificates Alias -----------
        Enumeration<String> enumeration = trustStore.aliases();
        while (enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias=" + alias);
            // Entry entry = trustStore.getEntry(alias, null);

            Entry entry = trustStore.getEntry(alias, new PasswordProtection(keyPasswd.toCharArray()));

            System.out.println("entryClass=" + entry.getClass());
        }
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
        e.printStackTrace();
    }
}
项目:xtf    文件:XTFKeyStore.java   
public void addSelfSignedCertificate(String certificateAlias, String dn, String password) {
    try {
        KeyPair keys = generateKeyPair();

        Calendar start = Calendar.getInstance();
        Calendar expiry = Calendar.getInstance();
        expiry.add(Calendar.YEAR, 1);
        X500Name name = new X500Name(dn);
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, BigInteger.ONE,
                start.getTime(), expiry.getTime(), name, SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded()));
        ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(new BouncyCastleProvider()).build(keys.getPrivate());
        X509CertificateHolder holder = certificateBuilder.build(signer);
        Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

        Entry entry = new PrivateKeyEntry(keys.getPrivate(), new Certificate[]{ cert });
        keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
    } catch (GeneralSecurityException | OperatorCreationException ex) {
        throw new RuntimeException("Unable to generate self-signed certificate", ex);
    }
}
项目:xtf    文件:XTFKeyStore.java   
/**
 * Asymmetric cryptography - only the private key from generated pair is used.
 * Pre-condition: #certificateAlias refers to existing certificate
 *
 * @throws {@link NullPointerException} when #certificateAlias is @code{null}
 */
public void addPrivateKey(String keyAlias, String certificateAlias, String password) {
    keyAlias = String.format("%s (%s)", keyAlias, certificateAlias);

    try {
        Certificate[] certChain = keystore.getCertificateChain(certificateAlias);
        if (certChain == null) {
            LoggerFactory.getLogger(getClass()).warn("Could not find certificate");
            certChain = new Certificate[0];
        }
        Entry entry = new PrivateKeyEntry(generateKeyPair().getPrivate(), certChain);
        ProtectionParameter protParam = new KeyStore.PasswordProtection(password.toCharArray());
        keystore.setEntry(keyAlias, entry, protParam);
    } catch (KeyStoreException | NoSuchAlgorithmException ex) {
        throw new RuntimeException("Unable to add new private key", ex);
    }
}
项目:commons-eid    文件:JCATest.java   
@Test
public void testRRNCertificate() throws Exception {
    // setup
    Security.addProvider(new BeIDProvider());
    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    // operate
    assertTrue(keyStore.containsAlias("RRN"));
    Entry entry = keyStore.getEntry("RRN", null);
    assertNotNull(entry);
    assertTrue(entry instanceof TrustedCertificateEntry);
    TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry;
    assertNotNull(trustedCertificateEntry.getTrustedCertificate());
    assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal()
            .toString().contains("RRN"));
    assertNotNull(keyStore.getCertificate("RRN"));
    Certificate[] certificateChain = keyStore.getCertificateChain("RRN");
    assertNotNull(certificateChain);
    assertEquals(2, certificateChain.length);
    LOGGER.debug("RRN subject: {}", ((X509Certificate) certificateChain[0]).getSubjectX500Principal());
    LOGGER.debug("RRN issuer: {}", ((X509Certificate) certificateChain[0]).getIssuerX500Principal());
    LOGGER.debug("root subject: {}", ((X509Certificate) certificateChain[1]).getSubjectX500Principal());
    LOGGER.debug("root issuer: {}", ((X509Certificate) certificateChain[1]).getIssuerX500Principal());
}
项目:commons-eid    文件:BeIDKeyStore.java   
@Override
public Entry engineGetEntry(String alias, ProtectionParameter protParam)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
    LOGGER.debug("engineGetEntry: {}", alias);
    if ("Authentication".equals(alias) || "Signature".equals(alias)) {
        PrivateKey privateKey = (PrivateKey) engineGetKey(alias, null);
        Certificate[] chain = engineGetCertificateChain(alias);
        PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain);
        return privateKeyEntry;
    }
    if ("CA".equals(alias) || "Root".equals(alias) || "RRN".equals(alias)) {
        Certificate certificate = engineGetCertificate(alias);
        TrustedCertificateEntry trustedCertificateEntry = new TrustedCertificateEntry(certificate);
        return trustedCertificateEntry;
    }
    return super.engineGetEntry(alias, protParam);
}
项目:picketbox    文件:PicketBoxSecurityVault.java   
private void checkAndConvertKeyStoreToJCEKS(String keystoreURL) throws Exception {
   if (keystore.getType().equalsIgnoreCase("JKS")) {

      // backup original keystore file
      copyFile(new File(keystoreURL), new File(keystoreURL + ".original"));

      KeyStore jceks = KeyStoreUtil.createKeyStore("JCEKS", keyStorePWD);

      Enumeration<String> aliases = keystore.aliases();
      while (aliases.hasMoreElements()) {
         String entryAlias = aliases.nextElement();
         KeyStore.PasswordProtection p = new KeyStore.PasswordProtection(keyStorePWD);
         KeyStore.Entry e = keystore.getEntry(entryAlias, p);
         jceks.setEntry(entryAlias, e, p);
      }
      keystore = jceks;
      keyStoreType = "JCEKS"; // after conversion we have to change keyStoreType to the one we really have
      saveKeyStoreToFile(keystoreURL);
      PicketBoxLogger.LOGGER.keyStoreConvertedToJCEKS(KEYSTORE_URL);
   }
}
项目:aws-dynamodb-encryption-java    文件:KeyStoreMaterialsProvider.java   
private static KeyPair entry2Pair(Entry entry) {
    PublicKey pub = null;
    PrivateKey priv = null;

    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry pk = (PrivateKeyEntry) entry;
        if (pk.getCertificate() != null) {
            pub = pk.getCertificate().getPublicKey();
        }
        priv = pk.getPrivateKey();
    } else if (entry instanceof TrustedCertificateEntry) {
        TrustedCertificateEntry tc = (TrustedCertificateEntry) entry;
        pub = tc.getTrustedCertificate().getPublicKey();
    } else {
        throw new IllegalArgumentException(
                "Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported.");
    }
    return new KeyPair(pub, priv);
}
项目:aws-dynamodb-encryption-java    文件:KeyStoreMaterialsProvider.java   
public CurrentMaterials(Entry encryptionEntry, Entry signingEntry) {
    super();
    this.encryptionEntry = encryptionEntry;
    this.signingEntry = signingEntry;

    if (encryptionEntry instanceof SecretKeyEntry) {
        if (signingEntry instanceof SecretKeyEntry) {
            this.symRawMaterials = new SymmetricRawMaterials(
                    ((SecretKeyEntry) encryptionEntry).getSecretKey(),
                    ((SecretKeyEntry) signingEntry).getSecretKey(),
                    description);
        } else {
            this.symRawMaterials = new SymmetricRawMaterials(
                    ((SecretKeyEntry) encryptionEntry).getSecretKey(),
                    entry2Pair(signingEntry),
                    description);
        }
    } else {
        this.symRawMaterials = null;
    }
}
项目:JavaCommon    文件:MapDemo.java   
public static void statis(String str, int top) {
    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    char[] cs = str.toCharArray();
    for (char c : cs) {
        if (null == hashMap.get(c)) {
            hashMap.put(c, 1);
        } else {
            hashMap.put(c, hashMap.get(c) + 1);
        }
    }
    // 把entry取出来进行排序
    List<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(hashMap.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
        public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
            return (o2.getValue() - o1.getValue());
        }
    });
    for (int i = 0; i < top; i++) {
        if (i < list.size()) {
            System.out.println(list.get(i).getKey() + "--" + list.get(i).getValue());
        }
    }
    // 只把value取出来
    List<Integer> valueList = new ArrayList<>(hashMap.values());
    Collections.sort(valueList, new Comparator<Integer>() {
        @Override
        public int compare(Integer a, Integer b) {
            return b.compareTo(a);
        }
    });
    for (int i = 0; i < top; i++) {
        if (i < valueList.size()) {
            System.out.println(valueList.get(i));
        }
    }
}
项目:oscm    文件:CopyKeyTask.java   
private Entry loadEntry(final EntryDescriptor descr) throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore(descr);
    final Entry entry = keystore.getEntry(descr.getAlias(),
            createProtection(descr));
    if (entry == null) {
        throw new BuildException(String.format(
                "No entry %s found in keystore %s.", descr.getAlias(),
                descr.getKeystore()));
    }
    return entry;
}
项目:oscm    文件:SignTask.java   
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
项目:xtf    文件:XTFKeyStore.java   
public void addSignedCertificate(final XTFKeyStore signerKeyStore, final String signerAlias, final String signerPassword, final String dn, final String certificateAlias, final String password) {
    try {
        final X509Certificate caCert = (X509Certificate) signerKeyStore.keystore.getCertificate(signerAlias);
        final PrivateKey caKey = (PrivateKey) signerKeyStore.keystore.getKey(signerAlias, signerPassword.toCharArray());
        final Calendar start = Calendar.getInstance();
        final Calendar expiry = Calendar.getInstance();
        expiry.add(Calendar.YEAR, 1);
        final KeyPair keyPair = generateKeyPair();
        final X500Name certName = new X500Name(dn);
        final X500Name issuerName = new X500Name(caCert.getSubjectDN().getName());
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                issuerName,
                BigInteger.valueOf(System.nanoTime()),
                start.getTime(),
                expiry.getTime(),
                certName,
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
        final JcaX509ExtensionUtils u = new JcaX509ExtensionUtils();
        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                u.createAuthorityKeyIdentifier(caCert));
        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                u.createSubjectKeyIdentifier(keyPair.getPublic()));
        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(caKey);
        X509CertificateHolder holder = certificateBuilder.build(signer);
        Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

        Entry entry = new PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] {cert, caCert});
        keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
    } catch (GeneralSecurityException | OperatorCreationException | CertIOException ex) {
        throw new RuntimeException("Unable to generate signed certificate", ex);
    }
}
项目:aws-encryption-sdk-java    文件:KeyStoreProvider.java   
private JceMasterKey internalGetMasterKey(final String provider, final String keyId) {
    final Entry entry;
    try {
        entry = keystore_.getEntry(keyId, keystore_.isKeyEntry(keyId) ? protection_ : null);
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        throw new UnsupportedProviderException(e);
    }
    if (entry == null) {
        throw new NoSuchMasterKeyException();
    }
    if (entry instanceof SecretKeyEntry) {
        final SecretKeyEntry skEntry = (SecretKeyEntry) entry;
        if (!skEntry.getSecretKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(skEntry.getSecretKey(), provider, keyId, wrappingAlgorithm_);
    } else if (entry instanceof PrivateKeyEntry) {
        final PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry;
        if (!pkEntry.getPrivateKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey(), provider,
                keyId, wrappingAlgorithm_);
    } else if (entry instanceof TrustedCertificateEntry) {
        final TrustedCertificateEntry certEntry = (TrustedCertificateEntry) entry;
        if (!certEntry.getTrustedCertificate().getPublicKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(certEntry.getTrustedCertificate().getPublicKey(), null, provider, keyId,
                wrappingAlgorithm_);
    } else {
        throw new NoSuchMasterKeyException();
    }
}
项目:development    文件:CopyKeyTask.java   
private Entry loadEntry(final EntryDescriptor descr) throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore(descr);
    final Entry entry = keystore.getEntry(descr.getAlias(),
            createProtection(descr));
    if (entry == null) {
        throw new BuildException(String.format(
                "No entry %s found in keystore %s.", descr.getAlias(),
                descr.getKeystore()));
    }
    return entry;
}
项目:development    文件:SignTask.java   
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
项目:LoboBrowser    文件:TrustManager.java   
public static SSLSocketFactory makeSSLSocketFactory(final InputStream extraCertsStream) {
  final String sep = File.separator;
  final String hardDefaultPath = System.getProperty("java.home") + sep + "lib" + sep + "security" + sep + "cacerts";
  final String defaultStorePath = System.getProperty("javax.net.ssl.trustStore", hardDefaultPath);
  try (
      final FileInputStream defaultIS = new FileInputStream(defaultStorePath)) {

    final KeyStore defKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    defKeyStore.load(defaultIS, "changeit".toCharArray());

    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(extraCertsStream, null);

    // final KeyStore keyStore =  KeyStore.Builder.newInstance(defKeyStore, null).getKeyStore();
    final Enumeration<String> aliases = defKeyStore.aliases();
    while (aliases.hasMoreElements()) {
      final String alias = aliases.nextElement();
      if (defKeyStore.isCertificateEntry(alias)) {
        final Entry entry = defKeyStore.getEntry(alias, null);
        keyStore.setEntry(alias, entry, null);
      }
    }

    final TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    final SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, tmf.getTrustManagers(), null);
    return sc.getSocketFactory();
  } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | IOException | CertificateException
      | UnrecoverableEntryException e) {
    throw new RuntimeException(e);
  }

}
项目:In-the-Box-Fork    文件:KeyStoreTest.java   
public static void assertPrivateKey(Entry actual)
        throws Exception {
    assertSame(PrivateKeyEntry.class, actual.getClass());
    PrivateKeyEntry privateKey = (PrivateKeyEntry) actual;
    assertEquals(PRIVATE_KEY.getPrivateKey(), privateKey.getPrivateKey());
    assertEquals(PRIVATE_KEY.getCertificate(), privateKey.getCertificate());
    assertEquals(Arrays.asList(PRIVATE_KEY.getCertificateChain()),
                 Arrays.asList(privateKey.getCertificateChain()));
}
项目:aws-dynamodb-encryption-java    文件:KeyStoreMaterialsProvider.java   
private void loadKeys() throws NoSuchAlgorithmException, UnrecoverableEntryException,
        KeyStoreException {
    Entry encryptionEntry = keyStore.getEntry(encryptionAlias, encryptionProtection);
    Entry signingEntry = keyStore.getEntry(signingAlias, signingProtection);
    CurrentMaterials newMaterials = new CurrentMaterials(encryptionEntry, signingEntry);
    currMaterials.set(newMaterials);
}
项目:Ignite    文件:SecureEncrypter.java   
/**
 * Initialize the secure secret key
 * 
 * @return
 * @throws Exception
 */
private static SecretKey initKey() throws Exception {

    KeyStore keyStore = null;

    // create the keystore if it doesn't exist
    File keyStoreFile = new File(KEYSTORE_LOCATION);
    keyStore = loadKeyStore(keyStoreFile, SECRET_KEY);

    PasswordProtection keyPassword = new PasswordProtection(
            SECRET_KEY.toCharArray());

    if (!keyStore.containsAlias(SystemConstants.APP_NAME)) {
        // create new key, store in the keystore
        keyGenerator = KeyGenerator.getInstance("AES");
        Logger.debug("SecureEncrypter init: Crypto Provider ["
                + keyGenerator.getProvider().getName()
                + "] creating new key for app: " + SystemConstants.APP_NAME);
        keyGenerator.init(KEY_SIZE);
        secretKey = keyGenerator.generateKey();

        // store the secret key
        KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(
                secretKey);

        keyStore.setEntry(SystemConstants.APP_NAME, keyStoreEntry,
                keyPassword);
        keyStore.store(new FileOutputStream(keyStoreFile),
                SECRET_KEY.toCharArray());
    }

    Entry entry = keyStore.getEntry(SystemConstants.APP_NAME, keyPassword);
    SecretKey key = ((KeyStore.SecretKeyEntry) entry).getSecretKey();

    return key;
}
项目:SamlSnort    文件:KeyStoreTool.java   
public static Entry getEntry(String alias) throws KeyStoreException,
        NoSuchAlgorithmException, UnrecoverableEntryException {
    LOGGER.entering(KeyStoreTool.class.getName(), "getEntry", alias);

    Entry result = keyStore.getEntry(alias,
            new KeyStore.PasswordProtection(Configuration.getInstance()
                    .getKeystorePassword().toCharArray()));

    LOGGER.exiting(KeyStoreTool.class.getName(), "getEntry", result);

    return result;
}
项目:commons-eid    文件:BeIDKeyStore.java   
@Override
public void engineSetEntry(String alias, Entry entry, ProtectionParameter protParam) throws KeyStoreException {
    LOGGER.debug("engineSetEntry: {}", alias);
    super.engineSetEntry(alias, entry, protParam);
}
项目:commons-eid    文件:BeIDKeyStore.java   
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends Entry> entryClass) {
    LOGGER.debug("engineEntryInstanceOf: {}", alias);
    return super.engineEntryInstanceOf(alias, entryClass);
}
项目:In-the-Box-Fork    文件:KeyStoreTest.java   
public static void assertSecretKey(Entry actual)
        throws Exception {
    assertSame(SecretKeyEntry.class, actual.getClass());
    assertEquals(SECRET_KEY, ((SecretKeyEntry) actual).getSecretKey());
}
项目:In-the-Box-Fork    文件:KeyStoreTest.java   
public static void assertCertificate(Entry actual)
        throws Exception {
    assertSame(TrustedCertificateEntry.class, actual.getClass());
    assertEquals(PRIVATE_KEY.getCertificate(),
                 ((TrustedCertificateEntry) actual).getTrustedCertificate());
}
项目:picketbox    文件:PicketBoxSecurityVault.java   
@SuppressWarnings("unchecked")
private void convertVaultContent(String keystoreURL, String alias) throws Exception {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Map<String, byte[]> theContent;

    try {
        fis = new FileInputStream(decodedEncFileDir + ENCODED_FILE);
        ois = new ObjectInputStream(fis);
        theContent = (Map<String, byte[]>) ois.readObject();
    } finally {
        safeClose(fis);
        safeClose(ois);
    }

    // create new SecurityVaultData object for transformed vault data
    vaultContent = new SecurityVaultData();

    adminKey = null;
    for (String key: theContent.keySet()) {
        if (key.equals(ADMIN_KEY)) {
            byte[] admin_key = theContent.get(key);
            adminKey = new SecretKeySpec(admin_key, encryptionAlgorithm);
        }
        else {
            if (key.contains("_")) {
                StringTokenizer tokenizer = new StringTokenizer(key, "_");
                String vaultBlock = tokenizer.nextToken();
                String attributeName = tokenizer.nextToken();
                if (tokenizer.hasMoreTokens()) {
                    attributeName = key.substring(vaultBlock.length() + 1);
                    PicketBoxLogger.LOGGER.ambiguosKeyForSecurityVaultTransformation("_", vaultBlock, attributeName);
                }
                byte[] encodedAttributeValue = theContent.get(key);
                vaultContent.addVaultData(alias, vaultBlock, attributeName, encodedAttributeValue);
            }
        }
    }
    if (adminKey == null) {
        throw PicketBoxMessages.MESSAGES.missingAdminKeyInOriginalVaultData();
    }

    // add secret key (admin_key) to keystore 
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(adminKey);
    KeyStore.PasswordProtection p = new KeyStore.PasswordProtection(keyStorePWD);
    Entry e = keystore.getEntry(alias, p);
    if (e != null) {
       // rename the old entry
       String originalAlias = alias + "-original";
       keystore.setEntry(originalAlias, e, p);
       keystore.deleteEntry(alias);
    }
    keystore.setEntry(alias, skEntry, new KeyStore.PasswordProtection(keyStorePWD));

    // save the current keystore
    saveKeyStoreToFile(keystoreURL);

    // backup original vault file (shared key file cannot be saved for obvious reasons
    copyFile(new File(decodedEncFileDir + ENCODED_FILE), new File(decodedEncFileDir + ENCODED_FILE + ".original"));

    // save vault data file
    writeVaultData();

    // delete original vault files
    File f = new File(decodedEncFileDir + ENCODED_FILE);
    if (!f.delete()) {
        PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
    }
    f = new File(decodedEncFileDir + SHARED_KEY_FILE);
    if (!f.delete()) {
        PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
    }

}