Java Code Examples for java.security.KeyStore#getCertificate()

The following examples show how to use java.security.KeyStore#getCertificate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetadataEmptyTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 2
Source File: EuropeanIdentityConfigurationTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldUseComplianceEnvironmentConfigExceptOverriddenWithMetadataSourceUriOnly() throws Exception {
    KeyStore complianceKeyStore = new KeyStoreLoader().load(ResourceHelpers.resourceFilePath(TEST_METADATA_TRUSTSTORE),DEFAULT_TRUST_STORE_PASSWORD);
    Certificate complianceEntryCert =  complianceKeyStore.getCertificate(IDAMETADATA);

    EuropeanIdentityConfiguration europeanIdentityConfiguration = OBJECT_MAPPER.readValue(configWithMetadataSourceUri, EuropeanIdentityConfiguration.class);
    europeanIdentityConfiguration.setEnvironment(HubEnvironment.COMPLIANCE_TOOL);
    Certificate europeanConfigCert =  europeanIdentityConfiguration.getTrustStore().getCertificate(IDAMETADATA);

    assertThat(europeanIdentityConfiguration.getTrustStore().containsAlias(IDACA)).isTrue();
    assertThat(europeanIdentityConfiguration.getTrustStore().containsAlias(IDAMETADATA)).isTrue();
    assertThat(europeanIdentityConfiguration.getTrustStore().size()).isEqualTo(2);
    assertThat(europeanConfigCert).isEqualTo(complianceEntryCert);

    assertThat(europeanIdentityConfiguration.getTrustAnchorUri()).isEqualTo(HubEnvironment.COMPLIANCE_TOOL.getEidasMetadataTrustAnchorUri());
    assertThat(europeanIdentityConfiguration.getMetadataSourceUri().toString()).isEqualTo(overriddenMetadataSourceUri);

}
 
Example 3
Source File: KeyStoreUtil.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the key pair from the keystore
 * @param keystore
 * @param alias
 * @param password
 * @return
 * @throws Exception
 */
public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) throws Exception
{ 
   // Get private key
   Key key = keystore.getKey(alias, password);
   if (key instanceof PrivateKey) 
   {
      // Get certificate of public key
      java.security.cert.Certificate cert = keystore.getCertificate(alias);

      // Get public key
      PublicKey publicKey = cert.getPublicKey();

      // Return a key pair
      return new KeyPair(publicKey, (PrivateKey)key);
   }
   return null;
}
 
Example 4
Source File: NewSize7.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, null);
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example 5
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
void loadSigningKeys(String path, String alias) {
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(path).toFile());

        keyStore.load(keyStream, "changeit".toCharArray());
        kmf.init(keyStore, "changeit".toCharArray());

        this.signingCertificate = (X509Certificate) keyStore.getCertificate(alias);

        this.signingCredential = new BasicX509Credential(this.signingCertificate,
                (PrivateKey) keyStore.getKey(alias, "changeit".toCharArray()));

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: NewSize7.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, null);
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example 7
Source File: ImportCertCommand.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected CommandResult importPrivateKey(AliasedCertificateFactory certFx, String alias, String filename, String password) throws Exception {
    KeyStore ks = AS2Util.getCryptoHelper().getKeyStore();
    ks.load(new FileInputStream(filename), password.toCharArray());

    Enumeration<String> aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
        String certAlias = aliases.nextElement();
        Certificate cert = ks.getCertificate(certAlias);

        if (cert instanceof X509Certificate) {
            certFx.addCertificate(alias, (X509Certificate) cert, true);

            Key certKey = ks.getKey(certAlias, password.toCharArray());
            certFx.addPrivateKey(alias, certKey, password);

            return new CommandResult(CommandResult.TYPE_OK, "Imported certificate and key: " + cert.toString());
        }
    }

    return new CommandResult(CommandResult.TYPE_ERROR, "No valid X509 certificates found");

}
 
Example 8
Source File: NewSize7.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, null);
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example 9
Source File: ProGradePolicy.java    From pro-grade with Apache License 2.0 6 votes vote down vote up
/**
 * Private method for gaining X500Principal from keystore according its alias.
 * 
 * @param alias alias of principal
 * @param keystore KeyStore which is used by this policy file
 * @return name of gained X500Principal
 * @throws Exception when there was any problem during gaining Principal
 */
private String gainPrincipalFromAlias(String alias, KeyStore keystore) throws Exception {
    if (keystore == null) {
        return null;
    }
    if (!keystore.containsAlias(alias)) {
        return null;
    }

    Certificate certificate = keystore.getCertificate(alias);
    if (certificate == null || !(certificate instanceof X509Certificate)) {
        return null;
    }

    X509Certificate x509Certificate = (X509Certificate) certificate;
    X500Principal principal = new X500Principal(x509Certificate.getSubjectX500Principal().toString());
    return principal.getName();
}
 
Example 10
Source File: AnchorCertificates.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
public Void run() {
    File f = new File(StaticProperty.javaHome(),
            "lib/security/cacerts");
    KeyStore cacerts;
    try {
        cacerts = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream(f)) {
            cacerts.load(fis, null);
            certs = new HashSet<>();
            Enumeration<String> list = cacerts.aliases();
            String alias;
            while (list.hasMoreElements()) {
                alias = list.nextElement();
                // Check if this cert is labeled a trust anchor.
                if (alias.contains(" [jdk")) {
                    X509Certificate cert = (X509Certificate) cacerts
                            .getCertificate(alias);
                    certs.add(X509CertImpl.getFingerprint(HASH, cert));
                }
            }
        }
    } catch (Exception e) {
        if (debug != null) {
            debug.println("Error parsing cacerts");
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 11
Source File: StartDateTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 12
Source File: StartDateTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 13
Source File: PaymentProtocolTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = PkiVerificationException.class)
public void testSignAndVerifyExpired() throws Exception {
    Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();

    // Sign
    KeyStore keyStore = X509Utils.loadKeyStore("JKS", "password",
            getClass().getResourceAsStream("test-expired-cert"));
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-expired", "password".toCharArray());
    X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-expired");
    PaymentProtocol.signPaymentRequest(paymentRequest, new X509Certificate[]{clientCert}, privateKey);

    // Verify
    PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
}
 
Example 14
Source File: LdapTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void testLdapKeyStoreService(String keystoreName, String alias) throws Exception {
    ServiceName serviceName = Capabilities.KEY_STORE_RUNTIME_CAPABILITY.getCapabilityServiceName(keystoreName);
    KeyStore keyStore = (KeyStore) services.getContainer().getService(serviceName).getValue();
    Assert.assertNotNull(keyStore);

    Assert.assertTrue(keyStore.containsAlias(alias));
    Assert.assertTrue(keyStore.isKeyEntry(alias));
    X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
    Assert.assertEquals("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=Firefly", cert.getSubjectDN().getName());
    Assert.assertEquals(alias, keyStore.getCertificateAlias(cert));

    Certificate[] chain = keyStore.getCertificateChain(alias);
    Assert.assertEquals("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=Firefly", ((X509Certificate) chain[0]).getSubjectDN().getName());
    Assert.assertEquals("O=Root Certificate Authority, [email protected], C=UK, ST=Elytron, CN=Elytron CA", ((X509Certificate) chain[1]).getSubjectDN().getName());
}
 
Example 15
Source File: SecurityUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static void addDecryptionSettings(KeyStore ks, RecipientId recId, DecryptableMailInput input) throws Exception {
    char[] smimePw = input.getDecryptionKeystorePassword().toCharArray();

    java.security.Security.addProvider(new BouncyCastleProvider());

    try (InputStream decryptionStream = new URL(input.getDecryptionKeystore()).openStream()) {
        ks.load(decryptionStream, smimePw);
    }

    if (StringUtils.EMPTY.equals(input.getDecryptionKeyAlias())) {
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();

            if (ks.isKeyEntry(alias)) {
                input.setDecryptionKeyAlias(alias);
            }
        }

        if (StringUtils.EMPTY.equals(input.getDecryptionKeyAlias())) {
            throw new Exception(ExceptionMsgs.PRIVATE_KEY_ERROR_MESSAGE);
        }
    }

    // find the certificate for the private key and generate a
    // suitable recipient identifier.
    X509Certificate cert = (X509Certificate) ks.getCertificate(input.getDecryptionKeyAlias());
    if (null == cert) {
        throw new Exception("Can't find a key pair with alias \"" + input.getDecryptionKeyAlias() +
                "\" in the given keystore");
    }
    if (input.isVerifyCertificate()) {
        cert.checkValidity();
    }

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
}
 
Example 16
Source File: PKCS12SameKeyId.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 17
Source File: SSLEngineFactory.java    From NetBare with MIT License 4 votes vote down vote up
private void initializeSSLContext() throws GeneralSecurityException, IOException {
    KeyStore ks = loadKeyStore();
    mCaCert = ks.getCertificate(mJKS.alias());
    mCaPrivKey = (PrivateKey) ks.getKey(mJKS.alias(), mJKS.password());
}
 
Example 18
Source File: BigCRL.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int n = 500000;
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "."
            + X509CertInfo.DN_NAME);

    Date date = new Date();
    PrivateKey privateKey = (PrivateKey)
            keyStore.getKey(alias, pass.toCharArray());
    String sigAlgName = signerCertImpl.getSigAlgOID();

    X509CRLEntry[] badCerts = new X509CRLEntry[n];
    CRLExtensions ext = new CRLExtensions();
    ext.set("Reason", new CRLReasonCodeExtension(1));
    for (int i = 0; i < n; i++) {
        badCerts[i] = new X509CRLEntryImpl(
                BigInteger.valueOf(i), date, ext);
    }
    X509CRLImpl crl = new X509CRLImpl(owner, date, date, badCerts);
    crl.sign(privateKey, sigAlgName);
    byte[] data = crl.getEncodedInternal();

    // Make sure the CRL is big enough
    if ((data[1]&0xff) != 0x84) {
        throw new Exception("The file should be big enough?");
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cf.generateCRL(new ByteArrayInputStream(data));
}
 
Example 19
Source File: BigCRL.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int n = 500000;
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "."
            + X509CertInfo.DN_NAME);

    Date date = new Date();
    PrivateKey privateKey = (PrivateKey)
            keyStore.getKey(alias, pass.toCharArray());
    String sigAlgName = signerCertImpl.getSigAlgOID();

    X509CRLEntry[] badCerts = new X509CRLEntry[n];
    CRLExtensions ext = new CRLExtensions();
    ext.set("Reason", new CRLReasonCodeExtension(1));
    for (int i = 0; i < n; i++) {
        badCerts[i] = new X509CRLEntryImpl(
                BigInteger.valueOf(i), date, ext);
    }
    X509CRLImpl crl = new X509CRLImpl(owner, date, date, badCerts);
    crl.sign(privateKey, sigAlgName);
    byte[] data = crl.getEncodedInternal();

    // Make sure the CRL is big enough
    if ((data[1]&0xff) != 0x84) {
        throw new Exception("The file should be big enough?");
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cf.generateCRL(new ByteArrayInputStream(data));
}
 
Example 20
Source File: KeyStoreUtil.java    From MaxKey with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * 根据密钥库获得证�?
 * </p>
 * 
 * @param keyStorePath 密钥库存储路�?
 * @param alias        密钥库别�?
 * @param password     密钥库密�?
 * @return
 * @throws Exception
 */
public static Certificate getCertificate(KeyStore keyStore, String alias, String password) throws Exception {
    Certificate certificate = keyStore.getCertificate(alias);
    return certificate;
}