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:com.indivica.olis.Driver.java

public static String signData(String data) {
    X509Certificate cert = null;// w  w w.  j a  v a 2  s .c  o  m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

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

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

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

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

        // 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:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java

@Test
public void testRegisterRevokeSessionKey() throws Exception {
    // setup//www .  j av a 2s  . c o  m
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    // operate
    xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertFalse(sessionKey.isValid());
}

From source file:test.integ.be.agiv.security.Config.java

public Config() throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, NoSuchProviderException {
    Properties properties = new Properties();
    properties.load(Config.class.getResourceAsStream("/agiv.properties"));
    this.username = properties.getProperty("username");
    this.password = properties.getProperty("password");
    this.pkcs12Path = properties.getProperty("pkcs12.path");
    this.pkcs12Password = properties.getProperty("pkcs12.password");
    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
        LOG.debug("security provider: " + provider.getName());
    }//from  ww  w.j  av  a  2  s.  co  m
    if (null != this.pkcs12Path) {
        InputStream pkcs12InputStream = new FileInputStream(pkcs12Path);
        KeyStore keyStore = KeyStore.getInstance("PKCS12", "SunJSSE");
        keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = aliases.nextElement();
        this.certificate = (X509Certificate) keyStore.getCertificate(alias);
        this.privateKey = (PrivateKey) keyStore.getKey(alias, this.pkcs12Password.toCharArray());
    } else {
        this.certificate = null;
        this.privateKey = null;
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java

@Test
public void testRegisterViaXKMS2RevokeViaXKMS1() throws Exception {
    // setup/*from   ww  w .j a  v  a2s . c om*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    String xkmsLocation = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms";
    XKMSClient xkmsClient = new XKMSClient(xkmsLocation);

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    // operate
    xkmsClient.revokeSessionKey(sessionKey);

    // verify
    assertFalse(sessionKey.isValid());
}

From source file:test.integ.be.e_contract.mycarenet.cxf.SyncClientTest.java

@Test
public void testEcho() throws Exception {
    // setup/*from  ww w . j  av a2  s .c  o  m*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync",
                sessionKey, packageLicenseKey);

        ObjectFactory objectFactory = new ObjectFactory();
        XmlDocumentWrapperType request = objectFactory.createXmlDocumentWrapperType();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("test");
        request.setAny(element);
        request.setLang("en");
        // operate
        XmlDocumentWrapperType result;
        try {
            result = syncClient.echo(request);
        } finally {
            LOG.debug("payload: " + syncClient.getPayload());
        }

        // verify
        assertEquals(result.getAny().getNodeName(), "test");
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:org.lockss.util.TestKeyStoreUtil.java

public void testDefaults() throws Exception {
    Properties p = initProps();/*from  w ww. j a  va  2  s .  co m*/
    KeyStore ks = KeyStoreUtil.createKeyStore(p);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
    assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
    assertNotNull(ks.getCertificate("mycert"));
    assertNull(ks.getCertificate("foocert"));
    assertEquals("JCEKS", ks.getType());
}

From source file:com.netscape.cmstools.pkcs11.PKCS11CertFindCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();/*from   ww  w .  j a  va2  s .c om*/
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

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

    boolean first = true;

    while (aliases.hasMoreElements()) {

        String alias = aliases.nextElement();

        Certificate cert = ks.getCertificate(alias);
        if (cert == null) {
            continue;
        }

        if (first) {
            first = false;
        } else {
            System.out.println();
        }

        PKCS11CertCLI.printCertInfo(alias, cert);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java

@Test
public void testEcho() throws Exception {
    // setup//from   w  w w  .j  a  va  2s.co  m
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        AsyncClient asyncClient = new AsyncClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/async",
                sessionKey, packageLicenseKey);

        BindingProvider bindingProvider = asyncClient.getBindingProvider();
        Client client = ClientProxy.getClient(bindingProvider);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(36000); // ms
        httpClientPolicy.setReceiveTimeout(36000); // ms
        http.setClient(httpClientPolicy);

        String message = "hello world";

        // operate
        String result;
        try {
            result = asyncClient.echo(message);
        } finally {
            LOG.debug("payload: " + asyncClient.getPayload());
        }

        // verify
        assertEquals(result, message);
    } finally {
        // operate
        XKMSClient xkmsClient = new XKMSClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms");
        xkmsClient.revokeSessionKey(sessionKey);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:org.lockss.util.TestKeyStoreUtil.java

public void testStore() throws Exception {
    File dir = getTempDir();//from  w ww . ja va  2s  .  com
    File file = new File(dir, "test.ks");
    Properties p = initProps();
    p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString());
    assertFalse(file.exists());
    KeyStore ks = KeyStoreUtil.createKeyStore(p);
    assertTrue(file.exists());

    KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases()));
    assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
    assertNotNull(ks2.getCertificate("mycert"));
    assertNull(ks2.getCertificate("foocert"));
    assertEquals("JCEKS", ks2.getType());
}

From source file:test.integ.be.agiv.security.PKCS12Test.java

@Test
public void testLoadPKCS12() throws Exception {
    Config config = new Config();
    String pkcs12Path = config.getPKCS12Path();
    String pkcs12Password = config.getPKCS12Password();

    InputStream pkcs12InputStream = new FileInputStream(pkcs12Path);
    assertNotNull(pkcs12InputStream);

    LOG.debug("loading PKCS12 keystore");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate: " + certificate);
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
        LOG.debug("private key algo: " + privateKey.getAlgorithm());
        assertEquals("RSA", privateKey.getAlgorithm());
        LOG.debug("certificate fingerprint: " + DigestUtils.shaHex(certificate.getEncoded()));
    }//from  w w w  . j ava2 s . com
}