use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project poi by apache.
the class PkiTestUtils method createOcspResp.
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
// request
//create a nonce to avoid replay attack
BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
Extensions exts = new Extensions(ext);
OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
ocspReqBuilder.addRequest(certId);
ocspReqBuilder.setRequestExtensions(exts);
OCSPReq ocspReq = ocspReqBuilder.build();
SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
basicOCSPRespBuilder.setResponseExtensions(exts);
// request processing
Req[] requestList = ocspReq.getRequestList();
for (Req ocspRequest : requestList) {
CertificateID certificateID = ocspRequest.getCertID();
CertificateStatus certificateStatus = CertificateStatus.GOOD;
if (revoked) {
certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
}
basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
}
// basic response generation
X509CertificateHolder[] chain = null;
if (!ocspResponderCertificate.equals(issuerCertificate)) {
// TODO: HorribleProxy can't convert array input params yet
chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
}
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
return ocspResp;
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project wso2-synapse by wso2.
the class OCSPVerifierTest method testOCSPVerifier.
/**
* A fake certificate signed by a fake CA is made as the revoked certificate. The created OCSP response to the
* OCSP request will say that that the fake peer certificate is revoked. the SingleResp derived from the OCSP
* response will be put the the cache against the serial number of the fake peer certificate. Since the SingleResp
* which corresponds to the revokedSerialNumber is in the cache, there will NOT be a call to a remote OCSP server.
* Note that the serviceUrl passed to cache.setCacheValue(..) is null since it is not needed.
*
* @throws Exception
*/
public void testOCSPVerifier() throws Exception {
// Add BouncyCastle as Security Provider.
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Utils utils = new Utils();
// Create fake CA certificate.
KeyPair caKeyPair = utils.generateRSAKeyPair();
X509Certificate caCert = utils.generateFakeRootCert(caKeyPair);
// Create fake peer certificate signed by the fake CA private key. This will be a revoked certificate.
KeyPair peerKeyPair = utils.generateRSAKeyPair();
BigInteger revokedSerialNumber = BigInteger.valueOf(111);
X509Certificate revokedCertificate = generateFakePeerCert(revokedSerialNumber, peerKeyPair.getPublic(), caKeyPair.getPrivate(), caCert);
// Create OCSP request to check if certificate with "serialNumber == revokedSerialNumber" is revoked.
OCSPReq request = getOCSPRequest(caCert, revokedSerialNumber);
// Create OCSP response saying that certificate with given serialNumber is revoked.
// CertificateID revokedID = new CertificateID(CertificateID.HASH_SHA1, caCert, revokedSerialNumber);
byte[] issuerCertEnc = caCert.getEncoded();
X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();
// 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
CertificateID revokedID = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, revokedSerialNumber);
OCSPResp response = generateOCSPResponse(request, certificateHolder, caKeyPair.getPrivate(), caKeyPair.getPublic(), revokedID);
SingleResp singleResp = ((BasicOCSPResp) response.getResponseObject()).getResponses()[0];
OCSPCache cache = OCSPCache.getCache();
cache.init(5, 5);
cache.setCacheValue(revokedSerialNumber, singleResp, request, null);
OCSPVerifier ocspVerifier = new OCSPVerifier(cache);
RevocationStatus status = ocspVerifier.checkRevocationStatus(revokedCertificate, caCert);
// the cache will have the SingleResponse derived from the OCSP response and it will be checked to see if the
// fake certificate is revoked. So the status should be REVOKED.
assertTrue(status == RevocationStatus.REVOKED);
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project pdfbox by apache.
the class CreateSignatureBase method sign.
/**
* SignatureInterface implementation.
*
* This method will be called from inside of the pdfbox and create the PKCS #7 signature.
* The given InputStream contains the bytes that are given by the byte range.
*
* This method is for internal use only.
*
* Use your favorite cryptographic library to implement PKCS #7 signature creation.
*
* @throws IOException
*/
@Override
public byte[] sign(InputStream content) throws IOException {
// cannot be done private (interface)
try {
List<Certificate> certList = new ArrayList<>();
certList.addAll(Arrays.asList(certificateChain));
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(certificateChain[0].getEncoded());
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
gen.addCertificates(certs);
CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
CMSSignedData signedData = gen.generate(msg, false);
if (tsaUrl != null && tsaUrl.length() > 0) {
ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
return signedData.getEncoded();
} catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
throw new IOException(e);
}
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project keystore-explorer by kaikramer.
the class JarSigner method createSignatureBlock.
private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
try {
List<X509Certificate> certList = new ArrayList<>();
Collections.addAll(certList, certificateChain);
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
if (provider != null) {
csb.setProvider(provider);
}
JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
// remove cmsAlgorithmProtect for compatibility reasons
SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {
@Override
public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
AttributeTable ret = sAttrGen.getAttributes(parameters);
return ret.remove(CMSAttributes.cmsAlgorithmProtect);
}
}, sigGen.getUnsignedAttributeTableGenerator());
CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
dataGen.addSignerInfoGenerator(sigGen);
dataGen.addCertificates(new JcaCertStore(certList));
CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
// now let TSA time-stamp the signature
if (tsaUrl != null && !tsaUrl.isEmpty()) {
signedData = addTimestamp(tsaUrl, signedData);
}
return signedData.getEncoded();
} catch (Exception ex) {
throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
}
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project structr by structr.
the class SignedJarBuilder method writeSignatureBlock.
/**
* Write the certificate file with a digital signature.
*/
private void writeSignatureBlock(final JarOutputStream jos, final CMSTypedData data, final X509Certificate publicKey, final PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
final List<X509Certificate> certList = new ArrayList<>();
certList.add(publicKey);
final JcaCertStore certs = new JcaCertStore(certList);
final CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()).build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(sha1Signer, publicKey));
gen.addCertificates(certs);
final CMSSignedData sigData = gen.generate(data, false);
final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
final DEROutputStream dos = new DEROutputStream(jos);
dos.writeObject(asn1.readObject());
}
Aggregations