Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

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

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterHeaderWithNoContent() throws Exception {
    //empty content and specific url
    String content = "";
    String requestURL = "http://localhost:8080";
    ServletInputStream emptyContent = new DelegatingServletInputStream(
            new ByteArrayInputStream(content.getBytes()));

    //prepare client
    KeyStore keyStore = getKeyStoreClient();
    Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray());
    JWSJerseyFilter jwsJerseyFilter = new JWSJerseyFilter();

    //environment
    ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class);
    when(context.getConfiguration()).thenReturn(config);
    when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT);
    when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key);
    when(context.getUri()).thenReturn(new URI(requestURL));
    when(context.getHeaders()).thenReturn(headers);
    when(context.getEntity()).thenReturn(null);

    //test client
    jwsJerseyFilter.filter(context);/* ww  w  .ja va 2 s . co m*/
    //validation client
    verify(headers, times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture());
    String headerKey = argumentHeader.getValue();
    String headerValue = argumentHeaderValue.getValue();
    Assert.assertTrue("Response from client should contain token",
            headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN));
    logger.info("Client Header Content: {}={}", headerKey, headerValue);

    //prepare server
    when(request.getHeader(headerKey)).thenReturn(headerValue);
    when(request.getInputStream()).thenReturn(emptyContent);
    when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL));
    //test server
    myJWSFilter.doFilter(request, response, chain);

    //validation
    verify(chain, times(1)).doFilter(any(ServletRequest.class), any(ServletResponse.class));
    verify(response, times(0)).sendError(anyInt());//check sendError is not set

}

From source file:test.integ.be.fedict.hsm.PKCS11Test.java

@Test
public void testEToken() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", ".conf");
    tmpConfigFile.deleteOnExit();/* w ww.  jav a2 s. c o m*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile));
    configWriter.println("name=test");
    configWriter.println("library=/usr/lib/libeTPkcs11.so");
    configWriter.println("slotListIndex=0");
    configWriter.close();
    SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    Security.removeProvider(sunPKCS11.getName());
    sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(sunPKCS11);

    KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11);
    keyStore.load(null, "HSMProxy1234".toCharArray());
    Enumeration<String> aliasesEnum = keyStore.aliases();
    String alias = aliasesEnum.nextElement();

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, "HSMProxy1234".toCharArray());

    final int TEST_COUNT = 50;
    int count = TEST_COUNT;
    while (count > 0) {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        signature.update("to be signed".getBytes());
        signature.sign();
        count--;
    }
}

From source file:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java

public PreSignResult preSign(List<X509Certificate> authnCertificateChain,
        AuthenticationSignatureContext authenticationSignatureContext) {
    LOG.debug("preSign");
    LOG.debug("authn cert chain size: " + authnCertificateChain.size());

    KeyStore proxyKeyStore;
    final ProxyPrivateKey proxyPrivateKey;
    try {//from w  ww.j  a v  a 2  s  .c om
        proxyKeyStore = KeyStore.getInstance("ProxyBeID");
        proxyKeyStore.load(null);
        proxyPrivateKey = (ProxyPrivateKey) proxyKeyStore.getKey("Signature", null);
    } catch (Exception e) {
        throw new RuntimeException("error loading ProxyBeID keystore");
    }

    FutureTask<String> signTask = new FutureTask<String>(new Callable<String>() {
        public String call() throws Exception {
            final Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(proxyPrivateKey);

            final byte[] toBeSigned = "hello world".getBytes();
            signature.update(toBeSigned);
            final byte[] signatureValue = signature.sign();
            LOG.debug("received signature value");
            return "signature result";
        }

    });
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(signTask);

    authenticationSignatureContext.store("key", proxyPrivateKey);
    authenticationSignatureContext.store("signTask", signTask);

    byte[] digestValue;
    try {
        digestValue = proxyPrivateKey.getDigestInfo().getDigestValue();
    } catch (InterruptedException e) {
        throw new RuntimeException("signature error: " + e.getMessage(), e);
    }
    DigestInfo digestInfo = new DigestInfo(digestValue, "SHA-256", "WS-Security message");
    PreSignResult preSignResult = new PreSignResult(digestInfo, true);
    return preSignResult;
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testGetAliases() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);//from  w w w .  j  a  v a  2s .  c  o m
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    HSMProxyClient client = new HSMProxyClient("http://localhost:8080/hsm-proxy-ws/dss", authnPrivateKey,
            authnCert);

    Set<String> aliases = client.getAliases();
    assertNotNull(aliases);
    LOG.debug("aliases: " + aliases);
    assertFalse(aliases.isEmpty());
}

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@Test
public void handleRenewCertificateInstruction() throws Exception {
    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, "localhost", 80, false, TEST_PW_VALUE);
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();
    replayAll();//from w  w w.  java  2s .c o  m
    keystoreService.saveCACertificate(CA_CERT);
    keystoreService.generateNodeSelfSignedCertificate(TEST_DN);
    String csr = keystoreService.generateNodePKCS10CertificateRequestString();

    X509Certificate originalCert;

    PemReader pemReader = new PemReader(new StringReader(csr));
    try {
        PemObject pem = pemReader.readPemObject();
        PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent());
        originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate());
        String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert });
        keystoreService.saveNodeSignedCertificate(signedPem);

        log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem);

        assertThat("Generated CSR", csr, notNullValue());
    } finally {
        pemReader.close();
    }

    // now let's renew!
    KeyStore keyStore = loadKeyStore();
    PrivateKey nodeKey = (PrivateKey) keyStore.getKey("node", TEST_PW_VALUE.toCharArray());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA");
    ContentSigner signer = signerBuilder.build(nodeKey);
    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(
            JcaX500NameUtil.getSubject(originalCert),
            SubjectPublicKeyInfo.getInstance(originalCert.getPublicKey().getEncoded()));
    X509Certificate renewedCert = PKITestUtils.sign(builder.build(signer), CA_CERT, CA_KEY_PAIR.getPrivate());
    String renewedSignedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { renewedCert });

    BasicInstruction instr = new BasicInstruction(DefaultSetupService.INSTRUCTION_TOPIC_RENEW_CERTIFICATE,
            new Date(), "123", "456", new BasicInstructionStatus(456L, InstructionState.Received, new Date()));
    for (int i = 0; i < renewedSignedPem.length(); i += 256) {
        int end = i + (i + 256 < renewedSignedPem.length() ? 256 : renewedSignedPem.length() - i);
        instr.addParameter(DefaultSetupService.INSTRUCTION_PARAM_CERTIFICATE,
                renewedSignedPem.substring(i, end));
    }

    InstructionState state = service.processInstruction(instr);
    assertThat("Instruction state", state, equalTo(InstructionState.Completed));

    X509Certificate nodeCert = keystoreService.getNodeCertificate();
    assertThat("Node cert is now renewed cert", nodeCert, equalTo(renewedCert));
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testGetCertificateChain() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);/*from   w w  w  . j ava2  s. c o m*/
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    HSMProxyClient client = new HSMProxyClient("http://localhost:8080/hsm-proxy-ws/dss", authnPrivateKey,
            authnCert);

    Set<String> aliases = client.getAliases();
    assertNotNull(aliases);
    LOG.debug("aliases: " + aliases);
    String alias = aliases.iterator().next();

    List<X509Certificate> certificateChain = client.getCertificateChain(alias);
    assertNotNull(certificateChain);
    for (X509Certificate certificate : certificateChain) {
        LOG.debug("certificate: " + certificate);
    }
    assertFalse(certificateChain.isEmpty());
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterHeaderWithContent() throws Exception {
    //some content and specific url
    final String content = "{\n" + "\t\"id\": \"0001\",\n" + "\t\"type\": \"donut\",\n"
            + "\t\"name\": \"Cake\",\n" + "\t\"image\":\n" + "\t\t{\n" + "\t\t\t\"url\": \"images/0001.jpg\",\n"
            + "\t\t\t\"width\": 200,\n" + "\t\t\t\"height\": 200\n" + "\t\t},\n" + "\t\"thumbnail\":\n"
            + "\t\t{\n" + "\t\t\t\"url\": \"images/thumbnails/0001.jpg\",\n" + "\t\t\t\"width\": 32,\n"
            + "\t\t\t\"height\": 32\n" + "\t\t}\n" + "}";
    String requestURL = "http://localhost:8080";

    //prepare client
    ServletInputStream someContent = new DelegatingServletInputStream(
            new ByteArrayInputStream(content.getBytes()));
    KeyStore keyStore = getKeyStoreClient();
    Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray());
    JWSJerseyFilter jwsJerseyFilter = new JWSJerseyFilter();

    //environment
    ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class);
    when(context.getConfiguration()).thenReturn(config);
    when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT);
    when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key);
    when(context.getUri()).thenReturn(new URI(requestURL));
    when(context.getHeaders()).thenReturn(headers);
    when(context.getEntity()).thenReturn(content);
    doAnswer(new Answer<Void>() {
        @Override/*from  ww  w.  j  a  v a  2 s . co m*/
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] arguments = invocation.getArguments();

            ((OutputStream) arguments[6]).write(content.getBytes());
            ((OutputStream) arguments[6]).flush();
            return null;
        }
    }).when(messageBodyWriter).writeTo(any(Object.class), any(Class.class), any(Type.class),
            any(Annotation[].class), any(MediaType.class), any(MultivaluedMap.class), any(OutputStream.class));

    /* TODO: Next sentence is not working because of jax.ws.rs version change, it needs to be reviewed 
    when(messageBodyWorkers.getMessageBodyWriter(any(Class.class), any(Type.class), any(Annotation[].class), any(MediaType.class))).thenReturn(messageBodyWriter);
    */
    jwsJerseyFilter.setWorkers(messageBodyWorkers);

    Type entity = content.getClass();
    when(context.getEntityClass()).thenReturn((Class) entity);

    //test client
    jwsJerseyFilter.filter(context);
    //validation client
    verify(headers, times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture());
    String headerKey = argumentHeader.getValue();
    String headerValue = argumentHeaderValue.getValue();
    Assert.assertTrue("Response from client should contain token",
            headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN));
    logger.info("Client Header Content: {}={}", headerKey, headerValue);

    //prepare server
    when(request.getHeader(headerKey)).thenReturn(headerValue);
    when(request.getInputStream()).thenReturn(someContent);
    when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL));
    //test server
    myJWSFilter.doFilter(request, response, chain);

    //validation
    verify(chain, times(1)).doFilter(any(ServletRequest.class), any(ServletResponse.class));
    verify(response, times(0)).sendError(anyInt());//check sendError is not set

}

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

@Test
public void testServiceBeID() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from   w ww  .ja v a  2 s .com
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication");

    CrabReadService crabReadService = new CrabReadService();

    ICrabRead iCrabRead = crabReadService.getWS2007FederationHttpBindingICrabRead(new AddressingFeature());

    AGIVSecurity agivSecurity = new AGIVSecurity(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/CertificateMessage",
            "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13",
            AGIVSecurity.BETA_REALM, certificate, privateKey);

    BindingProvider bindingProvider = (BindingProvider) iCrabRead;
    agivSecurity.enable(bindingProvider, "https://crab.beta.agiv.be/read/crabreadservice.svc/wsfed", false,
            "urn:agiv.be/crab/beta");

    ArrayOfstring gemeentes = iCrabRead.listGemeente();
    List<String> gemeenteList = gemeentes.getString();
    for (String gemeente : gemeenteList) {
        LOG.debug("gemeente: " + gemeente);
    }
    assertTrue(gemeenteList.contains("Vilvoorde"));

    agivSecurity.refreshSecurityTokens();
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);//  w  w  w  . ja  v a2s  .c  om
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:net.sf.keystore_explorer.gui.actions.ExportKeyPairPrivateKeyAction.java

/**
 * Do action.// www  .j  a  va2s .  c o  m
 */
@Override
protected void doAction() {
    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        DExportPrivateKeyType dExportPrivateKeyType = new DExportPrivateKeyType(frame);
        dExportPrivateKeyType.setLocationRelativeTo(frame);
        dExportPrivateKeyType.setVisible(true);

        if (!dExportPrivateKeyType.exportTypeSelected()) {
            return;
        }

        if (dExportPrivateKeyType.exportPkcs8()) {
            exportAsPkcs8(privateKey, alias);
        } else if (dExportPrivateKeyType.exportPvk()) {
            exportAsPvk(privateKey, alias);
        } else {
            exportAsOpenSsl(privateKey, alias);
        }
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    }
}