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:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);/*from w  ww. j a v  a  2  s .co  m*/
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testBeIDSignature() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    final BeIDCard beIDCard = getBeIDCard();
    keyStoreParameter.setBeIDCard(beIDCard);
    keyStoreParameter.setLogoff(true);//w  w w . j a v a 2 s . co m
    keyStore.load(keyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    assertEquals(2, keyStore.size());

    assertTrue(keyStore.containsAlias("Signature"));
    assertTrue(keyStore.containsAlias("Authentication"));
    assertNotNull(keyStore.getCreationDate("Signature"));
    assertNotNull(keyStore.getCreationDate("Authentication"));

    assertTrue(keyStore.isKeyEntry("Signature"));
    final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature");
    assertNotNull(signCertificate);

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);

    assertNotNull(keyStore.getCertificateChain("Signature"));
    assertNotNull(keyStore.getCertificateChain("Authentication"));

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    assertNotNull(authnPrivateKey);

    assertTrue(keyStore.isKeyEntry("Signature"));
    final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    assertNotNull(signPrivateKey);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());

    Security.addProvider(new BouncyCastleProvider());

    verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:org.texai.x509.X509Utils.java

/** Creates the Texai root X.509 certificate keystore on the trusted development system.  This
 * keystore also includes a jar-signing certificate.
 *//*from   w w w .  j  a  v a 2s.com*/
protected static synchronized void createTexaiRootKeyStore() {
    //Preconditions
    assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy();

    if (!isTrustedDevelopmentSystem()) {
        return;
    }
    final char[] keyStorePassword = getRootKeyStorePassword();
    assert keyStorePassword != null;
    final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
    final File serverKeyStoreFile = new File(filePath);
    if (serverKeyStoreFile.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating Texai root key pair");
        final KeyPair rootKeyPair = generateRSAKeyPair3072();
        LOGGER.info("creating Texai root X.509 certificate");
        final X509Certificate rootX509Certificate = generateRootX509Certificate(rootKeyPair);
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        final StringBuilder stringBuilder = new StringBuilder();
        for (final byte b : rootX509Certificate.getEncoded()) {
            stringBuilder.append(Byte.toString(b));
            stringBuilder.append(", ");
        }
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        LOGGER.info("\nroot certificate bytes...\n" + stringBuilder.toString());
        LOGGER.info("creating Texai root X.509 certificate keystore");
        final KeyStore rootKeyStore = X509Utils.findOrCreateJceksKeyStore(filePath, keyStorePassword);
        rootKeyStore.setKeyEntry(ROOT_ALIAS, rootKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { rootX509Certificate });

        // create and store the jar-signer certificate
        LOGGER.info("creating jar-signer key pair");
        final KeyPair jarSignerKeyPair = generateRSAKeyPair2048();
        LOGGER.info("creating jar-signer X.509 certificate");
        final UUID jarSignerUUID = UUID.randomUUID();
        LOGGER.info("jar-signer UUID: " + jarSignerUUID);
        final X509Certificate jarSignerX509Certificate = generateX509Certificate(jarSignerKeyPair.getPublic(),
                rootKeyPair.getPrivate(), rootX509Certificate, jarSignerUUID, "RootCertificate"); // domainComponent
        LOGGER.info("jar-signer certificate:\n" + jarSignerX509Certificate);
        rootKeyStore.setKeyEntry(JAR_SIGNER_ALIAS, jarSignerKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { jarSignerX509Certificate, rootX509Certificate });
        rootKeyStore.store(new FileOutputStream(filePath), keyStorePassword);

        //Postconditions
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);
        assert privateKey != null;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException
            | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:net.jsign.PESignerCLI.java

void execute(String... args) throws SignerException {
    DefaultParser parser = new DefaultParser();
    try {/*  w w  w . j  av  a 2  s .co  m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help") || args.length == 0) {
            printHelp();
            return;
        }

        File keystore = cmd.hasOption("keystore") ? new File(cmd.getOptionValue("keystore")) : null;
        String storepass = cmd.getOptionValue("storepass");
        String storetype = cmd.getOptionValue("storetype");
        String alias = cmd.getOptionValue("alias");
        String keypass = cmd.getOptionValue("keypass");
        File keyfile = cmd.hasOption("keyfile") ? new File(cmd.getOptionValue("keyfile")) : null;
        File certfile = cmd.hasOption("certfile") ? new File(cmd.getOptionValue("certfile")) : null;
        String tsaurl = cmd.getOptionValue("tsaurl");
        String tsmode = cmd.getOptionValue("tsmode");
        String algorithm = cmd.getOptionValue("alg");
        String name = cmd.getOptionValue("name");
        String url = cmd.getOptionValue("url");
        File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0));

        if (keystore != null && storetype == null) {
            // guess the type of the keystore from the extension of the file
            String filename = keystore.getName().toLowerCase();
            if (filename.endsWith(".p12") || filename.endsWith(".pfx")) {
                storetype = "PKCS12";
            } else {
                storetype = "JKS";
            }
        }

        PrivateKey privateKey;
        Certificate[] chain;

        // some exciting parameter validation...
        if (keystore == null && keyfile == null && certfile == null) {
            throw new SignerException("keystore option, or keyfile and certfile options must be set");
        }
        if (keystore != null && (keyfile != null || certfile != null)) {
            throw new SignerException("keystore option can't be mixed with keyfile or certfile");
        }

        if (keystore != null) {
            // JKS or PKCS12 keystore 
            KeyStore ks;
            try {
                ks = KeyStore.getInstance(storetype);
            } catch (KeyStoreException e) {
                throw new SignerException("keystore type '" + storetype + "' is not supported", e);
            }

            if (!keystore.exists()) {
                throw new SignerException("The keystore " + keystore + " couldn't be found");
            }
            FileInputStream in = null;
            try {
                in = new FileInputStream(keystore);
                ks.load(in, storepass != null ? storepass.toCharArray() : null);
            } catch (Exception e) {
                throw new SignerException("Unable to load the keystore " + keystore, e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            }

            if (alias == null) {
                throw new SignerException("alias option must be set");
            }

            try {
                chain = ks.getCertificateChain(alias);
            } catch (KeyStoreException e) {
                throw new SignerException(e.getMessage(), e);
            }
            if (chain == null) {
                throw new SignerException(
                        "No certificate found under the alias '" + alias + "' in the keystore " + keystore);
            }

            char[] password = keypass != null ? keypass.toCharArray() : storepass.toCharArray();

            try {
                privateKey = (PrivateKey) ks.getKey(alias, password);
            } catch (Exception e) {
                throw new SignerException("Failed to retrieve the private key from the keystore", e);
            }

        } else {
            // separate private key and certificate files (PVK/SPC)
            if (keyfile == null) {
                throw new SignerException("keyfile option must be set");
            }
            if (!keyfile.exists()) {
                throw new SignerException("The keyfile " + keyfile + " couldn't be found");
            }
            if (certfile == null) {
                throw new SignerException("certfile option must be set");
            }
            if (!certfile.exists()) {
                throw new SignerException("The certfile " + certfile + " couldn't be found");
            }

            // load the certificate chain
            try {
                chain = loadCertificateChain(certfile);
            } catch (Exception e) {
                throw new SignerException("Failed to load the certificate from " + certfile, e);
            }

            // load the private key
            try {
                privateKey = PVK.parse(keyfile, keypass);
            } catch (Exception e) {
                throw new SignerException("Failed to load the private key from " + keyfile, e);
            }
        }

        if (algorithm != null && DigestAlgorithm.of(algorithm) == null) {
            throw new SignerException("The digest algorithm " + algorithm + " is not supported");
        }

        if (file == null) {
            throw new SignerException("missing file argument");
        }
        if (!file.exists()) {
            throw new SignerException("The file " + file + " couldn't be found");
        }

        PEFile peFile;
        try {
            peFile = new PEFile(file);
        } catch (IOException e) {
            throw new SignerException("Couldn't open the executable file " + file, e);
        }

        // and now the actual work!
        PESigner signer = new PESigner(chain, privateKey).withProgramName(name).withProgramURL(url)
                .withDigestAlgorithm(DigestAlgorithm.of(algorithm))
                .withTimestamping(tsaurl != null || tsmode != null)
                .withTimestampingMode(TimestampingMode.of(tsmode)).withTimestampingAutority(tsaurl);

        try {
            System.out.println("Adding Authenticode signature to " + file);
            signer.sign(peFile);
        } catch (Exception e) {
            throw new SignerException("Couldn't sign " + file, e);
        } finally {
            try {
                peFile.close();
            } catch (IOException e) {
                System.err.println("Couldn't close " + file);
                e.printStackTrace(System.err);
            }
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

/**
 * Instantiates the encryptor and digester using the configuration properties. If the properties
 * are not found, reasonable defaults are used.
 * /*from  w  w  w. j a v a 2s .c  om*/
 * @param provider
 *            The provider to use (ex. BC)
 * @param keyStore
 *            The keystore from which to load the secret encryption key
 * @param keyPassword
 *            The secret key password
 * @throws Exception
 */
private void configureEncryption(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception {
    SecretKey secretKey = null;

    if (!keyStore.containsAlias(SECRET_KEY_ALIAS)) {
        logger.debug("encryption key not found, generating new one");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptionConfig.getEncryptionAlgorithm(),
                provider);
        keyGenerator.init(encryptionConfig.getEncryptionKeyLength());
        secretKey = keyGenerator.generateKey();
        KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey);
        keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword));
    } else {
        logger.debug("found encryption key in keystore");
        secretKey = (SecretKey) keyStore.getKey(SECRET_KEY_ALIAS, keyPassword);
    }

    /*
     * Now that we have a secret key, store it in the encryption settings so that we can use it
     * to encryption things client side.
     */
    encryptionConfig.setSecretKey(secretKey.getEncoded());

    encryptor = new KeyEncryptor();
    encryptor.setProvider(provider);
    encryptor.setKey(secretKey);
    encryptor.setFormat(Output.BASE64);

    digester = new Digester();
    digester.setProvider(provider);
    digester.setAlgorithm(encryptionConfig.getDigestAlgorithm());
    digester.setFormat(Output.BASE64);
}

From source file:it.cnr.icar.eric.common.security.KeystoreMover.java

public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword,
        String sourceAlias, String sourceKeyPassword, String destinationKeystoreType,
        String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias,
        String destinationKeyPassword) throws Exception {

    char[] sourceKeystorePasswordArr = null;
    if (sourceKeystorePassword != null) {
        sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray();
    }/*w w w .  j a  v  a  2 s. c  o  m*/

    char[] sourceKeyPasswordArr = sourceKeystorePasswordArr;
    if (sourceKeyPassword != null) {
        sourceKeyPasswordArr = sourceKeyPassword.toCharArray();
    }

    char[] destinationKeystorePasswordArr = null;
    if (destinationKeystorePassword != null) {
        destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray();
    }

    char[] destinationKeyPasswordArr = destinationKeystorePasswordArr;
    if (destinationKeyPassword != null) {
        destinationKeyPasswordArr = destinationKeyPassword.toCharArray();
    }

    FileInputStream in;

    // --------  Load source keystore to memory ---------
    in = new FileInputStream(sourceKeystorePath);
    KeyStore ksin = KeyStore.getInstance(sourceKeystoreType);

    ksin.load(in, sourceKeystorePasswordArr);
    in.close();

    // --------  Load destination keystore initial contents to memory ---------
    KeyStore ksout = KeyStore.getInstance(destinationKeystoreType);

    try {
        in = new FileInputStream(destinationKeystorePath);
        ksout.load(in, destinationKeystorePasswordArr);
    } catch (java.io.FileNotFoundException e) {
        ksout.load(null, destinationKeystorePasswordArr);
    } finally {
        in.close();
    }

    Enumeration<String> en = ksin.aliases();
    while (en.hasMoreElements()) {
        String alias = en.nextElement();

        if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) {

            if (ksout.containsAlias(alias)) {
                log.info(CommonResourceBundle.getInstance().getString(
                        "message.destinationKeystorePathAlreadyContains",
                        new Object[] { destinationKeystorePath, alias }));
                continue;
            }

            //Use existing alias if no destinationAlias specified
            if (destinationAlias == null) {
                destinationAlias = alias;
            }

            if (ksin.isCertificateEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate",
                        new Object[] { alias }));
                ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias));
            }

            if (ksin.isKeyEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingKey",
                        new Object[] { alias }));
                Certificate[] certChain = ksin.getCertificateChain(alias);
                ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr),
                        destinationKeyPasswordArr, certChain);
            }
        }

    }

    //---------  Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores--------------
    FileOutputStream out = new FileOutputStream(destinationKeystorePath);
    ksout.store(out, destinationKeystorePasswordArr);
    out.close();
    log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful"));
}

From source file:org.tolven.config.model.CredentialManager.java

public void changeGroupCredentialPassword(PasswordInfo passwordInfo, char[] oldPassword, char[] newPassword)
        throws IOException, GeneralSecurityException {
    if (oldPassword == null)
        throw new RuntimeException("Old password '" + passwordInfo.getRefId() + "' is null");
    if (!getPasswordHolder().verify(passwordInfo, oldPassword))
        throw new RuntimeException("Old Password is invalid for '" + passwordInfo.getRefId() + "'");
    if (newPassword == null)
        throw new RuntimeException("New password '" + passwordInfo.getRefId() + "' is null");
    CertificateGroupDetail certGroup = getTolvenConfigWrapper().getCredentialGroup(passwordInfo.getRefId());
    CertificateKeyDetail keyDetail = certGroup.getKey();
    PrivateKey privateKey = getPrivateKey(keyDetail, oldPassword);
    File keyFile = new File(keyDetail.getSource());
    KeyStore keyStore = null;
    File keyStoreFile = null;// w  w  w . j ava  2  s. c o m
    CertificateKeyStoreDetail certKeyStoreDetail = certGroup.getKeyStore();
    if (certKeyStoreDetail != null) {
        keyStore = getTolvenConfigWrapper().getKeyStore(oldPassword, certKeyStoreDetail);
        keyStoreFile = new File(certKeyStoreDetail.getSource());
    }
    TrustStoreDetail trustStoreDetail = getTolvenConfigWrapper().getTrustStoreDetail(passwordInfo.getRefId());
    KeyStore trustStore = null;
    File trustStoreFile = null;
    if (trustStore != null) {
        trustStore = getTolvenConfigWrapper().getTrustStore(oldPassword, trustStoreDetail);
        trustStoreFile = new File(trustStoreDetail.getSource());
    }
    File tmpKey = null;
    File tmpKeyStore = null;
    File tmpTrustStore = null;
    boolean success = false;
    try {
        getTolvenConfigWrapper().getBuildDir().mkdirs();
        tmpKey = new File(getTolvenConfigWrapper().getBuildDir(), keyFile.getName());
        write(privateKey, keyDetail.getFormat(), tmpKey, newPassword);
        if (keyStoreFile != null) {
            tmpKeyStore = new File(getTolvenConfigWrapper().getBuildDir(), keyStoreFile.getName());
            String alias = keyStore.aliases().nextElement();
            Key key = keyStore.getKey(alias, oldPassword);
            Certificate[] chain = keyStore.getCertificateChain(alias);
            keyStore.setKeyEntry(alias, key, newPassword, chain);
            write(keyStore, tmpKeyStore, newPassword);
        }
        if (trustStoreFile != null) {
            tmpTrustStore = new File(getTolvenConfigWrapper().getBuildDir(), trustStoreFile.getName());
            write(trustStore, tmpTrustStore, newPassword);
        }
        FileUtils.copyFile(tmpKey, keyFile);
        if (keyStoreFile != null) {
            FileUtils.copyFile(tmpKeyStore, keyStoreFile);
        }
        if (trustStoreFile != null) {
            FileUtils.copyFile(tmpTrustStore, trustStoreFile);
        }
        success = true;
    } finally {
        if (success) {
            if (tmpKey != null) {
                tmpKey.delete();
            }
            if (tmpKeyStore != null) {
                tmpKeyStore.delete();
            }
            if (tmpKeyStore != null) {
                tmpKeyStore.delete();
            }
            getPasswordHolder().changePassword(passwordInfo, oldPassword, newPassword);
        }
    }
}

From source file:com.adito.boot.KeyStoreManager.java

/**
 * Import a key in PKCS12 key format/*from w  ww . ja v a  2 s . com*/
 * 
 * @param keyFile file to import
 * @param password password for key
 * @param alias alias for key
 * @param newAlias 
 * @throws Exception on any error
 * @return the alias of the key imported
 */
public String importPKCS12Key(File keyFile, String password, String alias, String newAlias) throws Exception {
    KeyStore kspkcs12 = KeyStore.getInstance("PKCS12");
    kspkcs12.load(new FileInputStream(keyFile), password == null ? null : password.toCharArray());
    boolean hasTemp = false;
    if (isKeyStoreEmpty()) {
        if (isKeyStoreExists()) {
            deleteKeyStore();
        }
        createKeyStore();
        String dname = "cn=tmp, ou=tmp, o=tmp, l=tmp, st=tmp, c=GB";
        createKey("temporary-key", dname);
        hasTemp = true;
        reloadKeystore();
    }
    try {

        String firstAlias = (String) kspkcs12.aliases().nextElement();

        if (Util.isNullOrTrimmedBlank(alias)) {
            log.info("Alias not specified, importing first alias " + firstAlias);
            alias = firstAlias;
        }

        if (Util.isNullOrTrimmedBlank(newAlias)) {
            log.info("New alias not specified, using imported alias " + alias);
            newAlias = alias;
        }

        Certificate c[] = kspkcs12.getCertificateChain(alias);
        // Make sure we don't have a null chain
        if (c == null)
            c = new Certificate[] {};
        Key key = kspkcs12.getKey(alias, password == null ? null : password.toCharArray());
        if (key == null) {
            throw new Exception("No alias of '" + alias + "' in imported PKCS12 key file.");
        }
        this.keyStore.setKeyEntry(newAlias, key, getKeyStorePassword().toCharArray(), c);
    } finally {
        if (hasTemp || keyStore.containsAlias("temporary-key"))
            this.keyStore.deleteEntry("temporary-key");
        OutputStream out = null;
        try {
            out = new FileOutputStream(keyStoreFile.getAbsolutePath());
            getKeyStore().store(out, getKeyStorePassword().toCharArray());
        } finally {
            Util.closeStream(out);
        }
        updateRepository(false);
    }

    return newAlias;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

@Test
public void test07SignedOcsp() throws Exception {
    assertTrue("This test can only be run on a full EJBCA installation.",
            ((HttpURLConnection) new URL(httpReqPath + '/').openConnection()).getResponseCode() == 200);

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)
    try {//from ww  w  .j  a  v  a  2  s .  c  o  m
        KeyPair keys = createUserCert(caid);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));

        X509CertificateHolder chain[] = new X509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new JcaContentSignerBuilder("SHA1WithRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), chain);

        // First test with a signed OCSP request that can be verified
        Collection<Certificate> cacerts = new ArrayList<Certificate>();
        cacerts.add(cacert);
        CaCertificateCache certcache = CaCertificateCache.INSTANCE;
        certcache.loadCertificates(cacerts);
        X509Certificate signer = checkRequestSignature("127.0.0.1", req, certcache);
        assertNotNull(signer);
        assertEquals(ocspTestCert.getSerialNumber().toString(16), signer.getSerialNumber().toString(16));

        // Try with an unsigned request, we should get a SignRequestException
        req = gen.build();
        boolean caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the signing certificate has expired
        store = KeyStore.getInstance("PKCS12", "BC");
        fis = new ByteArrayInputStream(ksexpired);
        store.load(fis, "foo123".toCharArray());
        certs = KeyTools.getCertChain(store, "ocspclient");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        pk = (PrivateKey) store.getKey("ocspclient", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);
    } finally {
        endEntityManagementSession.deleteUser(admin, "ocsptest");
    }

}