org.bouncycastle.operator.DigestCalculator Java Examples
The following examples show how to use
org.bouncycastle.operator.DigestCalculator.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OcspRequestBuilder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
/** * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce * and CA's will (should) reject subsequent requests that have the same nonce value. */ public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException { SecureRandom generator = checkNotNull(this.generator, "generator"); DigestCalculator calculator = checkNotNull(this.calculator, "calculator"); X509Certificate certificate = checkNotNull(this.certificate, "certificate"); X509Certificate issuer = checkNotNull(this.issuer, "issuer"); BigInteger serial = certificate.getSerialNumber(); CertificateID certId = new CertificateID(calculator, new X509CertificateHolder(issuer.getEncoded()), serial); OCSPReqBuilder builder = new OCSPReqBuilder(); builder.addRequest(certId); byte[] nonce = new byte[8]; generator.nextBytes(nonce); Extension[] extensions = new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)) }; builder.setRequestExtensions(new Extensions(extensions)); return builder.build(); }
Example #2
Source File: OcspClientBouncyCastle.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException { //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder(); DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build(); DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber); // basic request generation with nonce OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(id); // create details for nonce extension Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded())); gen.setRequestExtensions(new Extensions(new Extension[]{ext})); return gen.build(); }
Example #3
Source File: SFTrustManager.java From snowflake-jdbc with Apache License 2.0 | 6 votes |
/** * Convert cache key to base64 encoded * cert id * * @param ocsp_cache_key Cache key to encode */ private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key) { try { DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash); ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, snumber); return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()); } catch (Exception ex) { LOGGER.debug("Failed to encode cache key to base64 encoded cert id"); } return null; }
Example #4
Source File: SFTrustManager.java From snowflake-jdbc with Apache License 2.0 | 6 votes |
/** * Creates a OCSP Request * * @param pairIssuerSubject a pair of issuer and subject certificates * @return OCSPReq object */ private OCSPReq createRequest( SFPair<Certificate, Certificate> pairIssuerSubject) throws IOException { Certificate issuer = pairIssuerSubject.left; Certificate subject = pairIssuerSubject.right; OCSPReqBuilder gen = new OCSPReqBuilder(); try { DigestCalculator digest = new SHA1DigestCalculator(); X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded()); CertificateID certId = new CertificateID( digest, certHolder, subject.getSerialNumber().getValue()); gen.addRequest(certId); return gen.build(); } catch (OCSPException ex) { throw new IOException("Failed to build a OCSPReq.", ex); } }
Example #5
Source File: SSDManager.java From snowflake-jdbc with Apache License 2.0 | 6 votes |
SFTrustManager.OcspResponseCacheKey getWildCardCertId() { DigestCalculator digest = new SFTrustManager.SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance("0"); ASN1OctetString keyHash = ASN1OctetString.getInstance("0"); ASN1Integer serial_number = ASN1Integer.getInstance(0); CertID cid = new CertID(algo, nameHash, keyHash, serial_number); SFTrustManager.OcspResponseCacheKey keyOcspResp = null; try { keyOcspResp = new SFTrustManager.OcspResponseCacheKey( ASN1OctetString.getInstance("0").getEncoded(), ASN1OctetString.getInstance("0").getEncoded(), ASN1Integer.getInstance(0).getValue()); } catch (Throwable ex) { LOGGER.debug("Could not create wildcard certid as cache key"); keyOcspResp = null; } return keyOcspResp; }
Example #6
Source File: Digester.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
public static DigestCalculator sha1() { Digest digest = new SHA1Digest(); AlgorithmIdentifier algId = new AlgorithmIdentifier( OIWObjectIdentifiers.idSHA1); return new Digester(digest, algId); }
Example #7
Source File: OCSPFuncTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Nonnull public static OCSPReq generateOCSPRequest (final X509Certificate aIssuerCert, final BigInteger aCheckSerialNumber) throws OCSPException { try { final DigestCalculatorProvider aDigestCalculatorProvider = new JcaDigestCalculatorProviderBuilder ().setProvider (PBCProvider.getProvider ()) .build (); final DigestCalculator aDigestCalculator = aDigestCalculatorProvider.get (CertificateID.HASH_SHA1); // CertID structure is used to uniquely identify certificates that are the // subject of an OCSP request or response and has an ASN.1 definition. // CertID structure is defined in RFC 2560 final CertificateID aCertificateID = new JcaCertificateID (aDigestCalculator, aIssuerCert, aCheckSerialNumber); // create details for nonce extension. The nonce extension is used to bind // a request to a response to prevent replay attacks. As the name implies, // the nonce value is something that the client should only use once // within a reasonably small period. final BigInteger aNonce = BigInteger.valueOf (System.nanoTime ()); // to create the request Extension final Extensions aExtensions = new Extensions (new Extension (OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString (aNonce.toByteArray ()))); // basic request generation with nonce final OCSPReqBuilder aBuilder = new OCSPReqBuilder (); aBuilder.addRequest (aCertificateID); // Extension to the whole request aBuilder.setRequestExtensions (aExtensions); return aBuilder.build (); } catch (final OperatorCreationException | CertificateEncodingException ex) { throw new IllegalStateException (ex); } }
Example #8
Source File: DSSRevocationUtils.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
public static DigestCalculator getDigestCalculator(DigestAlgorithm digestAlgorithm) { try { final DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build(); return digestCalculatorProvider.get(new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), DERNull.INSTANCE)); } catch (OperatorCreationException e) { throw new DSSException( String.format("Unable to create a DigestCalculator instance. DigestAlgorithm %s is not supported", digestAlgorithm.name()), e); } }
Example #9
Source File: CustomMessageDigestCalculatorProvider.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@Override public DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier) throws OperatorCreationException { LOG.info("message-digest algorithm is set with {}", messageDigestAlgo); return new DigestCalculator() { @Override public OutputStream getOutputStream() { OutputStream os = new ByteArrayOutputStream(); try { Utils.write(getDigest(), os); } catch (IOException e) { throw new DSSException("Unable to get outputstream", e); } return os; } @Override public byte[] getDigest() { return Utils.fromBase64(messageDigestValueBase64); } @Override public AlgorithmIdentifier getAlgorithmIdentifier() { return new AlgorithmIdentifier(new ASN1ObjectIdentifier(messageDigestAlgo.getOid())); } }; }
Example #10
Source File: PrecomputedDigestCalculatorProvider.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@Override public DigestCalculator get(final AlgorithmIdentifier digestAlgorithmIdentifier) throws OperatorCreationException { ASN1ObjectIdentifier algorithmOid = digestAlgorithmIdentifier.getAlgorithm(); final String digestBase64 = digestDocument.getDigest(DigestAlgorithm.forOID(algorithmOid.getId())); return new DigestCalculator() { @Override public OutputStream getOutputStream() { OutputStream os = new ByteArrayOutputStream(); try { Utils.write(getDigest(), os); } catch (IOException e) { throw new DSSException("Unable to get outputstream", e); } return os; } @Override public byte[] getDigest() { return Utils.fromBase64(digestBase64); } @Override public AlgorithmIdentifier getAlgorithmIdentifier() { return digestAlgorithmIdentifier; } }; }
Example #11
Source File: DeviceCertificateManager.java From enmasse with Apache License 2.0 | 5 votes |
private static AuthorityKeyIdentifier createAuthorityKeyId(final PublicKey publicKey) throws OperatorCreationException { final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); final DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); return new X509ExtensionUtils(digCalc) .createAuthorityKeyIdentifier(publicKeyInfo); }
Example #12
Source File: SFTrustManager.java From snowflake-jdbc with Apache License 2.0 | 5 votes |
/** * Encode OCSP Response Cache to JSON * * @return JSON object */ private static ObjectNode encodeCacheToJSON() { try { ObjectNode out = OBJECT_MAPPER.createObjectNode(); for (Map.Entry<OcspResponseCacheKey, SFPair<Long, String>> elem : OCSP_RESPONSE_CACHE.entrySet()) { OcspResponseCacheKey key = elem.getKey(); SFPair<Long, String> value0 = elem.getValue(); long currentTimeSecond = value0.left; DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(key.keyHash); ASN1Integer serialNumber = new ASN1Integer(key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, serialNumber); ArrayNode vout = OBJECT_MAPPER.createArrayNode(); vout.add(currentTimeSecond); vout.add(value0.right); out.set( Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()), vout); } return out; } catch (IOException ex) { LOGGER.debug("Failed to encode ASN1 object."); } return null; }
Example #13
Source File: Digester.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
public static DigestCalculator sha256() { Digest digest = new SHA256Digest(); // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1 ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier( "2.16.840.1.101.3.4.2.1").intern(); AlgorithmIdentifier algId = new AlgorithmIdentifier(oid); return new Digester(digest, algId); }
Example #14
Source File: DSSRevocationUtilsTest.java From dss with GNU Lesser General Public License v2.1 | 4 votes |
@Test public void getSHA1DigestCalculator() { DigestCalculator digestCalculator = DSSRevocationUtils.getDigestCalculator(DigestAlgorithm.SHA1); assertNotNull(digestCalculator); }
Example #15
Source File: OCSPCertificateVerifier.java From oxAuth with MIT License | 4 votes |
@Override public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) { X509Certificate issuer = issuers.get(0); ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN); try { Principal subjectX500Principal = certificate.getSubjectX500Principal(); String ocspUrl = getOCSPUrl(certificate); if (ocspUrl == null) { log.error("OCSP URL for '" + subjectX500Principal + "' is empty"); return status; } log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'"); DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1); CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber()); // Generate OCSP request OCSPReq ocspReq = generateOCSPRequest(certificateId); // Get OCSP response from server OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq); if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) { log.error("OCSP response is invalid!"); status.setValidity(CertificateValidity.INVALID); return status; } boolean foundResponse = false; BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (!certificateId.equals(responseCertificateId)) { continue; } foundResponse = true; log.debug("OCSP validationDate: " + validationDate); log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate()); log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt()); Object certStatus = singleResp.getCertStatus(); if (certStatus == CertificateStatus.GOOD) { log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'"); status.setValidity(CertificateValidity.VALID); } else { if (singleResp.getCertStatus() instanceof RevokedStatus) { log.warn("OCSP status is revoked for: " + subjectX500Principal); if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) { log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate); status.setValidity(CertificateValidity.VALID); } else { Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime(); log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate); status.setRevocationDate(revocationDate); status.setRevocationObjectIssuingTime(singleResp.getThisUpdate()); status.setValidity(CertificateValidity.REVOKED); } } } } if (!foundResponse) { log.error("There is no matching OCSP response entries"); } } catch (Exception ex) { log.error("OCSP exception: ", ex); } return status; }
Example #16
Source File: CertificateRequest.java From jqm with Apache License 2.0 | 4 votes |
private void generateX509() throws Exception { SecureRandom random = new SecureRandom(); X500Name dnName = new X500Name(Subject); Calendar endValidity = Calendar.getInstance(); endValidity.add(Calendar.YEAR, validityYear); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); X509v3CertificateBuilder gen = new X509v3CertificateBuilder( authorityCertificate == null ? dnName : authorityCertificate.getSubject(), BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(), endValidity.getTime(), dnName, publicKeyInfo); // Public key ID DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo)); // EKU gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic constraints (is CA?) if (authorityCertificate == null) { gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); } // Key usage gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage)); // Subject Alt names ? // Authority if (authorityCertificate != null) { gen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo())); } // Signer ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER) .build(authorityKey == null ? privateKey : authorityKey); // Go holder = gen.build(signer); }
Example #17
Source File: OcspHandler.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } final byte[] buffy = new byte[16384]; try (InputStream requestStream = exchange.getInputStream()) { requestStream.read(buffy); } final OCSPReq request = new OCSPReq(buffy); final Req[] requested = request.getRequestList(); final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build() .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1)); final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator); if (nonce != null) { responseBuilder.setResponseExtensions(new Extensions(nonce)); } for (final Req req : requested) { final CertificateID certId = req.getCertID(); final BigInteger certificateSerialNumber = certId.getSerialNumber(); responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber)); } final ContentSigner contentSigner = new BcRSAContentSignerBuilder( new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption), new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey); final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL, responseBuilder.build(contentSigner, chain, new Date())); final byte[] responseBytes = response.getEncoded(); final HeaderMap responseHeaders = exchange.getResponseHeaders(); responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response"); final Sender responseSender = exchange.getResponseSender(); responseSender.send(ByteBuffer.wrap(responseBytes)); exchange.endExchange(); }
Example #18
Source File: CertificateUtils.java From keycloak with Apache License 2.0 | 4 votes |
/** * Generates version 3 {@link java.security.cert.X509Certificate}. * * @param keyPair the key pair * @param caPrivateKey the CA private key * @param caCert the CA certificate * @param subject the subject name * * @return the x509 certificate * * @throws Exception the exception */ public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception { try { X500Name subjectDN = new X500Name("CN=" + subject); // Serial Number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt())); // Validity Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3); // SubjectPublicKeyInfo SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic() .getEncoded())); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo); DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); // Subject Key Identifier certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo)); // Authority Key Identifier certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo)); // Key Usage certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); // Extended Key Usage KeyPurposeId[] EKU = new KeyPurposeId[2]; EKU[0] = KeyPurposeId.id_kp_emailProtection; EKU[1] = KeyPurposeId.id_kp_serverAuth; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic Constraints certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); // Content Signer ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey); // Certificate return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); } catch (Exception e) { throw new RuntimeException("Error creating X509v3Certificate.", e); } }
Example #19
Source File: DeviceCertificateManager.java From enmasse with Apache License 2.0 | 3 votes |
private static SubjectKeyIdentifier createSubjectKeyId(final PublicKey publicKey) throws OperatorCreationException { final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); final DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); return new X509ExtensionUtils(digCalc) .createSubjectKeyIdentifier(publicKeyInfo); }
Example #20
Source File: DSSRevocationUtils.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
/** * Returns the {@code CertificateID} for the given certificate and its * issuer's certificate. * * @param cert * {@code CertificateToken} for which the id is created * @param issuerCert * {@code CertificateToken} issuer certificate of the {@code cert} * @param digestAlgorithm * {@code DigestAlgorithm} to be used for CertificateID hash calculation * @return {@code CertificateID} */ public static CertificateID getOCSPCertificateID(final CertificateToken cert, final CertificateToken issuerCert, final DigestAlgorithm digestAlgorithm) { try { final BigInteger serialNumber = cert.getSerialNumber(); final DigestCalculator digestCalculator = getDigestCalculator(digestAlgorithm); final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(issuerCert); return new CertificateID(digestCalculator, x509CertificateHolder, serialNumber); } catch (OCSPException e) { throw new DSSException("Unable to create CertificateID", e); } }