List of usage examples for java.security.cert CertificateException getMessage
public String getMessage()
From source file:be.fedict.eid.dss.client.DigitalSignatureServiceClient.java
/** * Verifies whether the given document has been signed and reports back on * the signing parties.//from ww w. j av a 2s. c om * * @param signedDocument * signed document to verify * @param mimeType * optional mime-type, default is "text/xml". * @param originalDocument * the optional original document. * @return a list of signature information objects detailing on the signing * parties. * @throws NotParseableXMLDocumentException * XML document was not parseable. */ public List<SignatureInfo> verifyWithSigners(byte[] signedDocument, String mimeType, byte[] originalDocument) throws NotParseableXMLDocumentException { ResponseBaseType responseBase = doVerification(signedDocument, mimeType, false, true, originalDocument); validateResult(responseBase); // parse VerificationReport List<SignatureInfo> signers = new LinkedList<SignatureInfo>(); VerificationReportType verificationReport = findVerificationReport(responseBase); if (null == verificationReport) { return signers; } List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (IndividualReportType individualReport : individualReports) { if (!DSSConstants.RESULT_MAJOR_SUCCESS.equals(individualReport.getResult().getResultMajor())) { LOG.warn("some invalid VR result reported: " + individualReport.getResult().getResultMajor()); continue; } SignedObjectIdentifierType signedObjectIdentifier = individualReport.getSignedObjectIdentifier(); Date signingTime = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties() .getSigningTime().toGregorianCalendar().getTime(); List<Object> details = individualReport.getDetails().getAny(); X509Certificate signer = null; String role = null; for (Object detail : details) { if (detail instanceof JAXBElement<?>) { JAXBElement<?> detailElement = (JAXBElement<?>) detail; if (detailedSignatureReportQName.equals(detailElement.getName())) { DetailedSignatureReportType detailedSignatureReport = (DetailedSignatureReportType) detailElement .getValue(); List<CertificateValidityType> certificateValidities = detailedSignatureReport .getCertificatePathValidity().getPathValidityDetail().getCertificateValidity(); CertificateValidityType certificateValidity = certificateValidities.get(0); byte[] encodedSigner = certificateValidity.getCertificateValue(); try { signer = (X509Certificate) this.certificateFactory .generateCertificate(new ByteArrayInputStream(encodedSigner)); } catch (CertificateException e) { throw new RuntimeException("cert decoding error: " + e.getMessage(), e); } PropertiesType properties = detailedSignatureReport.getProperties(); if (null != properties) { SignerRoleType signerRole = properties.getSignedProperties() .getSignedSignatureProperties().getSignerRole(); if (null != signerRole) { role = (String) signerRole.getClaimedRoles().getClaimedRole().get(0).getContent() .get(0); } } } } } if (null == signer) { throw new RuntimeException("no signer certificate present in verification report"); } SignatureInfo signatureInfo = new SignatureInfo(signer, signingTime, role); signers.add(signatureInfo); } return signers; }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Generate an X509 cert for use as the keystore cert chain * //w ww .ja v a 2 s . c o m * @param keyPair * @return */ private X509Certificate generateCertificate(KeyPair keyPair, NodeRef person) { X509Certificate cert = null; int validDuration = Integer .parseInt(config.getProperty(RepositoryManagedSignatureProviderFactory.VALID_DURATION)); // get user's first and last name Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(person); String firstName = String.valueOf(props.get(ContentModel.PROP_FIRSTNAME)); String lastName = String.valueOf(props.get(ContentModel.PROP_LASTNAME)); // backdate the start date by a day Calendar start = Calendar.getInstance(); start.add(Calendar.DATE, -1); java.util.Date startDate = start.getTime(); // what is the end date for this cert's validity? Calendar end = Calendar.getInstance(); end.add(Calendar.DATE, validDuration); java.util.Date endDate = end.getTime(); try { // This code works with newer versions of the BouncyCastle libraries, but not // the (severely outdated) version that ships with Alfresco /*X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder( new X500Principal("CN=" + firstName + " " + lastName), BigInteger.ONE, startDate, cal.getTime(), new X500Principal("CN=" + firstName + " " + lastName), keyPair.getPublic()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParam); X509CertificateHolder certHolder = certBuilder.build(sigGen); // now lets convert this thing back to a regular old java cert CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certIs = new ByteArrayInputStream(certHolder.getEncoded()); cert = (X509Certificate) cf.generateCertificate(certIs); certIs.close();*/ X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal subjectName = new X500Principal("CN=" + firstName + " " + lastName); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setNotBefore(startDate); certGen.setNotAfter(endDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // if we are actually generating a trusted cert, the action is a little different boolean generateTrusted = Boolean.parseBoolean( config.getProperty(RepositoryManagedSignatureProviderFactory.ENABLE_TRUSTED_CERTS)); if (generateTrusted) { KeyStore trustedKs = getTrustedKeyStore(); PrivateKey caKey = getCaKey(trustedKs); X509Certificate caCert = getCaCert(trustedKs); // set the issuer of the generated cert to the subject of the ca cert X500Principal caSubject = caCert.getSubjectX500Principal(); certGen.setIssuerDN(caSubject); //add the required extensions for the new cert certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); cert = certGen.generate(caKey, "BC"); //verify the cert cert.verify(caCert.getPublicKey()); } else { certGen.setIssuerDN(subjectName); cert = certGen.generate(keyPair.getPrivate(), "BC"); } } catch (CertificateException ce) { logger.error("CertificateException creating or validating X509 certificate for user: " + ce); throw new AlfrescoRuntimeException(ce.getMessage()); } catch (Exception ex) { logger.error("Unknown exception creating or validating X509 certificate for user : " + ex); ex.printStackTrace(); } return cert; }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
/** * addCACertificatesToTrustStore adds a CA certs in a stream to the trust store used for signature validation * * @param bis an X.509 certificate stream in PEM format in bytes * @throws CryptoException//ww w . j a v a 2s . c om * @throws InvalidArgumentException */ public void addCACertificatesToTrustStore(BufferedInputStream bis) throws CryptoException, InvalidArgumentException { if (bis == null) { throw new InvalidArgumentException("The certificate stream bis cannot be null"); } try { final Collection<? extends Certificate> certificates = cf.generateCertificates(bis); for (Certificate certificate : certificates) { addCACertificateToTrustStore(certificate); } } catch (CertificateException e) { throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e); } }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
/** * Resets curve name, hash algorithm and cert factory. Call this method when a config value changes * * @throws CryptoException//from w w w . j a va 2 s . c o m * @throws InvalidArgumentException */ private void resetConfiguration() throws CryptoException, InvalidArgumentException { setSecurityLevel(securityLevel); setHashAlgorithm(hashAlgorithm); try { cf = CertificateFactory.getInstance(CERTIFICATE_FORMAT); } catch (CertificateException e) { CryptoException ex = new CryptoException( "Cannot initialize " + CERTIFICATE_FORMAT + " certificate factory. Error = " + e.getMessage(), e); logger.error(ex.getMessage(), ex); throw ex; } }
From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java
/** * Metodo encargado de la verificacin de los certificados * //from ww w.j av a 2s .c o m * @param certificadoX509 * @throws ExcepcionErrorInterno */ public CodigoError validarCRL(X509Certificate certificadoX509) { try { // 1.- Inicia la factoria de certificados CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN()); CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); // 2.- Configuracin de los parametros del validador // 2.1.- Para comprobar que el camino de confianza no esta roto, // tengo en cuenta todos los certificados PKIXParameters parametros = new PKIXParameters(certificadosConfianza); // Fecha para la comprobacin de validez. parametros.setDate(new Date()); if (validacionOnline) { // Para la validacin online de del estado de revocacin de los // certificados // ************ // creo un almacen( cache ) de certificados y CRLs para no tener // que conectarme a las crls // en cada validacin // Genero un listado de las CRLS que vamos a utilizar para la // validacin del certificado. List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>(); // Aade las crls de los certificados de confianza reconocidos // por Viafirma. // estos certificados son los marcados con el prefijo viafirma_ for (TrustAnchor trustAnchor : certificadosConfianza) { // TODO establecer un sistema de cache eficiente // TODO recuperar solo las crls del certificado en uso. listaCRLsCertificadosAlmacenados .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert())); // para cada certificado. } // aado al listado todas las crls del certificado actual. EJ // para el caso de // un certificado de FNMT el certificado personal contiene CN = // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509)); // parametros para la creacin del almacen(cache CRLs) CollectionCertStoreParameters params = new CollectionCertStoreParameters( listaCRLsCertificadosAlmacenados); CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME); parametros.addCertStore(almacen); } else { // No se utilizan las CRLs para la comprobacin de la // revocacin. parametros.setRevocationEnabled(false); } // certificados a validar ( solo 1) List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1); certificadosValidar.add(certificadoX509); // genero el listado de certificados a validar CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar); // validacin CertPathValidatorResult resultado = validador.validate(certPath, parametros); if (log.isDebugEnabled()) { if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) { // pintamos el arbol de politicas PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree(); StringBuffer ruta = new StringBuffer( "Certificado vlido: " + certificadoX509.getSubjectDN().getName()); while (node != null) { ruta.append("-->"); ruta.append(node.getValidPolicy()); if (node.getChildren().hasNext()) { node = node.getChildren().next(); } else { node = null; } } log.info("ruta de validacin: " + ruta); } } return CodigoError.OK_CERTIFICADO_VALIDADO; } catch (CertificateException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchProviderException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchAlgorithmException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (InvalidAlgorithmParameterException e) { log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e); return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO; } catch (CRLException e) { log.fatal(CodigoError.ERROR_VALIDACION_CRL, e); return CodigoError.ERROR_VALIDACION_CRL; } catch (CertPathValidatorException e) { // detectamos el tipo de problema if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName()) || e.getMessage().contains("Certificate revocation after") || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) { log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO; } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) { log.warn( "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("no valid CRL found")) { log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("CertPath not found")) { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } else { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } // TODO java.security.cert.CertPathValidatorException: couldn't // validate certificate: // java.security.cert.CertificateNotYetValidException: NotBefore: // Thu Apr 19 19:22:17 CEST 2007 // at // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819) } }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
protected X509Certificate getX509Certificate(RoleDescriptorType md) { byte[] x509CertificateBin = getBinCertificate(md); if (x509CertificateBin == null) return null; try {//from ww w . j a v a2s .co m CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate x509Cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(x509CertificateBin)); return x509Cert; } catch (CertificateException e) { logger.error("Cannot get X509 Certificate " + e.getMessage(), e); } return null; }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private String revokeInternal(User revoker, String serial, String aki, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); }/*from w w w. j a va 2 s .co m*/ if (Utils.isNullOrEmpty(serial)) { throw new IllegalArgumentException("Serial number id required to revoke ceritificate"); } if (Utils.isNullOrEmpty(aki)) { throw new IllegalArgumentException("AKI is required to revoke certificate"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url)); try { setUpSSL(); // build request body RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL); String body = req.toJson(); // send revoke request JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker); logger.debug("revoke done"); if (genCRL) { if (resp.isEmpty()) { throw new RevocationException("Failed to return CRL, revoke response is empty"); } if (resp.isNull("CRL")) { throw new RevocationException("Failed to return CRL"); } return resp.getString("CRL"); } return null; } catch (CertificateException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage()); throw new RevocationException("Error while revoking cert. " + e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); }/*from w w w. j a v a 2s. c o m*/ if (enrollment == null) { throw new InvalidArgumentException("revokee enrollment is not set"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url)); try { setUpSSL(); // get cert from to-be-revoked enrollment BufferedInputStream pem = new BufferedInputStream( new ByteArrayInputStream(enrollment.getCert().getBytes())); CertificateFactory certFactory = CertificateFactory .getInstance(Config.getConfig().getCertificateFormat()); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem); // get its serial number String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray()); // get its aki // 2.5.29.35 : AuthorityKeyIdentifier byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId()); ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue); String aki = DatatypeConverter .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier()); // build request body RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL); String body = req.toJson(); // send revoke request JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker); logger.debug("revoke done"); if (genCRL) { if (resp.isEmpty()) { throw new RevocationException("Failed to return CRL, revoke response is empty"); } if (resp.isNull("CRL")) { throw new RevocationException("Failed to return CRL"); } return resp.getString("CRL"); } return null; } catch (CertificateException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage()); throw new RevocationException("Error while revoking cert. " + e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }
From source file:org.ejbca.util.CertTools.java
/** * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging. * * @param cert Certificate// w w w . j av a2 s . c o m * * @return String with cvc or asn.1 dump. */ public static String dumpCertificateAsString(final Certificate cert) { String ret = null; if (cert instanceof X509Certificate) { try { final Certificate c = getCertfromByteArray(cert.getEncoded()); ret = c.toString(); // ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded())); // DERObject obj = ais.readObject(); // ret = ASN1Dump.dumpAsString(obj); } catch (CertificateException e) { ret = e.getMessage(); } } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; final CVCObject obj = cvccert.getCVCertificate(); ret = obj.getAsText(""); } else { throw new IllegalArgumentException( "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented"); } return ret; }
From source file:org.ejbca.util.CertTools.java
/** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate//from w ww . j a va 2 s .c om * @param which 1 = subjectDN, anything else = issuerDN * * @return String containing the DN. */ private static String getDN(Certificate cert, int which) { /*if (log.isTraceEnabled()) { log.trace(">getDN("+which+")"); }*/ String ret = null; if (cert == null) { return null; } if (cert instanceof X509Certificate) { // cert.getType=X.509 try { CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); //log.debug("Created certificate of class: " + x509cert.getClass().getName()); String dn = null; if (which == 1) { dn = x509cert.getSubjectDN().toString(); } else { dn = x509cert.getIssuerDN().toString(); } ret = stringToBCDNString(dn); } catch (CertificateException ce) { log.info("Could not get DN from X509Certificate. " + ce.getMessage()); log.debug("", ce); return null; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ReferenceField rf = null; if (which == 1) { rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference(); } else { rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference(); } if (rf != null) { // Construct a "fake" DN which can be used in EJBCA // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part String dn = ""; // if (rf.getSequence() != null) { // dn += "SERIALNUMBER="+rf.getSequence(); // } if (rf.getMnemonic() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "CN=" + rf.getMnemonic(); } if (rf.getCountry() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "C=" + rf.getCountry(); } ret = stringToBCDNString(dn); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); return null; } } /*if (log.isTraceEnabled()) { log.trace("<getDN("+which+"):"+dn); }*/ return ret; }