List of usage examples for java.security.cert X509Certificate verify
public abstract void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException;
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
private X509Certificate createMiddleCaCert(X500Name subject, PublicKey pubKey, KeyPair pKeyPair, X500Name issuer) throws Exception { BigInteger sno = BigInteger.valueOf(3); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + TWENTY_YEAR); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, subject, pubKey);//from w ww . ja v a 2s . com addSubjectKID(certBuilder, pubKey); addAuthorityKID(certBuilder, pKeyPair.getPublic()); certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3)); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU)); X509Certificate certificate = signCert(certBuilder, pKeyPair.getPrivate()); certificate.checkValidity(new Date()); certificate.verify(pKeyPair.getPublic()); setPKCS9Info(certificate); return certificate; }
From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java
public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, KeyPair keyPair, KeyPair pKeyPair) throws Exception { PublicKey pPubKey = pKeyPair.getPublic(); PrivateKey pPrivKey = pKeyPair.getPrivate(); X500Name idn = X500NameUtil.createClass3RootPrincipal(); BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + FIVE_YEAR); PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey); addSubjectKID(certBuilder, pubKey);/*w w w .ja v a2 s.c o m*/ addAuthorityKID(certBuilder, pPubKey); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU)); certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE)); if (exts != null) { Set<String> key = exts.keySet(); for (Iterator<String> it = key.iterator(); it.hasNext();) { String oid = it.next(); String value = exts.get(oid); if (!StringUtils.isBlank(value)) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, new DEROctetString(value.getBytes())); } } } X509Certificate certificate = signCert(certBuilder, pPrivKey); certificate.checkValidity(new Date()); certificate.verify(pPubKey); setPKCS9Info(certificate); return certificate; }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
/** * Generate the CA's certificate.//from ww w . j a v a2 s.c o m * * @param publicKey * Public key. * @param privateKey * Private key. * @param distinguishedName * Distinguished Name. * @param serialNumber * Unique serial number. * @param validDays * valid Days. * @param certFriendlyName Certificate friendly name * * @throws DigitalSigningException * Customized exception with error message. * * @return a Certificate. */ @SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.ExcessiveParameterList" }) // same handling for multiple exception types, parameters required for generation Certificate generateRootCert(PublicKey publicKey, PrivateKey privateKey, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays, String certFriendlyName) throws DigitalSigningException { try { X509V1CertificateGenerator v1CertGen = buildX509V1CertificateGenerator(publicKey, distinguishedName, serialNumber, validDays); X509Certificate cert = v1CertGen.generate(privateKey, BOUNCY_CASTLE_PROVIDER); cert.checkValidity(new Date()); cert.verify(publicKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(certFriendlyName)); return cert; } catch (Exception e) { throw new DigitalSigningException(ROOT_CA_GENERATION_ERROR_MESSAGE, e); } }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
/** * Generate intermediate certificate signed by CA. * * @param publicKey/*w w w .j a va2s . c o m*/ * Public key. * @param caPrivateKey * Private key. * @param caDistinguishedName * Issuer's Distinguished Name.. * @param distinguishedName * User's Distinguished Name. * @param serialNumber * Unique serial number. * @param validDays * valid Days. * @param friendName * Set a friendly name for the certificate. Can be null. * * @throws DigitalSigningException * Customized exception with error message. * * @return a Certificate. */ @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.AvoidCatchingGenericException" }) // This is minimal parameter list. // same handling for multiple exception types Certificate generateUserCert(PublicKey publicKey, PrivateKey caPrivateKey, X509Certificate caCert, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays) throws DigitalSigningException { try { X509V3CertificateGenerator v3CertGen = buildX509V3CertificateGenerator(publicKey, caCert, distinguishedName, serialNumber, validDays); X509Certificate cert = v3CertGen.generate(caPrivateKey, BOUNCY_CASTLE_PROVIDER); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("User Certificate")); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(publicKey)); return cert; } catch (Exception e) { throw new DigitalSigningException(CERT_GENERATION_ERROR_MESSAGE, e); } }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair) throws Exception { SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent()); KeyFactory kf = KeyFactory.getInstance(ALG_RSA); PublicKey publicKey = kf.generatePublic(rsaSpec); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - DateConstant.ONE_DAY), new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo); ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER) .build(pKeyPair.getPrivate()); X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER) .getCertificate(certBuilder.build(signer)); signedCert.verify(pKeyPair.getPublic()); return signedCert; }
From source file:com.vmware.demo.SamlUtils.java
/** * Generate a public x509 cert, based on a key. * * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed. * @param issuer If generating an SSL Cert, issuer needs to match hostname * @return// www . j ava2s. c o m * @throws SamlException */ public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException { X509Certificate binCert; try { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years v3CertGen.setSubjectDN(new X509Principal(issuer)); v3CertGen.setPublicKey(key.getPublic()); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false, new BasicConstraints(true)); // generate the actual cert binCert = v3CertGen.generate(key.getPrivate()); // check the cert binCert.checkValidity(new Date()); binCert.verify(key.getPublic()); } catch (Exception e) { throw new SamlException("Failed to generate certificate.", e); } return binCert; }
From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java
/** * If set, unilateral TLS authentication will occur, verifying the server * {@link X509Certificate} specified against the {@link PublicKey}. * /*from w w w.j a v a 2 s. c o m*/ * @param publicKey * public key to validate server TLS certificate against. */ public void setServicePublicKey(final PublicKey publicKey) { // Create TrustManager TrustManager[] trustManager = { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { X509Certificate serverCertificate = chain[0]; LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString()); LOG.debug("authentication type: " + authType); if (null == publicKey) { return; } try { serverCertificate.verify(publicKey); LOG.debug("valid server certificate"); } catch (InvalidKeyException e) { throw new CertificateException("Invalid Key"); } catch (NoSuchAlgorithmException e) { throw new CertificateException("No such algorithm"); } catch (NoSuchProviderException e) { throw new CertificateException("No such provider"); } catch (SignatureException e) { throw new CertificateException("Wrong signature"); } } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException("this trust manager cannot be used as server-side trust manager"); } } }; // Create SSL Context try { SSLContext sslContext = SSLContext.getInstance("TLS"); SecureRandom secureRandom = new SecureRandom(); sslContext.init(null, trustManager, secureRandom); LOG.debug("SSL context provider: " + sslContext.getProvider().getName()); // Setup TrustManager for validation Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext(); requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory()); } catch (KeyManagementException e) { String msg = "key management error: " + e.getMessage(); LOG.error(msg, e); throw new RuntimeException(msg, e); } catch (NoSuchAlgorithmException e) { String msg = "TLS algo not present: " + e.getMessage(); LOG.error(msg, e); throw new RuntimeException(msg, e); } }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
/** * Returns a {@code Certificate} with the received data. * * @param keypair//from ww w . j a va 2s . co m * key pair for the certificate * @param issuer * issuer for the certificate * @return a {@code Certificate} with the received data * @throws IOException * if there is an I/O or format problem with the certificate * data * @throws OperatorCreationException * if there was a problem creation a bouncy castle operator * @throws CertificateException * if any of the certificates in the keystore could not be * loaded * @throws InvalidKeyException * if there was a problem with the key * @throws NoSuchAlgorithmException * if an algorithm required to create the key store could not be * found * @throws NoSuchProviderException * if a required provider is missing * @throws SignatureException * if any problem occurs while signing the certificate */ private final Certificate getCertificate(final KeyPair keypair, final String issuer) throws IOException, OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { final X509v3CertificateBuilder builder; // Certificate builder final X509Certificate certificate; // Certificate // Generates the certificate builder builder = getCertificateBuilder(keypair.getPublic(), issuer); // Generates the signed certificate certificate = getSignedCertificate(builder, keypair.getPrivate()); // Verifies the certificate certificate.checkValidity(getCurrentDate()); certificate.verify(keypair.getPublic()); LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(), Arrays.asList(certificate.getEncoded())); LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey()); return certificate; }
From source file:edu.duke.cabig.c3pr.web.security.SecureWebServiceHandler.java
/** * @param cert//from w w w. j a va2 s .co m * @param crypto * @throws SignatureException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws InvalidKeyException * @throws WSSecurityException */ private void checkCertificateValidity(X509Certificate cert, Crypto crypto) throws InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, WSSecurityException { //cert.checkValidity(); String subjectdn = cert.getSubjectDN().getName(); String issuerdn = cert.getIssuerDN().getName(); if (subjectdn.equals(issuerdn)) { log.debug("This is a self-signed certificate. Verifying signature..."); cert.verify(cert.getPublicKey()); } else { X509Certificate signingcert = getIssuerCert(cert, crypto); if (signingcert != null) { checkCertificateValidity(signingcert, crypto); cert.verify(signingcert.getPublicKey()); } else { log.warn( "Unable to check the signature of the certificate, because the issuer's certificate is not found. Certificate: " + cert); } } }
From source file:be.fedict.trust.PublicKeyTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) { LOG.debug("child certificate issuer not the same as the issuer certificate subject"); LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal()); LOG.debug("certificate: " + certificate.getSubjectX500Principal()); LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal()); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate issuer not the same as the issuer certificate subject"); }// w w w .ja v a2s.c o m try { childCertificate.verify(certificate.getPublicKey()); } catch (Exception e) { LOG.debug("verification error: " + e.getMessage(), e); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "verification error: " + e.getMessage()); } if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) { LOG.warn("child certificate validity end is after certificate validity end"); LOG.warn("child certificate validity end: " + childCertificate.getNotAfter()); LOG.warn("certificate validity end: " + certificate.getNotAfter()); } if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) { LOG.warn("child certificate validity begin before certificate validity begin"); LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore()); LOG.warn("certificate validity begin: " + certificate.getNotBefore()); } if (true == validationDate.before(childCertificate.getNotBefore())) { LOG.debug("certificate is not yet valid"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate is not yet valid"); } if (true == validationDate.after(childCertificate.getNotAfter())) { LOG.debug("certificate already expired"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate already expired"); } if (-1 == certificate.getBasicConstraints()) { LOG.debug("certificate not a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA"); } if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) { LOG.debug("child should not be a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA"); } /* * SKID/AKID sanity check */ boolean isCa = isCa(certificate); boolean isChildCa = isCa(childCertificate); byte[] subjectKeyIdentifierData = certificate .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); byte[] authorityKeyIdentifierData = childCertificate .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (isCa && null == subjectKeyIdentifierData) { LOG.debug("certificate is CA and MUST contain a Subject Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate is CA and MUST contain a Subject Key Identifier"); } if (isChildCa && null == authorityKeyIdentifierData) { LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate is CA and MUST contain an Authority Key Identifier"); } if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) { AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure; try { authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing authority key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing authority key identifier structure"); } String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier())); SubjectKeyIdentifierStructure subjectKeyIdentifierStructure; try { subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing subject key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing subject key identifier structure"); } String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier())); if (!skidId.equals(akidId)) { LOG.debug( "certificate's subject key identifier does not match child certificate's authority key identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate's subject key identifier does not match child certificate's authority key identifier"); } } /* * We don't check pathLenConstraint since this one is only there to * protect the PKI business. */ return null; }