Example usage for javax.security.cert X509Certificate getInstance

List of usage examples for javax.security.cert X509Certificate getInstance

Introduction

In this page you can find the example usage for javax.security.cert X509Certificate getInstance.

Prototype

public static final X509Certificate getInstance(byte[] certData) throws CertificateException 

Source Link

Document

Instantiates an X509Certificate object, and initializes it with the specified byte array.

Usage

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

public ValidacionesCertificado(InputStream archivoClavePublica, InputStream archivoClavePrivada,
        String password) {/* w  w  w  .j av  a  2  s.  co m*/

    try {
        this.clavePrivada = IOUtils.toByteArray(archivoClavePrivada);
        this.clavePublica = IOUtils.toByteArray(archivoClavePublica);
        //this.clavePublica2=IOUtils.toString(archivoClavePublica);
        this.password = password;
        this.certificado = X509Certificate.getInstance(this.clavePublica);
        cerInputStream = archivoClavePublica;
        keyInputStream = archivoClavePrivada;
        //this.cadenaOriginal= cadenaOrigin;
        /* X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
         boolean statusFecha;
         int statusFIEL=-1;
         boolean statusCorresp;
         boolean statusLCO;
         statusFecha=validaFecha(cert);
         System.out.println("\nel status fecha es: \n" + statusFecha);
         //statusFIEL=validaFIEL(cert);
         //System.out.println("el status FIEL es: " + statusFIEL);
         statusCorresp=validaCorrespondencias();
         System.out.println("\nel status de que el .key y el .cer correspondan es: \n" + statusCorresp);
         statusLCO=validaLCO();
         System.out.println("\nel status LCO es: \n" + statusLCO); */
    } catch (Exception ea) {
        ea.printStackTrace();
    }
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

public ValidacionesCertificado(InputStream archivoCertificado) {

    try {//from w ww.  j  a  va 2 s . com
        this.clavePublica = IOUtils.toByteArray(archivoCertificado);

        try {
            certificado = X509Certificate.getInstance(this.clavePublica);
        } catch (CertificateException ex) {
            Logger.getLogger(ValidacionesCertificado.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(ValidacionesCertificado.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida el password y que la llave privada corresponda a la
 * llave publica//from  w  w  w .java  2s . c  om
 *
 * @return true si el password y llave privada corresponden, en otro caso
 * false
 */
public boolean validaCorrespondencias() {

    try {

        PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray());
        //valida el pass
        PrivateKey pk = pkcs8.getPrivateKey();
        //valida que la llave privada corresponda  a la llave publica
        X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
        Signature firma = Signature.getInstance("SHA1withRSA");
        firma.initSign(pk);
        byte[] firmado = firma.sign();
        firma.initVerify(cert.getPublicKey());
        if (firma.verify(firmado)) {
            return this.correcto;
        } else {
            return this.error;
        }
    } catch (GeneralSecurityException e) {

        return this.error;
    } catch (CertificateException e) {

        return this.error;
    }
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest.java

@Test(description = "Handle request with device type URI with Mutual Auth Header", dependsOnMethods = "testHandleSuccessRequestProxyMutualAuthHeader")
public void testHandleSuccessRequestMutualAuthHeader() throws Exception {
    HashMap<String, String> transportHeaders = new HashMap<>();
    transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
    setMockClient();/*  ww w.  jav a2  s. co  m*/
    this.mockClient.setResponse(getAccessTokenReponse());
    this.mockClient.setResponse(getValidationResponse());
    MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
            transportHeaders, "https://test.com/testservice/api/testdevice");
    org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();
    String certStr = getContent(TestUtils.getAbsolutePathOfConfig("ra_cert.pem"));
    X509Certificate cert = X509Certificate
            .getInstance(new ByteArrayInputStream(certStr.getBytes(StandardCharsets.UTF_8.name())));
    axisMC.setProperty(AuthConstants.CLIENT_CERTIFICATE, new X509Certificate[] { cert });
    boolean response = this.handler.handleRequest(messageContext);
    Assert.assertTrue(response);
    this.mockClient.reset();
}

From source file:org.panlab.tgw.restclient.PtmInfoParser.java

private static void getPTMCertificate(String alias, URL url) {
    if (App.ptm_indexes.containsKey(alias))
        return;//from  w  ww. j a  v a  2 s . c  om
    System.out.println("Trying " + alias);

    try {

        Socket socket = new Socket(url.getHost(), url.getPort());

        OutputStream os = socket.getOutputStream();
        os.write(getClientHello());
        os.flush();
        os.flush();

        InputStream is = socket.getInputStream();

        byte[] buffer = new byte[2000];
        int length = 0;
        int tries = 0;
        while (true) {
            length += is.read(buffer, length, buffer.length - length);
            if (length > 0 && tries == 0) {
                tries++;
                if (buffer[0] == 0x16) {
                    log.info("TLSv1 Handshake");
                    log.info("Version: " + getText(buffer, 1, 2));
                    log.info("Length: " + getInt(buffer, 3, 2));
                    byte[] tmp = new byte[getInt(buffer, 3, 2) + 5];
                    System.arraycopy(buffer, 0, tmp, 0, length);
                    buffer = tmp;
                }
            }
            //log.info("Length: "+length);
            if (buffer.length == length) {
                break;
            }
        }
        //log.info("Length: "+length);
        int index = 0;
        if ((index = locateServerCertificate(buffer)) > 0) {
            log.info("Certificates Section Located at: " + index);
            length = getInt(buffer, index + 1, 3);
            log.info("Certificates length: " + length);
            length = getInt(buffer, index + 7, 3);
            log.info("First Certificate length: " + length);
            //log.info(getText(buffer, index+10, length));

            byte[] cert = new byte[length];
            System.arraycopy(buffer, index + 10, cert, 0, length);

            X509Certificate x509 = X509Certificate.getInstance(cert);
            log.info(x509.getSubjectDN().toString().replace(", ", ","));
            processCertificate(alias, x509, url);

        }
    } catch (Exception error) {
        log.error(error.getMessage());
    }

}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactory.java

/**
 * Create {@link CertificateDefinition}. This definition is used to create and check a {@link X509Certificate}.
 *
 * @param configuration properties to define {@link CertificateDefinition}.
 * @param keyName       the name of the key.
 * @return the {@link CertificateDefinition}.
 *///www . ja va2 s  .  co  m
CertificateDefinition createCertificateDefinition(Configuration configuration, String keyName) {
    Configuration keyConfiguration = configurationForKey(configuration, keyName);
    CertificateDefinition definition = new CertificateDefinition();
    String resource = keyConfiguration.getString(CERT_RESOURCE);
    String certLocation;

    if (resource != null) {
        URL urlResource = SeedReflectionUtils.findMostCompleteClassLoader(null).getResource(resource);
        if (urlResource == null) {
            throw new RuntimeException("Certificate [" + resource + "] not found !");
        }
        certLocation = urlResource.getFile();
    } else {
        certLocation = keyConfiguration.getString(CERT_FILE);
    }

    // Certificate information
    if (certLocation != null) {
        FileInputStream in;
        try {
            in = new FileInputStream(certLocation);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Certificate [" + certLocation + "] not found !");
        }
        try {
            definition.setCertificate(X509Certificate.getInstance(in));
        } catch (javax.security.cert.CertificateException e) {
            throw new RuntimeException("Certificate [" + certLocation + "] parsing error !");
        }
        try {
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("Certificate [" + certLocation + "] not closed !");
        }
    }

    // Private key informations
    definition.setAlias(keyConfiguration.getString(KEYSTORE_ALIAS));
    definition.setPassword(keyConfiguration.getString(KEY_PASSWORD));

    return definition;
}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for/* w  w w .j  a  va2 s  . com*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createCertificateDefinition(Configuration, String)}
 *
 * @throws Exception if an error occurred
 */
@Test
public void testCreateCertificateDefinitionWithFileCertificate(@Mocked final Configuration configuration,
        @Mocked final FileInputStream file, @Mocked final X509Certificate x509Certificate) throws Exception {

    final String alias = "alias";
    final String password = "password";

    new Expectations() {
        final String filename = "file.crt";

        {
            configuration.getString("cert.file");
            result = filename;
            configuration.getString("keystore.alias");
            result = alias;
            configuration.getString("key.password");
            result = password;

            new FileInputStream(filename);
            result = file;

            X509Certificate.getInstance(file);
            result = x509Certificate;

        }
    };
    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    CertificateDefinition definition = factory.createCertificateDefinition(configuration, "test");

    Assertions.assertThat(definition.getAlias()).isEqualTo(alias);
    Assertions.assertThat(definition.getPassword()).isEqualTo(password);
    Assertions.assertThat(definition.getCertificate()).isEqualTo(x509Certificate);
}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for//from  w  w w  .  j av a 2 s.co m
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createCertificateDefinition(Configuration, String)}
 *
 * @throws Exception if an error occurred
 */
@Test
public void testCreateCertificateDefinitionWithResourceCertificate(@Mocked final Configuration configuration,
        @Mocked final URL url, @Mocked final FileInputStream file,
        @Mocked final X509Certificate x509Certificate) throws Exception {

    final String alias = "alias";
    final String password = "password";
    final String filename = "client.ceree";

    new MockUp<ClassLoader>() {
        @Mock
        public URL getResource(Invocation inv, String name) {
            if (name == filename) {
                return url;
            }
            return inv.proceed(name);
        }
    };
    new Expectations() {
        {
            configuration.getString("cert.resource");
            result = filename;
            configuration.getString("keystore.alias");
            result = alias;
            configuration.getString("key.password");
            result = password;

            url.getFile();
            result = filename;

            new FileInputStream(filename);
            result = file;

            X509Certificate.getInstance(file);
            result = x509Certificate;

        }
    };
    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    CertificateDefinition definition = factory.createCertificateDefinition(configuration, "test");

    Assertions.assertThat(definition.getAlias()).isEqualTo(alias);
    Assertions.assertThat(definition.getPassword()).isEqualTo(password);
    Assertions.assertThat(definition.getCertificate()).isEqualTo(x509Certificate);
}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for/*from  w  ww. j a  va2  s.  c  o  m*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createCertificateDefinition(Configuration, String)}
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateCertificateDefinitionWithCertificateException(@Mocked final Configuration configuration,
        @Mocked final FileInputStream file,
        @SuppressWarnings("unused") @Mocked final X509Certificate x509Certificate) throws Exception {

    new Expectations() {
        final String filename = "file.crt";

        {
            configuration.getString("cert.file");
            result = filename;

            new FileInputStream(filename);
            result = file;

            X509Certificate.getInstance(file);
            result = new javax.security.cert.CertificateException("dummy exception");

        }
    };
    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createCertificateDefinition(configuration, "test");

}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for//  w  w  w  .java2  s .c o  m
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createCertificateDefinition(Configuration, String)}
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateCertificateDefinitionWithIOException(@Mocked final Configuration configuration,
        @Mocked final FileInputStream file, @Mocked final X509Certificate x509Certificate) throws Exception {

    new Expectations() {
        final String filename = "file.crt";

        {
            configuration.getString("cert.file");
            result = filename;

            new FileInputStream(filename);
            result = file;

            X509Certificate.getInstance(file);
            result = x509Certificate;

            file.close();
            result = new IOException("dummy exception");
        }
    };
    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createCertificateDefinition(configuration, "test");

}