Java Code Examples for java.security.KeyStore.getCertificate()

The following are Jave code examples for showing how to use getCertificate() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: nutz-pay   File: CertUtil.java   View Source Code Vote up 7 votes
/**
 * 通过keystore获取私钥证书的certId值
 * @param keyStore
 * @return
 */
private static String getCertIdIdByStore(KeyStore keyStore) {
	Enumeration<String> aliasenum = null;
	try {
		aliasenum = keyStore.aliases();
		String keyAlias = null;
		if (aliasenum.hasMoreElements()) {
			keyAlias = aliasenum.nextElement();
		}
		X509Certificate cert = (X509Certificate) keyStore
				.getCertificate(keyAlias);
		return cert.getSerialNumber().toString();
	} catch (KeyStoreException e) {
		log.error("getCertIdIdByStore Error", e);
		return null;
	}
}
 
Example 2
Project: openjdk-jdk10   File: MVJarSigningTest.java   View Source Code Vote up 7 votes
private static void signWithJarSignerAPI(String jarName)
        throws Throwable {
    // Get JarSigner
    try (FileInputStream fis = new FileInputStream(KEYSTORE)) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(fis, STOREPASS.toCharArray());
            PrivateKey pk = (PrivateKey)ks.getKey(ALIAS, KEYPASS.toCharArray());
            Certificate cert = ks.getCertificate(ALIAS);
            JarSigner signer = new JarSigner.Builder(pk,
                    CertificateFactory.getInstance("X.509").generateCertPath(
                            Collections.singletonList(cert)))
                    .build();
        // Sign jar
        try (ZipFile src = new JarFile(jarName);
                FileOutputStream out = new FileOutputStream(SIGNED_JAR)) {
            signer.sign(src,out);
        }
    }
}
 
Example 3
Project: jdk8u-jdk   File: PKIXParameters.java   View Source Code Vote up 6 votes
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 4
Project: jdk8u-jdk   File: Main.java   View Source Code Vote up 6 votes
/**
 * Stores the (leaf) certificates of a keystore in a hashtable.
 * All certs belonging to the same CA are stored in a vector that
 * in turn is stored in the hashtable, keyed by the CA's subject DN
 */
private void keystorecerts2Hashtable(KeyStore ks,
            Hashtable<Principal, Vector<Certificate>> hash)
    throws Exception {

    for (Enumeration<String> aliases = ks.aliases();
                                    aliases.hasMoreElements(); ) {
        String alias = aliases.nextElement();
        Certificate cert = ks.getCertificate(alias);
        if (cert != null) {
            Principal subjectDN = ((X509Certificate)cert).getSubjectDN();
            Vector<Certificate> vec = hash.get(subjectDN);
            if (vec == null) {
                vec = new Vector<Certificate>();
                vec.addElement(cert);
            } else {
                if (!vec.contains(cert)) {
                    vec.addElement(cert);
                }
            }
            hash.put(subjectDN, vec);
        }
    }
}
 
Example 5
Project: azure-libraries-for-java   File: HostNameSslBindingImpl.java   View Source Code Vote up 6 votes
private String getCertificateThumbprint(String pfxPath, String password) {
    try {
        InputStream inStream = new FileInputStream(pfxPath);

        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(inStream, password.toCharArray());

        String alias = ks.aliases().nextElement();
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        inStream.close();
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        return BaseEncoding.base16().encode(sha.digest(certificate.getEncoded()));
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 6
Project: jdk8u-jdk   File: Main.java   View Source Code Vote up 6 votes
private static String verifyCRL(KeyStore ks, CRL crl)
        throws Exception {
    X509CRLImpl xcrl = (X509CRLImpl)crl;
    X500Principal issuer = xcrl.getIssuerX500Principal();
    for (String s: e2i(ks.aliases())) {
        Certificate cert = ks.getCertificate(s);
        if (cert instanceof X509Certificate) {
            X509Certificate xcert = (X509Certificate)cert;
            if (xcert.getSubjectX500Principal().equals(issuer)) {
                try {
                    ((X509CRLImpl)crl).verify(cert.getPublicKey());
                    return s;
                } catch (Exception e) {
                }
            }
        }
    }
    return null;
}
 
Example 7
Project: openjdk-jdk10   File: MetadataEmptyTest.java   View Source Code Vote up 6 votes
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 8
Project: xitk   File: P12CertExportCmd.java   View Source Code Vote up 6 votes
@Override
protected Object execute0() throws Exception {
    KeyStore ks = getKeyStore();

    String keyname = null;
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) {
            keyname = alias;
            break;
        }
    }

    if (keyname == null) {
        throw new CmdFailure("could not find private key");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(keyname);
    saveVerbose("saved certificate to file", new File(outFile), cert.getEncoded());

    return null;
}
 
Example 9
Project: openjdk-jdk10   File: DefaultSignatureAlgorithm.java   View Source Code Vote up 6 votes
private static void run(String keyAlg, int keySize,
                String expectedSigAlg, String sigAlg) throws Exception {
    String alias = keyAlg + keySize + System.currentTimeMillis();
    String cmd = "-keystore ks -storepass changeit" +
            " -keypass changeit -alias " + alias +
            " -keyalg " + keyAlg + " -keysize " + keySize +
            " -genkeypair -dname CN=" + alias + " -debug";
    if (sigAlg != null) {
        cmd += " -sigalg " + sigAlg;
    }
    Main.main(cmd.split(" "));

    KeyStore ks = KeyStore.getInstance(
            new File("ks"), "changeit".toCharArray());
    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    String actualSigAlg = cert.getSigAlgName();
    if (!actualSigAlg.equals(expectedSigAlg)) {
        throw new Exception("Failure at " + alias + ": expected "
                + expectedSigAlg + ", actually " + actualSigAlg);
    }
}
 
Example 10
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 6 votes
/**
 * Iterates over the certificates stored in the truststore to verify the signature of the provided certificate
 * 
 * @param trustStoreFilename The relative path and file name of the truststore
 * @param certificate The certificate whose signature needs to be signed
 * @return True, if the provided certificate has been signed by one of the certificates in the 
 * 		   truststore, false otherwise
 */
public static boolean verifySignature(X509Certificate certificate, String trustStoreFilename) {
	KeyStore trustStore = SecurityUtils.getTrustStore(trustStoreFilename, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	X500Principal expectedIssuer = certificate.getIssuerX500Principal();
	
	try {
		Enumeration<String> aliases = trustStore.aliases();
		while (aliases.hasMoreElements()) {
			X509Certificate rootCA = (X509Certificate) trustStore.getCertificate(aliases.nextElement());
			if (rootCA.getSubjectX500Principal().getName().equals(expectedIssuer.getName()) &&
				verifySignature(certificate, rootCA)) return true;
		}
	} catch (KeyStoreException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to verify trust " +
						  "status of certificate with distinguished name '" + 
						  certificate.getSubjectX500Principal().getName() + "' with truststore at " +
						  "location '" + trustStoreFilename + "'", e);
	}
	
	return false;
}
 
Example 11
Project: openjdk-jdk10   File: StartDateTest.java   View Source Code Vote up 5 votes
static Date getIssueDate(String alias) throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    return cert.getNotBefore();
}
 
Example 12
Project: q-mail   File: KeyStoreProvider.java   View Source Code Vote up 5 votes
public X509Certificate getServerCertificate() {
    try {
        KeyStore keyStore = loadKeyStore();
        return (X509Certificate) keyStore.getCertificate(SERVER_CERTIFICATE_ALIAS);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Project: openjdk-jdk10   File: Main.java   View Source Code Vote up 5 votes
/**
 * Stores the (leaf) certificates of a keystore in a hashtable.
 * All certs belonging to the same CA are stored in a vector that
 * in turn is stored in the hashtable, keyed by the CA's subject DN.
 * Each cert comes with a string label that shows its origin and alias.
 */
private void keystorecerts2Hashtable(KeyStore ks,
            Hashtable<Principal, Vector<Pair<String,X509Certificate>>> hash)
    throws Exception {

    for (Enumeration<String> aliases = ks.aliases();
                                    aliases.hasMoreElements(); ) {
        String alias = aliases.nextElement();
        Certificate cert = ks.getCertificate(alias);
        if (cert != null) {
            Principal subjectDN = ((X509Certificate)cert).getSubjectDN();
            Pair<String,X509Certificate> pair = new Pair<>(
                    String.format(
                            rb.getString(ks == caks ?
                                    "alias.in.cacerts" :
                                    "alias.in.keystore"),
                            alias),
                    (X509Certificate)cert);
            Vector<Pair<String,X509Certificate>> vec = hash.get(subjectDN);
            if (vec == null) {
                vec = new Vector<>();
                vec.addElement(pair);
            } else {
                if (!vec.contains(pair)) {
                    vec.addElement(pair);
                }
            }
            hash.put(subjectDN, vec);
        }
    }
}
 
Example 14
Project: xitk   File: P11ProviderTestCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    KeyStore ks = KeyStore.getInstance("PKCS11", XiSecurityConstants.PROVIDER_NAME_XIPKI);
    ks.load(null, null);
    if (verbose.booleanValue()) {
        println("available aliases:");
        Enumeration<?> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias2 = (String) aliases.nextElement();
            println("    " + alias2);
        }
    }

    String alias = getAlias();
    println("alias: " + alias);
    PrivateKey key = (PrivateKey) ks.getKey(alias, null);
    if (key == null) {
        println("could not find key with alias '" + alias + "'");
        return null;
    }

    Certificate cert = ks.getCertificate(alias);
    if (cert == null) {
        println("could not find certificate to verify signature");
        return null;
    }
    PublicKey pubKey = cert.getPublicKey();

    String sigAlgo = getSignatureAlgo(pubKey);
    println("signature algorithm: " + sigAlgo);
    Signature sig = Signature.getInstance(sigAlgo, XiSecurityConstants.PROVIDER_NAME_XIPKI);
    sig.initSign(key);

    byte[] data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    sig.update(data);
    byte[] signature = sig.sign(); // CHECKSTYLE:SKIP
    println("signature created successfully");

    Signature ver = Signature.getInstance(sigAlgo, "BC");
    ver.initVerify(pubKey);
    ver.update(data);
    boolean valid = ver.verify(signature);
    println("signature valid: " + valid);
    return null;
}
 
Example 15
Project: xitk   File: ConvertKeystoreCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    File realInFile = new File(IoUtil.expandFilepath(inFile));
    File realOutFile = new File(IoUtil.expandFilepath(outFile));

    if (CompareUtil.equalsObject(realInFile, realOutFile)) {
        throw new IllegalCmdParamException("in and out cannot be the same");
    }

    KeyStore inKs = KeyStore.getInstance(inType);
    KeyStore outKs = KeyStore.getInstance(outType);
    outKs.load(null);

    char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
    FileInputStream inStream = new FileInputStream(realInFile);
    try {
        inKs.load(inStream, inPassword);
    } finally {
        inStream.close();
    }

    char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
    Enumeration<String> aliases = inKs.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (inKs.isKeyEntry(alias)) {
            Certificate[] certs = inKs.getCertificateChain(alias);
            Key key = inKs.getKey(alias, inPassword);
            outKs.setKeyEntry(alias, key, outPassword, certs);
        } else {
            Certificate cert = inKs.getCertificate(alias);
            outKs.setCertificateEntry(alias, cert);
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    outKs.store(bout, outPassword);
    saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
    return null;
}
 
Example 16
Project: iotgateway   File: MqttGatewaySecurityConfiguration.java   View Source Code Vote up 5 votes
public String getClientId() {
  if (this.isTokenBased()) {
    return sha256(this.getAccessToken().getBytes(StandardCharsets.UTF_8));
  } else {
    try {
      FileInputStream is = new FileInputStream(this.getKeystore());

      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      keystore.load(is, this.getKeystorePassword().toCharArray());

      Key key = keystore.getKey(this.getKeystoreKeyAlias(), this.getKeystorePassword().toCharArray());
      if (key instanceof PrivateKey) {
        // Get certificate of public key
        java.security.cert.Certificate cert = keystore.getCertificate(this.getKeystoreKeyAlias());

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        return sha256(publicKey.getEncoded());
      } else {
        throw new RuntimeException("No public key!");
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 17
Project: openjdk-jdk10   File: Main.java   View Source Code Vote up 4 votes
/**
 * Import a single entry named alias from srckeystore
 * @return  1 if the import action succeed
 *          0 if user choose to ignore an alias-dumplicated entry
 *          2 if setEntry throws Exception
 */
private int doImportKeyStoreSingle(KeyStore srckeystore, String alias)
        throws Exception {

    String newAlias = (dest==null) ? alias : dest;

    if (keyStore.containsAlias(newAlias)) {
        Object[] source = {alias};
        if (noprompt) {
            System.err.println(new MessageFormat(rb.getString(
                    "Warning.Overwriting.existing.alias.alias.in.destination.keystore")).format(source));
        } else {
            String reply = getYesNoReply(new MessageFormat(rb.getString(
                    "Existing.entry.alias.alias.exists.overwrite.no.")).format(source));
            if ("NO".equals(reply)) {
                newAlias = inputStringFromStdin(rb.getString
                        ("Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry."));
                if ("".equals(newAlias)) {
                    System.err.println(new MessageFormat(rb.getString(
                            "Entry.for.alias.alias.not.imported.")).format(
                            source));
                    return 0;
                }
            }
        }
    }

    Pair<Entry,char[]> objs = recoverEntry(srckeystore, alias, srcstorePass, srckeyPass);
    Entry entry = objs.fst;

    PasswordProtection pp = null;

    // According to keytool.html, "The destination entry will be protected
    // using destkeypass. If destkeypass is not provided, the destination
    // entry will be protected with the source entry password."
    // so always try to protect with destKeyPass.
    char[] newPass = null;
    if (destKeyPass != null) {
        newPass = destKeyPass;
        pp = new PasswordProtection(destKeyPass);
    } else if (objs.snd != null) {
        newPass = objs.snd;
        pp = new PasswordProtection(objs.snd);
    }

    try {
        Certificate c = srckeystore.getCertificate(alias);
        if (c != null) {
            checkWeak("<" + newAlias + ">", c);
        }
        keyStore.setEntry(newAlias, entry, pp);
        // Place the check so that only successful imports are blocked.
        // For example, we don't block a failed SecretEntry import.
        if (P12KEYSTORE.equalsIgnoreCase(storetype)) {
            if (newPass != null && !Arrays.equals(newPass, storePass)) {
                throw new Exception(rb.getString(
                        "The.destination.pkcs12.keystore.has.different.storepass.and.keypass.Please.retry.with.destkeypass.specified."));
            }
        }
        return 1;
    } catch (KeyStoreException kse) {
        Object[] source2 = {alias, kse.toString()};
        MessageFormat form = new MessageFormat(rb.getString(
                "Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported."));
        System.err.println(form.format(source2));
        return 2;
    }
}
 
Example 18
Project: openjdk-jdk10   File: BigCRL.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    int n = 500000;
    String ks = System.getProperty("test.src", ".")
            + "/../../../../javax/net/ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "."
            + X509CertInfo.DN_NAME);

    Date date = new Date();
    PrivateKey privateKey = (PrivateKey)
            keyStore.getKey(alias, pass.toCharArray());
    String sigAlgName = signerCertImpl.getSigAlgOID();

    X509CRLEntry[] badCerts = new X509CRLEntry[n];
    CRLExtensions ext = new CRLExtensions();
    ext.set("Reason", new CRLReasonCodeExtension(1));
    for (int i = 0; i < n; i++) {
        badCerts[i] = new X509CRLEntryImpl(
                BigInteger.valueOf(i), date, ext);
    }
    X509CRLImpl crl = new X509CRLImpl(owner, date, date, badCerts);
    crl.sign(privateKey, sigAlgName);
    byte[] data = crl.getEncodedInternal();

    // Make sure the CRL is big enough
    if ((data[1]&0xff) != 0x84) {
        throw new Exception("The file should be big enough?");
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cf.generateCRL(new ByteArrayInputStream(data));
}
 
Example 19
Project: BTNotifierAndroid   File: SslUtils.java   View Source Code Vote up 4 votes
public static void generateSelfSignedCertificate() throws Exception {
    String alias = "nuntius";
    KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
    ks.load(null);
    Enumeration<String> aliases = ks.aliases();
    boolean found = false;
    while (aliases.hasMoreElements()) {
        String currentAlias = aliases.nextElement();
        if (alias.equals(currentAlias)) {
            found = true;
            Log.i(TAG, "Self Signed Certificate found in keystore");
            Key key = ks.getKey(alias, pwd);
            Log.i(TAG, "Key: " + key);
            Certificate certificate = ks.getCertificate(alias);
            Log.i(TAG, "Certificate: " + certificate);
        }
    }

    if (found) {
        return;
    }

    Log.i(TAG, "Self Signed Certificate not found in keystore. Generating a new one...");

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    KeyPair keyPair = keyGen.generateKeyPair();

    X500Name subject = new X500Name("CN=nuntius");
    X500Name issuer = subject ;

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            issuer,
            new BigInteger(64, new SecureRandom()),
            NOT_BEFORE,
            NOT_AFTER,
            subject,
            keyPair.getPublic());

    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    cert.verify(keyPair.getPublic());

    Log.i(TAG, "Certificate generated: " + cert);

    ks.setKeyEntry(alias, keyPair.getPrivate(), pwd, new Certificate[] { cert });
}
 
Example 20
Project: openjdk-jdk10   File: Function.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        try (FileOutputStream fout =new FileOutputStream("src.zip");
                ZipOutputStream zout = new ZipOutputStream(fout)) {
            zout.putNextEntry(new ZipEntry("x"));
            zout.write(new byte[10]);
            zout.closeEntry();
        }

        sun.security.tools.keytool.Main.main(
                ("-storetype jks -keystore ks -storepass changeit" +
                        " -keypass changeit -dname" +
                        " CN=RSA -alias r -genkeypair -keyalg rsa").split(" "));

        JarSigner.Builder jsb;

        try (FileInputStream fis = new FileInputStream("ks")) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(fis, "changeit".toCharArray());
            PrivateKey key = (PrivateKey)ks.getKey("r", "changeit".toCharArray());
            Certificate cert = ks.getCertificate("r");
            jsb = new JarSigner.Builder(key,
                    CertificateFactory.getInstance("X.509").generateCertPath(
                            Collections.singletonList(cert)));
        }

        jsb.digestAlgorithm("SHA1");
        jsb.signatureAlgorithm("SHA1withRSA");

        AtomicInteger counter = new AtomicInteger(0);
        StringBuilder sb = new StringBuilder();
        jsb.eventHandler(
                (a, f)->{
                    counter.incrementAndGet();
                    sb.append(a).append(' ').append(f).append('\n');
                });

        OutputStream blackHole = new OutputStream() {
            @Override
            public void write(int b) throws IOException { }
        };

        try (ZipFile src = new ZipFile("src.zip")) {
            jsb.build().sign(src, blackHole);
        }

        if (counter.get() != 4) {
            throw new Exception("Event number is " + counter.get()
                    + ":\n" + sb.toString());
        }

        // Provider test.
        Provider p = new MyProvider();
        jsb.digestAlgorithm("Five", p);
        jsb.signatureAlgorithm("SHA1WithRSA", p);
        try (ZipFile src = new ZipFile("src.zip");
                FileOutputStream out = new FileOutputStream("out.jar")) {
            jsb.build().sign(src, out);
        }

        try (JarFile signed = new JarFile("out.jar")) {
            Manifest man = signed.getManifest();
            assertTrue(man.getAttributes("x").getValue("Five-Digest").equals("FAKE"));

            Manifest sf = new Manifest(signed.getInputStream(
                    signed.getJarEntry("META-INF/SIGNER.SF")));
            assertTrue(sf.getMainAttributes().getValue("Five-Digest-Manifest")
                    .equals("FAKE"));
            assertTrue(sf.getAttributes("x").getValue("Five-Digest").equals("FAKE"));

            try (InputStream sig = signed.getInputStream(
                    signed.getJarEntry("META-INF/SIGNER.RSA"))) {
                byte[] data = sig.readAllBytes();
                assertTrue(Arrays.equals(
                        Arrays.copyOfRange(data, data.length-8, data.length),
                        "FAKEFAKE".getBytes()));
            }
        }
    }