List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java
/** * Checks if a certificate is valid//from www. ja v a 2s.c o m * Does also print a WARN if the certificate is about to expire. * @param signerCert the certificate to be tested * @return true if the certificate is valid */ public static boolean isCertificateValid(X509Certificate signerCert) { try { signerCert.checkValidity(); } catch (CertificateExpiredException e) { m_log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } catch (CertificateNotYetValidException e) { m_log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime(); if (warnBeforeExpirationTime < 1) { return true; } final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime); try { signerCert.checkValidity(warnDate); } catch (CertificateExpiredException e) { m_log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(), signerCert.getIssuerDN(), signerCert.getNotAfter())); } catch (CertificateNotYetValidException e) { throw new Error("This should never happen.", e); } if (!m_log.isDebugEnabled()) { return true; } m_log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: " + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime)); return true; }
From source file:org.cesecore.certificates.ocsp.cache.OcspSigningCache.java
/** @return the CertificateID's based on the provided certificate */ public static List<CertificateID> getCertificateIDFromCertificate(final X509Certificate certificate) { try {// ww w. j av a 2 s .co m if (log.isTraceEnabled()) { log.trace("Building CertificateId's from certificate with subjectDN '" + CertTools.getSubjectDN(certificate) + "'."); } List<CertificateID> ret = new ArrayList<CertificateID>(); ret.add(new JcaCertificateID( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)), certificate, certificate.getSerialNumber())); ret.add(new JcaCertificateID( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), certificate, certificate.getSerialNumber())); return ret; } catch (OCSPException e) { throw new OcspFailureException(e); } catch (CertificateEncodingException e) { throw new OcspFailureException(e); } catch (OperatorCreationException e) { throw new OcspFailureException(e); } }
From source file:ee.ria.xroad.common.util.CryptoUtils.java
/** * Creates a new certificate ID instance (using SHA-1 digest calculator) * for the specified subject and issuer certificates. * @param subject the subject certificate * @param issuer the issuer certificate/*www . j av a 2s . c o m*/ * @return the certificate id * @throws Exception if the certificate if cannot be created */ public static CertificateID createCertId(X509Certificate subject, X509Certificate issuer) throws Exception { return createCertId(subject.getSerialNumber(), issuer); }
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
public static void verifyTimeStampTokenSignature(TimeStampToken timeStampToken) throws XAdESValidationException { try {/*from ww w .j av a 2 s . c o m*/ SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); //X500Principal signerCertIssuer = signerId.getIssuer(); X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded()); CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate tsaCertificate = null; for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { tsaCertificate = x509Certificate; break; } } if (null == tsaCertificate) { throw new XAdESValidationException("TSA certificate not present in TST"); } timeStampToken.validate(tsaCertificate, BouncyCastleProvider.PROVIDER_NAME); } catch (Exception e) { throw new XAdESValidationException(e); } }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura); Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);//from ww w.j a v a2s . c o m final CMSSignedData s = new CMSSignedData(map, assinatura); Collection ss = s.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()); TimeStampToken tok = new TimeStampToken(cmsTS); Store cs = tok.getCertificates(); SignerId signer_id = tok.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { certificate = cert; } } else { if (certificate == null) { certificate = cert; } } } tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); // Nato: falta validar as CRLs do carimbo de tempo if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(), MessageDigest.getInstance("SHA1").digest(si.getSignature()))) { throw new Exception("Carimbo de tempo no confere com o resumo do documento"); } try { validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime()); } catch (Exception e) { throw new Exception("Carimbo de tempo invlido!", e); } return nome; }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) throws CertificateManagementDAOException { try {//from ww w .j a v a2 s . c om if (certificateBytes != null) { java.security.cert.Certificate x509Certificate = (java.security.cert.Certificate) Serializer .deserialize(certificateBytes); if (x509Certificate instanceof X509Certificate) { X509Certificate certificate = (X509Certificate) x509Certificate; certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); certificateResponse.setCertificateserial(certificate.getSerialNumber()); certificateResponse.setIssuer(certificate.getIssuerDN().getName()); certificateResponse.setSubject(certificate.getSubjectDN().getName()); certificateResponse.setCertificateVersion(certificate.getVersion()); } } } catch (ClassNotFoundException | IOException e) { String errorMsg = "Error while during deserialization of the certificate."; throw new CertificateManagementDAOException(errorMsg, e); } }
From source file:ru.codeinside.gws.crypto.cryptopro.SunPkcs7.java
public static Signature fromPkcs7(final byte[] bytes) { final PKCS7 pkcs7; try {//from w w w . j a v a 2 s . co m pkcs7 = new PKCS7(bytes); } catch (ParsingException e) { log.info("fail parse pkcs7: ", e); return new Signature(null, null, null, false); } final AlgorithmId digestAlgorithmId = new AlgorithmId(GOST3411); final AlgorithmId signAlgorithmId = new AlgorithmId(GOST3410); final AlgorithmId[] digestAlgorithmIds = pkcs7.getDigestAlgorithmIds(); if (digestAlgorithmIds == null || digestAlgorithmIds.length == 0) { log.info("no digestAlgorithm in pkcs7"); } else if (!digestAlgorithmIds[0].equals(digestAlgorithmId)) { log.info("no GOST3411 in pkcs7"); } else { final X509Certificate[] certificates = pkcs7.getCertificates(); if (certificates == null || certificates.length == 0) { log.info("no certificate in pkcs7"); } else { final X509Certificate certificate = certificates[0]; final SignerInfo[] signerInfos = pkcs7.getSignerInfos(); if (signerInfos == null || signerInfos.length == 0) { log.info("no signerInfos in pkcs7"); } else { final SignerInfo signerInfo = signerInfos[0]; if (!signerInfo.getIssuerName() .equals(X500Name.asX500Name(certificate.getIssuerX500Principal()))) { log.info("invalid issuerX500Principal in pkcs7"); } else if (!signerInfo.getDigestAlgorithmId().equals(digestAlgorithmId)) { log.info("no GOST3411 in pkcs7"); } else if (!signerInfo.getDigestEncryptionAlgorithmId().equals(signAlgorithmId)) { log.info("no GOST3410 in pkcs7"); } else if (!signerInfo.getCertificateSerialNumber().equals(certificate.getSerialNumber())) { log.info("invalid certificate serial number in pkcs7"); } else { return new Signature(certificate, null, signerInfo.getEncryptedDigest(), true); } } } } return new Signature(null, null, null, false); }
From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java
/** * Validate the user certificate/*from ww w. j a va2 s . c o m*/ * * @param userName name of the user * @param certificateBytes x509 certificate * @return boolean status of the action * @throws AuthenticationFailedException */ public static boolean validateCertificate(String userName, AuthenticationContext authenticationContext, byte[] certificateBytes, boolean isSelfRegistrationEnable) throws AuthenticationFailedException { X509Certificate x509Certificate; try { CertificateFactory cf = CertificateFactory.getInstance("X509"); x509Certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes)); if (isSelfRegistrationEnable && isCertificateExist(userName) && !isUserCertificateValid(userName, x509Certificate)) { return false; } else if (!isSelfRegistrationEnable && !isUserExists(userName, authenticationContext)) { return false; } if (isCertificateRevoked(x509Certificate)) { if (log.isDebugEnabled()) { log.debug("X509 certificate with serial num: " + x509Certificate.getSerialNumber() + " is revoked"); } if (isSelfRegistrationEnable) { deleteUserCertificate(userName, x509Certificate); } return false; } else if (isSelfRegistrationEnable && !isCertificateExist(userName)) { addUserCertificate(userName, x509Certificate); } } catch (CertificateException e) { throw new AuthenticationFailedException("Error while retrieving certificate ", e); } catch (CertificateValidationException e) { throw new AuthenticationFailedException("Error while validating client certificate with serial num: ", e); } catch (UserStoreException e) { throw new AuthenticationFailedException("Cannot find the user realm for the username: " + userName, e); } return true; }
From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java
/** * Get the information from the certificate to allow it to be displayed in human readable form. * //from w ww .j av a2 s .c o m * @param keyEntry the DSSPrivateKeyEntry * @return the CertificateDisplayName */ public static CertificateDisplayDetails getDisplayDetails(DSSPrivateKeyEntry keyEntry, CardProfile cp) { final X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); String subjectDN = cert.getSubjectDN().getName(); Map<String, String> parts = parseLdapName(subjectDN); if (parts.get("CN") != null) { subjectDN = parts.get("CN"); } String issuerDN = cert.getIssuerX500Principal() == null ? "" : cert.getIssuerX500Principal().getName(); parts = parseLdapName(issuerDN); String issuerCountry = parts.get("C") == null ? "" : parts.get("C"); String issuerName = parts.get("CN") == null ? "" : parts.get("CN"); if (parts.get("O") != null) { issuerName += ", " + parts.get("O"); } String serialNumber = formatSerialNumber(cert.getSerialNumber()); CertificateDisplayDetails cdd = new CertificateDisplayDetails(subjectDN, issuerName, issuerCountry, serialNumber, digest(cert), qualified(cert), sscd(cert), cert.getKeyUsage(), cert, cp, extensions(cert)); //check the expiration/start date valid(cdd); cdd.setSummaryInfo(summaryInfo(subjectDN, issuerName, issuerCountry, serialNumber, cdd.getStartDate(), cdd.getExpirationDate())); return cdd; }
From source file:org.taverna.server.master.utils.X500Utils.java
/** * Get the serial number from a certificate as a hex string. * /*from www.j a v a2 s .co m*/ * @param cert * The certificate to extract from. * @return A hex string, in upper-case. */ public String getSerial(X509Certificate cert) { return new BigInteger(1, cert.getSerialNumber().toByteArray()).toString(16).toUpperCase(); }