Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:nl.clockwork.mule.ebms.cxf.XMLSecSignatureInInterceptor.java

private boolean verify(KeyStore keyStore, Document document, List<EbMSDataSource> dataSources)
        throws XMLSignatureException, XMLSecurityException, CertificateExpiredException,
        CertificateNotYetValidException, KeyStoreException {
    NodeList nodeList = document.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS,
            org.apache.xml.security.utils.Constants._TAG_SIGNATURE);
    if (nodeList.getLength() > 0) {
        XMLSignature signature = new XMLSignature((Element) nodeList.item(0),
                org.apache.xml.security.utils.Constants.SignatureSpecNS);

        EbMSDataSourceResolver resolver = new EbMSDataSourceResolver(dataSources);
        signature.addResourceResolver(resolver);

        X509Certificate certificate = signature.getKeyInfo().getX509Certificate();
        if (certificate != null) {
            certificate.checkValidity();
            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                try {
                    Certificate c = keyStore.getCertificate(aliases.nextElement());
                    certificate.verify(c.getPublicKey());
                    return signature.checkSignatureValue(certificate);
                } catch (KeyStoreException e) {
                    throw e;
                } catch (Exception e) {
                }//from   www. j  av  a  2  s. co  m
            }
        } else {
            PublicKey publicKey = signature.getKeyInfo().getPublicKey();
            if (publicKey != null)
                return signature.checkSignatureValue(publicKey);
        }
        return false;
    }
    return true;
}

From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java

private static Certificate getCertificate(String tenantDomain, int tenantId) throws Exception {
    Certificate publicCert = null;

    if (!(publicCerts.containsKey(tenantId))) {

        try {//w  w  w  .j a  va 2s  .  c  om
            IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain);
        } catch (IdentityException e) {
            throw new IdentityOAuth2Exception(
                    "Error occurred while loading registry for tenant " + tenantDomain, e);
        }

        // get tenant's key store manager
        KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

        KeyStore keyStore = null;
        if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            // derive key store name
            String ksName = tenantDomain.trim().replace(".", "-");
            String jksName = ksName + ".jks";
            keyStore = tenantKSM.getKeyStore(jksName);
            publicCert = keyStore.getCertificate(tenantDomain);
        } else {
            publicCert = tenantKSM.getDefaultPrimaryCertificate();
        }
        if (publicCert != null) {
            publicCerts.put(tenantId, publicCert);
        }
    } else {
        publicCert = publicCerts.get(tenantId);
    }
    return publicCert;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private X509Certificate FindCertByDN(X500Principal name) throws Exception {
    KeyStore ks = GetTrustStore();
    if (ks == null) {
        return null;
    }//from   w w  w.  j  a v a 2 s.  c  o m
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String nextElement = aliases.nextElement();
        Certificate certificate = ks.getCertificate(nextElement);
        X509Certificate x = (X509Certificate) certificate;
        if (x.getSubjectX500Principal().equals(name)) {
            return x;
        }
    }
    return null;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private X509Certificate FindCertByIssuer(String X509IssuerName, String X509SerialNumber) throws Exception {
    KeyStore ks = GetTrustStore();
    if (ks == null) {
        return null;
    }//w  w  w  .  j av  a2  s.  co  m
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String nextElement = aliases.nextElement();
        Certificate certificate = ks.getCertificate(nextElement);
        X509Certificate x = (X509Certificate) certificate;
        if (x.getIssuerDN().getName().equals(X509IssuerName)
                && x.getSerialNumber().toString().equalsIgnoreCase(X509SerialNumber)) {
            return x;
        }
    }
    return null;
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public String generateNodePKCS10CertificateRequestString() throws CertificateException {
    KeyStore keyStore = loadKeyStore();
    Key key;//ww  w. ja v a2  s .  c  o  m
    try {
        key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray());
    } catch (UnrecoverableKeyException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error opening node private key", e);
    }
    assert key instanceof PrivateKey;
    Certificate cert;
    try {
        cert = keyStore.getCertificate(nodeAlias);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node certificate", e);
    }
    assert cert instanceof X509Certificate;
    return certificateService.generatePKCS10CertificateRequestString((X509Certificate) cert, (PrivateKey) key);
}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java

@Override
public X509Certificate[] getCertificateChain(final String alias) {
    try {//  w w w  . j a va  2  s .c  o m
        final KeyStore store;
        try {
            store = this.getKeystore();
        } catch (IOException e) {
            return null;
        }
        final List<X509Certificate> result = new ArrayList<X509Certificate>();
        final Certificate[] chain = store.getCertificateChain(alias);
        if (null == chain) {
            log.warn(String.format("No certificate chain for alias %s", alias));
            // Return null if the alias can't be found
            return null;
        } else {
            for (Certificate cert : chain) {
                if (cert instanceof X509Certificate) {
                    result.add((X509Certificate) cert);
                }
            }
        }
        if (result.isEmpty()) {
            log.warn(String.format("No certificate chain for alias %s", alias));
            final Certificate cert = store.getCertificate(alias);
            if (null == cert) {
                // Return null if the alias can't be found
                return null;
            }
            if (cert instanceof X509Certificate) {
                final X509Certificate x509 = (X509Certificate) cert;
                result.add(x509);
            }
        }
        return result.toArray(new X509Certificate[result.size()]);
    } catch (KeyStoreException e) {
        log.error(String.format("Keystore not loaded %s", e.getMessage()));
    }
    return null;
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public String generateNodePKCS7CertificateString() throws CertificateException {
    KeyStore keyStore = loadKeyStore();
    Key key;//www .  j  a v a 2  s  .co  m
    try {
        key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray());
    } catch (UnrecoverableKeyException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error opening node private key", e);
    }
    assert key instanceof PrivateKey;
    Certificate cert;
    try {
        cert = keyStore.getCertificate(nodeAlias);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node certificate", e);
    }
    assert cert instanceof X509Certificate;
    return certificateService
            .generatePKCS7CertificateChainString(new X509Certificate[] { (X509Certificate) cert });
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

private ArrayList<Object> getCertificateInfo(final URL url, final String password, String keyStoreType,
        String prefix) {/* w  w w.j  a va  2s  .  co m*/
    ArrayList<Object> certificateList = new ArrayList<Object>();
    try {
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
        if (log.isInfoEnabled()) {
            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                ArrayList<Object> infoElem = new ArrayList<Object>();
                infoElem.add(prefix + " '" + alias + "':");
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    infoElem.add("Subject DN: " + cert.getSubjectDN());
                    infoElem.add("Signature Algorithm: " + cert.getSigAlgName());
                    infoElem.add("Valid from: " + cert.getNotBefore());
                    infoElem.add("Valid until: " + cert.getNotAfter());
                    infoElem.add("Issuer: " + cert.getIssuerDN());
                }
                certificateList.add(infoElem);
            }
        }
    } catch (Exception e) {
        certificateList.add("*** ERROR ***");
    }
    return certificateList;
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

@Override
protected void setupCloudClient() throws IOException {
    // Get settings from the configuration
    bucketName = getProperty(BUCKET_NAME_PROPERTY);
    bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY);
    String bucketRegion = getProperty(BUCKET_REGION_PROPERTY);
    if (isBlank(bucketRegion)) {
        bucketRegion = DEFAULT_BUCKET_REGION;
    }//from w  w w. j ava2s  .  com
    String awsID = getProperty(AWS_ID_PROPERTY);
    String awsSecret = getProperty(AWS_SECRET_PROPERTY);

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY);
    int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY);
    int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY);
    int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY);

    String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY);
    String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY);
    String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY);
    String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY);
    String endpoint = getProperty(ENDPOINT_PROPERTY);
    String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY);
    if (isNotBlank(sseprop)) {
        userServerSideEncryption = Boolean.parseBoolean(sseprop);
    }

    // Fallback on default env keys for ID and secret
    if (isBlank(awsID)) {
        awsID = System.getenv(AWS_ID_ENV);
    }
    if (isBlank(awsSecret)) {
        awsSecret = System.getenv(AWS_SECRET_ENV);
    }

    if (isBlank(bucketName)) {
        throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY);
    }

    if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) {
        log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.",
                BUCKET_PREFIX_PROPERTY, bucketNamePrefix));
        bucketNamePrefix += "/";
    }
    // set up credentials
    if (isBlank(awsID) || isBlank(awsSecret)) {
        awsCredentialsProvider = new InstanceProfileCredentialsProvider();
        try {
            awsCredentialsProvider.getCredentials();
        } catch (AmazonClientException e) {
            throw new RuntimeException("Missing AWS credentials and no instance role found");
        }
    } else {
        awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret);
    }

    // set up client configuration
    clientConfiguration = new ClientConfiguration();
    if (isNotBlank(proxyHost)) {
        clientConfiguration.setProxyHost(proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
    }
    if (isNotBlank(proxyLogin)) {
        clientConfiguration.setProxyUsername(proxyLogin);
    }
    if (proxyPassword != null) { // could be blank
        clientConfiguration.setProxyPassword(proxyPassword);
    }
    if (maxConnections > 0) {
        clientConfiguration.setMaxConnections(maxConnections);
    }
    if (maxErrorRetry >= 0) { // 0 is allowed
        clientConfiguration.setMaxErrorRetry(maxErrorRetry);
    }
    if (connectionTimeout >= 0) { // 0 is allowed
        clientConfiguration.setConnectionTimeout(connectionTimeout);
    }
    if (socketTimeout >= 0) { // 0 is allowed
        clientConfiguration.setSocketTimeout(socketTimeout);
    }

    // set up encryption
    encryptionMaterials = null;
    if (isNotBlank(keystoreFile)) {
        boolean confok = true;
        if (keystorePass == null) { // could be blank
            log.error("Keystore password missing");
            confok = false;
        }
        if (isBlank(privkeyAlias)) {
            log.error("Key alias missing");
            confok = false;
        }
        if (privkeyPass == null) { // could be blank
            log.error("Key password missing");
            confok = false;
        }
        if (!confok) {
            throw new RuntimeException("S3 Crypto configuration incomplete");
        }
        try {
            // Open keystore
            File ksFile = new File(keystoreFile);
            FileInputStream ksStream = new FileInputStream(ksFile);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(ksStream, keystorePass.toCharArray());
            ksStream.close();
            // Get keypair for alias
            if (!keystore.isKeyEntry(privkeyAlias)) {
                throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias");
            }
            PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray());
            Certificate cert = keystore.getCertificate(privkeyAlias);
            PublicKey pubKey = cert.getPublicKey();
            KeyPair keypair = new KeyPair(pubKey, privKey);
            // Get encryptionMaterials from keypair
            encryptionMaterials = new EncryptionMaterials(keypair);
            cryptoConfiguration = new CryptoConfiguration();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias,
                    e);
        }
    }
    isEncrypted = encryptionMaterials != null;

    // Try to create bucket if it doesn't exist
    if (!isEncrypted) {
        amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);
    } else {
        amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider,
                new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration,
                cryptoConfiguration);
    }
    if (isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }

    // Set region explicitely for regions that reguire Version 4 signature
    ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>();
    V4_ONLY_REGIONS.add("eu-central-1");
    V4_ONLY_REGIONS.add("ap-northeast-2");
    if (V4_ONLY_REGIONS.contains(bucketRegion)) {
        amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    }

    try {
        if (!amazonS3.doesBucketExist(bucketName)) {
            amazonS3.createBucket(bucketName, bucketRegion);
            amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private);
        }
    } catch (AmazonClientException e) {
        throw new IOException(e);
    }

    // compat for NXP-17895, using "downloadfroms3", to be removed
    // these two fields have already been initialized by the base class initialize()
    // using standard property "directdownload"
    String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT);
    if (dd != null) {
        directDownload = Boolean.parseBoolean(dd);
    }
    int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT);
    if (dde >= 0) {
        directDownloadExpire = dde;
    }

    transferManager = new TransferManager(amazonS3);
    abortOldUploads();
}

From source file:Manifest.java

/**
 * This method verifies the digital signature of the named manifest file, if
 * it has one, and if that verification succeeds, it verifies the message
 * digest of each file in filelist that is also named in the manifest. This
 * method can throw a bunch of exceptions
 *///  ww w .j  a va 2  s  .  co  m
public static void verify(String manifestfile, KeyStore keystore) throws NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, KeyStoreException, IOException {
    Properties manifest = new Properties();
    manifest.load(new FileInputStream(manifestfile));
    String digestAlgorithm = manifest.getProperty("__META.DIGESTALGORITHM");
    String signername = manifest.getProperty("__META.SIGNER");
    String signatureAlgorithm = manifest.getProperty("__META.SIGNATUREALGORITHM");
    String hexsignature = manifest.getProperty("__META.SIGNATURE");

    // Get a list of filenames in the manifest.
    List files = new ArrayList();
    Enumeration names = manifest.propertyNames();
    while (names.hasMoreElements()) {
        String s = (String) names.nextElement();
        if (!s.startsWith("__META"))
            files.add(s);
    }
    int numfiles = files.size();

    // If we've got a signature but no keystore, warn the user
    if (signername != null && keystore == null)
        System.out.println("Can't verify digital signature without " + "a keystore.");

    // If the manifest contained metadata about a digital signature, then
    // verify that signature first
    if (signername != null && keystore != null) {
        System.out.print("Verifying digital signature...");
        System.out.flush();

        // To verify the signature, we must process the files in exactly
        // the same order we did when we created the signature. We
        // guarantee this order by sorting the filenames.
        Collections.sort(files);

        // Create a Signature object to do signature verification with.
        // Initialize it with the signer's public key from the keystore
        Signature signature = Signature.getInstance(signatureAlgorithm);
        PublicKey publickey = keystore.getCertificate(signername).getPublicKey();
        signature.initVerify(publickey);

        // Now loop through these files in their known sorted order For
        // each one, send the bytes of the filename and of the digest to
        // the signature object for use in computing the signature. It is
        // important that this be done in exactly the same order when
        // verifying the signature as it was done when creating the
        // signature.
        for (int i = 0; i < numfiles; i++) {
            String filename = (String) files.get(i);
            signature.update(filename.getBytes());
            signature.update(hexDecode(manifest.getProperty(filename)));
        }

        // Now decode the signature read from the manifest file and pass
        // it to the verify() method of the signature object. If the
        // signature is not verified, print an error message and exit.
        if (!signature.verify(hexDecode(hexsignature))) {
            System.out.println("\nManifest has an invalid signature");
            System.exit(0);
        }

        // Tell the user we're done with this lengthy computation
        System.out.println("verified.");
    }

    // Tell the user we're starting the next phase of verification
    System.out.print("Verifying file message digests");
    System.out.flush();

    // Get a MessageDigest object to compute digests
    MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
    // Loop through all files
    for (int i = 0; i < numfiles; i++) {
        String filename = (String) files.get(i);
        // Look up the encoded digest from the manifest file
        String hexdigest = manifest.getProperty(filename);
        // Compute the digest for the file.
        byte[] digest;
        try {
            digest = getFileDigest(filename, md);
        } catch (IOException e) {
            System.out.println("\nSkipping " + filename + ": " + e);
            continue;
        }

        // Encode the computed digest and compare it to the encoded digest
        // from the manifest. If they are not equal, print an error
        // message.
        if (!hexdigest.equals(hexEncode(digest)))
            System.out.println("\nFile '" + filename + "' failed verification.");

        // Send one dot of output for each file we process. Since
        // computing message digests takes some time, this lets the user
        // know that the program is functioning and making progress
        System.out.print(".");
        System.out.flush();
    }
    // And tell the user we're done with verification.
    System.out.println("done.");
}