use of org.bouncycastle.operator.OperatorCreationException in project signer by demoiselle.
the class RequestSigner method signRequest.
/**
* Signs a time stamp request
*
* @param privateKey private key to sign with
* @param certificates certificate chain
* @param request request to be signed
* @return The signed request
*/
public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) {
try {
logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
Security.addProvider(new BouncyCastleProvider());
X509Certificate signCert = (X509Certificate) certificates[0];
List<X509Certificate> certList = new ArrayList<>();
certList.add(signCert);
// setup the generator
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
String varAlgorithm = null;
if (algorithm != null && !algorithm.isEmpty()) {
varAlgorithm = algorithm;
} else {
varAlgorithm = "SHA256withRSA";
}
SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert);
generator.addSignerInfoGenerator(signerInfoGenerator);
Store<?> certStore = new JcaCertStore(certList);
generator.addCertificates(certStore);
// Store crlStore = new JcaCRLStore(crlList);
// generator.addCRLs(crlStore);
// Create the signed data object
CMSTypedData data = new CMSProcessableByteArray(request);
CMSSignedData signed = generator.generate(data, true);
return signed.getEncoded();
} catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
logger.info(ex.getMessage());
}
return null;
}
use of org.bouncycastle.operator.OperatorCreationException in project candlepin by candlepin.
the class X509CRLStreamWriter method preScan.
public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator) throws IOException {
if (locked) {
throw new IllegalStateException("Cannot modify a locked stream.");
}
if (preScanned) {
throw new IllegalStateException("preScan has already been run.");
}
X509CRLEntryStream reaperStream = null;
ASN1InputStream asn1In = null;
try {
reaperStream = new X509CRLEntryStream(crlToChange);
if (!reaperStream.hasNext()) {
emptyCrl = true;
preScanned = true;
return this;
}
while (reaperStream.hasNext()) {
CRLEntry entry = reaperStream.next();
if (validator != null && validator.shouldDelete(entry)) {
// Get the serial number
deletedEntries.add(entry.getUserCertificate().getValue());
deletedEntriesLength += entry.getEncoded().length;
}
}
/* At this point, crlToChange is at the point where the crlExtensions would
* be. RFC 5280 says that "Conforming CRL issuers are REQUIRED to include
* the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
* extensions in all CRLs issued.
*/
byte[] oldExtensions = null;
ASN1Primitive o;
asn1In = new ASN1InputStream(crlToChange);
while ((o = asn1In.readObject()) != null) {
if (o instanceof ASN1Sequence) {
// Now we are at the signatureAlgorithm
ASN1Sequence seq = (ASN1Sequence) o;
if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) {
// It's possible an algorithm has already been set using setSigningAlgorithm()
if (signingAlg == null) {
signingAlg = AlgorithmIdentifier.getInstance(seq);
}
try {
// Build the signer
this.signer = createContentSigner(signingAlg, key);
} catch (OperatorCreationException e) {
throw new IOException("Could not create ContentSigner for " + signingAlg.getAlgorithm());
}
}
} else if (o instanceof ASN1BitString) {
oldSigLength = o.getEncoded().length;
} else {
if (oldExtensions != null) {
throw new IllegalStateException("Already read in CRL extensions.");
}
oldExtensions = o.getEncoded();
}
}
if (oldExtensions == null) {
/* v1 CRLs (defined in RFC 1422) don't require extensions but all new
* CRLs should be v2 (defined in RFC 5280). In the extremely unlikely
* event that someone is working with a v1 CRL, we handle it here although
* we print a warning.
*/
preScanned = true;
newExtensions = null;
extensionsDelta = 0;
log.warn("The CRL you are modifying is a version 1 CRL." + " Please investigate moving to a version 2 CRL by adding the CRL Number" + " and Authority Key Identifier extensions.");
return this;
}
newExtensions = updateExtensions(oldExtensions);
// newExtension and oldExtensions have already been converted to DER so any difference
// in the length of the L bytes will be accounted for in the overall difference between
// the length of the two byte arrays.
extensionsDelta = newExtensions.length - oldExtensions.length;
} finally {
if (reaperStream != null) {
reaperStream.close();
}
IOUtils.closeQuietly(asn1In);
}
preScanned = true;
return this;
}
use of org.bouncycastle.operator.OperatorCreationException in project candlepin by candlepin.
the class X509CRLStreamWriter method writeToEmptyCrl.
protected void writeToEmptyCrl(OutputStream out) throws IOException {
ASN1InputStream asn1in = null;
try {
asn1in = new ASN1InputStream(crlIn);
ASN1Sequence certListSeq = (ASN1Sequence) asn1in.readObject();
CertificateList certList = CertificateList.getInstance(certListSeq);
X509CRLHolder oldCrl = new X509CRLHolder(certList);
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
crlBuilder.addCRL(oldCrl);
Date now = new Date();
Date oldNextUpdate = certList.getNextUpdate().getDate();
Date oldThisUpdate = certList.getThisUpdate().getDate();
Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
crlBuilder.setNextUpdate(nextUpdate);
for (Object o : oldCrl.getExtensionOIDs()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
Extension ext = oldCrl.getExtension(oid);
if (oid.equals(Extension.cRLNumber)) {
ASN1OctetString octet = ext.getExtnValue();
ASN1Integer currentNumber = (ASN1Integer) new ASN1InputStream(octet.getOctets()).readObject();
ASN1Integer nextNumber = new ASN1Integer(currentNumber.getValue().add(BigInteger.ONE));
crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
} else if (oid.equals(Extension.authorityKeyIdentifier)) {
crlBuilder.addExtension(oid, ext.isCritical(), ext.getParsedValue());
}
}
for (DERSequence entry : newEntries) {
// XXX: This is all a bit messy considering the user already passed in the serial, date
// and reason.
BigInteger serial = ((ASN1Integer) entry.getObjectAt(0)).getValue();
Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
int reason = CRLReason.unspecified;
if (entry.size() == 3) {
Extensions extensions = (Extensions) entry.getObjectAt(2);
Extension reasonExt = extensions.getExtension(Extension.reasonCode);
if (reasonExt != null) {
reason = ((ASN1Enumerated) reasonExt.getParsedValue()).getValue().intValue();
}
}
crlBuilder.addCRLEntry(serial, revokeDate, reason);
}
if (signingAlg == null) {
signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
}
ContentSigner s;
try {
s = createContentSigner(signingAlg, key);
X509CRLHolder newCrl = crlBuilder.build(s);
out.write(newCrl.getEncoded());
} catch (OperatorCreationException e) {
throw new IOException("Could not sign CRL", e);
}
} finally {
IOUtils.closeQuietly(asn1in);
}
}
use of org.bouncycastle.operator.OperatorCreationException in project keystore-explorer by kaikramer.
the class X509CertificateGenerator method generateVersion1.
private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException {
Date notBefore = validityStart == null ? new Date() : validityStart;
Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;
JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey);
try {
ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC").build(privateKey);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(certSigner));
} catch (CertificateException | IllegalStateException | OperatorCreationException ex) {
throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
}
}
use of org.bouncycastle.operator.OperatorCreationException in project vespa by vespa-engine.
the class AthenzPrincipalFilterTest method createSelfSignedCertificate.
// TODO Move this to separate athenz module/bundle
private static X509Certificate createSelfSignedCertificate(AthenzIdentity identity) {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair keyPair = keyGen.genKeyPair();
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate());
X500Name x500Name = new X500Name("CN=" + identity.getFullName());
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, BigInteger.ONE, new Date(), Date.from(Instant.now().plus(Duration.ofDays(30))), x500Name, keyPair.getPublic());
return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
} catch (CertificateException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new RuntimeException(e);
}
}
Aggregations