List of usage examples for org.bouncycastle.cert X509CertificateHolder getSignatureAlgorithm
public AlgorithmIdentifier getSignatureAlgorithm()
From source file:be.apsu.extremon.probes.tsp.TSPProbe.java
License:Open Source License
public void probe_forever() { double start = 0, end = 0; BigInteger requestNonce;/* w w w . ja v a 2 s .c o m*/ byte[] requestHashedMessage = new byte[20]; List<String> comments = new ArrayList<String>(); STATE result = STATE.OK; log("running"); this.running = true; while (this.running) { comments.clear(); this.random.nextBytes(requestHashedMessage); requestNonce = new BigInteger(512, this.random); TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage, requestNonce); end = 0; start = System.currentTimeMillis(); try { TimeStampResponse response = probe(request); switch (response.getStatus()) { case PKIStatus.GRANTED: comments.add("granted"); result = STATE.OK; break; case PKIStatus.GRANTED_WITH_MODS: comments.add("granted with modifications"); result = STATE.WARNING; break; case PKIStatus.REJECTION: comments.add("rejected"); result = STATE.ALERT; break; case PKIStatus.WAITING: comments.add("waiting"); result = STATE.ALERT; break; case PKIStatus.REVOCATION_WARNING: comments.add("revocation warning"); result = STATE.WARNING; break; case PKIStatus.REVOCATION_NOTIFICATION: comments.add("revocation notification"); result = STATE.ALERT; break; default: comments.add("response outside RFC3161"); result = STATE.ALERT; break; } if (response.getStatus() >= 2) comments.add(response.getFailInfo() != null ? response.getFailInfo().getString() : "(missing failinfo)"); if (response.getStatusString() != null) comments.add(response.getStatusString()); end = System.currentTimeMillis(); TimeStampToken timestampToken = response.getTimeStampToken(); timestampToken.validate(this.signerVerifier); comments.add("validated"); AttributeTable table = timestampToken.getSignedAttributes(); TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo(); BigInteger responseNonce = tokenInfo.getNonce(); byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest(); long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000; long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000; put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000); if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) { comments.add("clock skew > 1s"); result = STATE.ALERT; } Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null); for (X509CertificateHolder certificate : certs) { AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm(); if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) { String cleanDn = certificate.getSubject().toString().replace("=", ":"); comments.add("signature cert \"" + cleanDn + "\" signed using " + getName(sigalg.getAlgorithm().getId())); result = STATE.ALERT; } } if (!responseNonce.equals(requestNonce)) { comments.add("nonce modified"); result = STATE.ALERT; } if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) { comments.add("hashed message modified"); result = STATE.ALERT; } if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) { comments.add("signingcertificate missing"); result = STATE.ALERT; } } catch (TSPException tspEx) { comments.add("validation failed"); comments.add("tspexception-" + tspEx.getMessage().toLowerCase()); result = STATE.ALERT; } catch (IOException iox) { comments.add("unable to obtain response"); comments.add("ioexception-" + iox.getMessage().toLowerCase()); result = STATE.ALERT; } catch (Exception ex) { comments.add("unhandled exception"); result = STATE.ALERT; } finally { if (end == 0) end = System.currentTimeMillis(); } put(RESULT_SUFFIX, result); put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|")); put("responsetime", (end - start)); try { Thread.sleep(this.delay); } catch (InterruptedException ex) { log("interrupted"); } } }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
License:Open Source License
@Override public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy) throws TrustLinkerResultException, Exception { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return TrustLinkerResult.UNDECIDED; }/*from w ww . j a v a 2 s .co m*/ LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate, validationDate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return TrustLinkerResult.UNDECIDED; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return TrustLinkerResult.UNDECIDED; } Object responseObject = ocspResp.getResponseObject(); BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts(); for (X509CertificateHolder responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubject()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer()); } algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate); if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the issuing * CA itself. */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey()); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return TrustLinkerResult.UNDECIDED; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509CertificateHolder ocspResponderCertificate = responseCertificates[0]; ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return TrustLinkerResult.UNDECIDED; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature algorithm algorithmPolicy.checkSignatureAlgorithm( ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate); X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { // so the OCSP certificate chain only contains a single // entry LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly signed * by the CA. */ issuingCaCertificate = certificate; } else { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); issuingCaCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded())); /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return TrustLinkerResult.UNDECIDED; } } // check certificate signature algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate); PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded())); LOG.debug("OCSP Responder public key fingerprint: " + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded())); publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate, validationDate, revocationData, algorithmPolicy); if (null == x509OcspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return TrustLinkerResult.UNDECIDED; } List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage(); if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return TrustLinkerResult.UNDECIDED; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return TrustLinkerResult.UNDECIDED; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); // and the CA certificate is already trusted at this point } } DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber()); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } DateTime thisUpdate = new DateTime(singleResp.getThisUpdate()); DateTime nextUpdate; if (null != singleResp.getNextUpdate()) { nextUpdate = new DateTime(singleResp.getNextUpdate()); } else { LOG.debug("no OCSP nextUpdate"); nextUpdate = thisUpdate; } LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("(OCSP) nextUpdate: " + nextUpdate); DateTime beginValidity = thisUpdate.minus(this.freshnessInterval); DateTime endValidity = nextUpdate.plus(this.freshnessInterval); DateTime validationDateTime = new DateTime(validationDate); if (validationDateTime.isBefore(beginValidity)) { LOG.warn("OCSP response not yet valid"); continue; } if (validationDateTime.isAfter(endValidity)) { LOG.warn("OCSP response expired"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp, ocspUri); return TrustLinkerResult.TRUSTED; } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp, ocspUri); throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return TrustLinkerResult.UNDECIDED; }
From source file:dorkbox.util.crypto.CryptoX509.java
License:Apache License
/** * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file) * signature of the .SF file./*from w w w .j av a 2 s . c o m*/ * * It contains the hash of the data, and the verification signature. */ public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder, AsymmetricKeyParameter privateKey) { try { CMSTypedData content = new CMSProcessableByteArray(signatureSourceData); ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId()); ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm(); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes) BcContentSignerBuilder contentSignerBuilder; AlgorithmIdentifier digEncryptionAlgorithm; if (privateKey instanceof ECPrivateKeyParameters) { contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1 // DSA hashID } else if (privateKey instanceof DSAPrivateKeyParameters) { contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1 // DSA hashID } else if (privateKey instanceof RSAPrivateCrtKeyParameters) { contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID } else { throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported."); } ContentSigner hashSigner = contentSignerBuilder.build(privateKey); OutputStream outputStream = hashSigner.getOutputStream(); outputStream.write(signatureSourceData, 0, signatureSourceData.length); outputStream.flush(); byte[] sigBytes = hashSigner.getSignature(); SignerIdentifier sigId = new SignerIdentifier( new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure())); SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm, new DEROctetString(sigBytes), (ASN1Set) null); digestAlgs.add(inf.getDigestAlgorithm()); signerInfos.add(inf); ASN1EncodableVector certs = new ASN1EncodableVector(); certs.add(x509CertificateHolder.toASN1Structure()); ContentInfo encInfo = new ContentInfo(contentTypeOID, null); SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd); CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo); return cmsSignedData2.getEncoded(); } catch (Throwable t) { logger.error("Error signing data.", t); throw new RuntimeException("Error trying to sign data. " + t.getMessage()); } }