use of org.bouncycastle.cert.CertIOException in project nifi by apache.
the class CertificateUtils method generateSelfSignedX509Certificate.
/**
* Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
*
* @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for
* @param dn the distinguished name to user for the {@link X509Certificate}
* @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate}
* @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
* @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
* @throws CertificateException if there is an generating the new certificate
*/
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// Sign the certificate
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new CertificateException(e);
}
}
use of org.bouncycastle.cert.CertIOException in project xipki by xipki.
the class ScepUtil method generateSelfsignedCert.
public static X509Certificate generateSelfsignedCert(X500Name subjectDn, SubjectPublicKeyInfo pubKeyInfo, PrivateKey identityKey) throws CertificateException {
requireNonNull("subjectDn", subjectDn);
requireNonNull("pubKeyInfo", pubKeyInfo);
requireNonNull("identityKey", identityKey);
Date notBefore = new Date(System.currentTimeMillis() - 5 * MIN_IN_MS);
Date notAfter = new Date(notBefore.getTime() + 30 * DAY_IN_MS);
X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.ONE, notBefore, notAfter, subjectDn, pubKeyInfo);
X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment);
try {
certGenerator.addExtension(Extension.keyUsage, true, ku);
} catch (CertIOException ex) {
throw new CertificateException("could not generate self-signed certificate: " + ex.getMessage(), ex);
}
String sigAlgorithm = ScepUtil.getSignatureAlgorithm(identityKey, ScepHashAlgo.SHA1);
ContentSigner contentSigner;
try {
contentSigner = new JcaContentSignerBuilder(sigAlgorithm).build(identityKey);
} catch (OperatorCreationException ex) {
throw new CertificateException("error while creating signer", ex);
}
Certificate asn1Cert = certGenerator.build(contentSigner).toASN1Structure();
return toX509Cert(asn1Cert);
}
use of org.bouncycastle.cert.CertIOException in project nifi by apache.
the class CertificateUtils method generateIssuedCertificate.
/**
* Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
*
* @param dn the distinguished name to use
* @param publicKey the public key to issue the certificate to
* @param extensions extensions extracted from the CSR
* @param issuer the issuer's certificate
* @param issuerKeyPair the issuer's keypair
* @param signingAlgorithm the signing algorithm to use
* @param days the number of days it should be valid for
* @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
* @throws CertificateException if there is an error issuing the certificate
*/
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// (3) subjectAlternativeName
if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
}
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new CertificateException(e);
}
}
use of org.bouncycastle.cert.CertIOException in project webofneeds by researchstudio-sat.
the class CertificateService method addToCertBuilderWebIdInfo.
private void addToCertBuilderWebIdInfo(final X509v3CertificateBuilder certBuilder, final String webID) throws CertificateException {
if (webID != null) {
org.bouncycastle.asn1.x509.GeneralName[] genNames = new org.bouncycastle.asn1.x509.GeneralName[1];
genNames[0] = new org.bouncycastle.asn1.x509.GeneralName(org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, webID);
try {
certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, new org.bouncycastle.asn1.x509.GeneralNames(genNames));
} catch (CertIOException e) {
throw new CertificateException("Could not add webID to the certificate" + webID, e);
}
}
}
use of org.bouncycastle.cert.CertIOException in project xipki by xipki.
the class X509Ca method generateCrl0.
private X509CRL generateCrl0(boolean deltaCrl, Date thisUpdate, Date nextUpdate, AuditEvent event, String msgId) throws OperationException {
X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
if (crlSigner == null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed");
}
LOG.info(" START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caIdent, deltaCrl, nextUpdate);
event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL");
if (nextUpdate == null) {
event.addEventData(CaAuditConstants.NAME_nextUpdate, "null");
} else {
event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate));
if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
// less than 10 minutes
throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
}
}
CrlControl crlControl = crlSigner.getCrlControl();
boolean successful = false;
try {
ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner();
CrlControl control = crlSigner.getCrlControl();
boolean directCrl;
X500Name crlIssuer;
if (tmpCrlSigner == null) {
directCrl = true;
crlIssuer = caInfo.getPublicCaInfo().getX500Subject();
} else {
directCrl = false;
crlIssuer = X500Name.getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded());
}
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
if (nextUpdate != null) {
crlBuilder.setNextUpdate(nextUpdate);
}
final int numEntries = 100;
Date notExpireAt;
if (control.isIncludeExpiredCerts()) {
notExpireAt = new Date(0);
} else {
// 10 minutes buffer
notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
}
long startId = 1;
// we have to cache the serial entries to sort them
List<CertRevInfoWithSerial> allRevInfos = new LinkedList<>();
List<CertRevInfoWithSerial> revInfos;
do {
if (deltaCrl) {
revInfos = certstore.getCertsForDeltaCrl(caIdent, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
} else {
revInfos = certstore.getRevokedCerts(caIdent, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
}
allRevInfos.addAll(revInfos);
long maxId = 1;
for (CertRevInfoWithSerial revInfo : revInfos) {
if (revInfo.getId() > maxId) {
maxId = revInfo.getId();
}
}
// end for
startId = maxId + 1;
} while (// end do
revInfos.size() >= numEntries);
if (revInfos != null) {
// free the memory
revInfos.clear();
}
// sort the list by SerialNumber ASC
Collections.sort(allRevInfos);
boolean isFirstCrlEntry = true;
for (CertRevInfoWithSerial revInfo : allRevInfos) {
CrlReason reason = revInfo.getReason();
if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) {
reason = CrlReason.UNSPECIFIED;
}
Date revocationTime = revInfo.getRevocationTime();
Date invalidityTime = revInfo.getInvalidityTime();
switch(crlControl.getInvalidityDateMode()) {
case FORBIDDEN:
invalidityTime = null;
break;
case OPTIONAL:
break;
case REQUIRED:
if (invalidityTime == null) {
invalidityTime = revocationTime;
}
break;
default:
throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode());
}
BigInteger serial = revInfo.getSerial();
LOG.debug("added cert ca={} serial={} to CRL", caIdent, serial);
if (directCrl || !isFirstCrlEntry) {
if (invalidityTime != null) {
crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime);
} else {
crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode());
}
continue;
}
List<Extension> extensions = new ArrayList<>(3);
if (reason != CrlReason.UNSPECIFIED) {
Extension ext = createReasonExtension(reason.getCode());
extensions.add(ext);
}
if (invalidityTime != null) {
Extension ext = createInvalidityDateExtension(invalidityTime);
extensions.add(ext);
}
Extension ext = createCertificateIssuerExtension(caInfo.getPublicCaInfo().getX500Subject());
extensions.add(ext);
crlBuilder.addCRLEntry(serial, revocationTime, new Extensions(extensions.toArray(new Extension[0])));
isFirstCrlEntry = false;
}
// free the memory
allRevInfos.clear();
BigInteger crlNumber = caInfo.nextCrlNumber();
event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber);
boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
boolean onlyCaCerts = crlControl.isOnlyContainsCaCerts();
if (onlyUserCerts && onlyCaCerts) {
throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
}
try {
// AuthorityKeyIdentifier
byte[] akiValues = directCrl ? caInfo.getPublicCaInfo().getSubjectKeyIdentifer() : crlSigner.getSubjectKeyIdentifier();
AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
// add extension CRL Number
crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));
// IssuingDistributionPoint
if (onlyUserCerts || onlyCaCerts || !directCrl) {
IssuingDistributionPoint idp = new IssuingDistributionPoint(// distributionPoint,
(DistributionPointName) null, // onlyContainsUserCerts,
onlyUserCerts, // onlyContainsCACerts,
onlyCaCerts, // onlySomeReasons,
(ReasonFlags) null, // indirectCRL,
!directCrl, // onlyContainsAttributeCerts
false);
crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
}
// freshestCRL
List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris();
if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) {
CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris, caInfo.getPublicCaInfo().getX500Subject(), crlIssuer);
crlBuilder.addExtension(Extension.freshestCRL, false, cdp);
}
} catch (CertIOException ex) {
LogUtil.error(LOG, ex, "crlBuilder.addExtension");
throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
}
addXipkiCertset(crlBuilder, deltaCrl, control, notExpireAt, onlyCaCerts, onlyUserCerts);
ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner;
ConcurrentBagEntrySigner signer0;
try {
signer0 = concurrentSigner.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage());
}
X509CRLHolder crlHolder;
try {
crlHolder = crlBuilder.build(signer0.value());
} finally {
concurrentSigner.requiteSigner(signer0);
}
try {
X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure());
caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1);
caManager.commitNextCrlNo(caIdent, caInfo.getCaEntry().getNextCrlNumber());
publishCrl(crl);
successful = true;
LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caIdent, crlNumber, crl.getThisUpdate());
if (!deltaCrl) {
// clean up the CRL
cleanupCrlsWithoutException(msgId);
}
return crl;
} catch (CRLException | CertificateException ex) {
throw new OperationException(ErrorCode.CRL_FAILURE, ex);
}
} finally {
if (!successful) {
LOG.info(" FAILED generateCrl: ca={}", caIdent);
}
}
}
Aggregations