Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.tolven.security.cert.CertificateHelper.java

public static X509Certificate getX509Certificate(byte[] bytes) {
    //return (X509Certificate) getPEMObject(bytes);
    X509Certificate x509Certificate = null;
    ByteArrayInputStream bis = null;
    try {//from  w w  w . j ava 2  s .co  m
        bis = new ByteArrayInputStream(bytes);
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            x509Certificate = (X509Certificate) certificateFactory.generateCertificate(bis);
        } catch (CertificateException ex) {
            throw new RuntimeException("Could not generate an X509 certificate", ex);
        }
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception ex) {
                throw new RuntimeException(
                        "Could not close bytearrayinputstream after generating an X509 certificate", ex);
            }
        }
    }
    return x509Certificate;
}

From source file:org.tolven.gatekeeper.CertificateHelper.java

public static X509Certificate getX509Certificate(byte[] bytes) {
    //return (X509Certificate) getPEMObject(bytes);
    X509Certificate x509Certificate = null;
    ByteArrayInputStream bis = null;
    try {// w  w  w. ja  va  2s  .  c  o m
        bis = new ByteArrayInputStream(bytes);
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            x509Certificate = (X509Certificate) certificateFactory.generateCertificate(bis);
        } catch (CertificateException ex) {
            throw new RuntimeException("Could not generate an X509 certificate", ex);
        }
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Could not close bytearrayinputstream after generating an X509 certificate", ex);
            }
        }
    }
    return x509Certificate;
}

From source file:org.teknux.jettybootstrap.keystore.JettyKeystore.java

private static Certificate loadCertificate(InputStream certificateOutputStream) throws JettyKeystoreException {

    try {//from  w w  w  . j  a va2  s.c  o  m
        CertificateFactory certificateFactory;
        certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE_X509);
        Certificate certificate = certificateFactory.generateCertificate(certificateOutputStream);

        return certificate;
    } catch (CertificateException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_LOAD_CERTIFICATE,
                "Can not load certificate", e);
    }
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception//from w ww .j a v  a  2 s  . c  om
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath());

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception//from   w  w w.  j a  v a2 s  .  com
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:com.vmware.eucenablement.saml.impl.SAMLUtil.java

/**
 * transfer certificate content to X509Certificate object
 *
 * @param cert// w w w.j  a v  a 2s .  c o  m
 *            content of certificate
 * @return X509Certificate object
 */
public static X509Certificate transfer2X509Certificate(String cert) {

    // return null if no certificate content
    if (null == cert) {
        log.error("The input cert for transfer2X509Certificate is null!");
        return null;
    }
    /*
     * Test cert = "-----BEGIN CERTIFICATE-----\n" +
     * "MIID7DCCAtSgAwIBAgIFFHYYEzIwDQYJKoZIhvcNAQELBQAwgawxCzAJBgNVBAYT\n"
     * "qNHgsx8lHUoenasijd4sJPnj3YKz2Q9lHjSIOgMK41PSgVymOY2W7y2ANoNNKR0Q\n"
     * + "-----END CERTIFICATE-----";
     */
    if (!cert.contains(VidmSamlConstants.BEGIN_CERT)) {
        cert = convertCertToPemFormat(cert);
    }

    InputStream certinputstream = new ByteArrayInputStream(cert.getBytes());
    CertificateFactory cf = null;
    X509Certificate x509 = null;
    try {
        cf = CertificateFactory.getInstance("X.509");
        x509 = (X509Certificate) cf.generateCertificate(certinputstream);
    } catch (CertificateException e) {
        log.error("Caught CertificateException", e);
        return null;
    }

    return x509;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ?????,??//from  w  w w .j  a  v  a 2 s. c om
 * 
 * @param ctx
 *            
 * @param symmetryKey
 *            
 * @param pubKey
 *            
 * @return String(?base64?)
 */
public static String generateDigitalEnvelope(SecurityContext ctx, Key symmetryKey, byte[] pubKey) {
    String result = null;
    InputStream inputStream = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        inputStream = new ByteArrayInputStream(pubKey);
        java.security.cert.Certificate cert = cf.generateCertificate(inputStream);
        inputStream.close();
        PublicKey publicKey = cert.getPublicKey();
        Cipher cipher = Cipher.getInstance(ctx.getAsymmetryAlgorithm());

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        result = Base64.encodeBase64String(cipher.doFinal(symmetryKey.getEncoded()));
        return result;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException ex) {
        }
    }
}

From source file:com.indivica.olis.Driver.java

public static String signData2(String data) {
    X509Certificate cert = null;//from   w w w.j ava 2  s. co m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = OscarProperties.getInstance().getProperty("olis_ssl_keystore_password", "changeit");
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("JKS");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        //Enumeration e = keystore.aliases();
        String name = "olis";

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());

        FileInputStream is = new FileInputStream(
                OscarProperties.getInstance().getProperty("olis_returned_cert"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(is);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Get Certificate thumb print and Issuer Name from the ACS token.
 * @param acsToken the acs token//  w ww.j av  a2 s .  c om
 * @return returnData the Map containing Thumb print and issuer name of X509Certiificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    byte[] acsTokenByteArray = null;
    Map<String, String> returnData = new HashMap<String, String>();

    try {
        acsTokenByteArray = acsToken.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder;
    String issuerName = null;
    StringBuffer thumbprint = null;

    try {
        docBuilder = builderFactory.newDocumentBuilder();
        Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray));
        Element keyInfo = (Element) resultDoc.getDocumentElement()
                .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0);

        NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate");
        Element x509CertNode = (Element) x509CertNodeList.item(0);
        if (x509CertNode == null) {
            return null;
        }
        //generating Certificate to retrieve its detail.
        String x509CertificateData = x509CertNode.getTextContent();
        InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes()));
        CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory
                .generateCertificate(inStream);
        String issuerDN = x509Certificate.getIssuerDN().toString();
        String[] issuerDNData = issuerDN.split("=");
        issuerName = issuerDNData[1];

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = x509Certificate.getEncoded();
        md.update(der);
        thumbprint = new StringBuffer();
        thumbprint.append(Hex.encodeHex(md.digest()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnData.put("IssuerName", issuerName);
    returnData.put("Thumbprint", thumbprint.toString().toUpperCase());
    return returnData;
}

From source file:edu.vt.middleware.crypt.util.CryptReader.java

/**
 * Reads a PEM or DER-encoded certificate of the default type from an input
 * stream into a {@link Certificate} object.
 *
 * @param  certStream  Input stream with certificate data.
 * @param  type  Type of certificate to read, e.g. X.509.
 *
 * @return  Certificate created from data read from stream.
 *
 * @throws  CryptException  On certificate read or format errors.
 *///from w w w. jav a2  s.co m
public static Certificate readCertificate(final InputStream certStream, final String type)
        throws CryptException {
    final CertificateFactory cf = CryptProvider.getCertificateFactory(type);
    try {
        return cf.generateCertificate(certStream);
    } catch (CertificateException e) {
        throw new CryptException("Certificate read/format error.", e);
    }
}