use of org.bouncycastle.asn1.x509.Time in project xipki by xipki.
the class X509Ca method createGrantedCertTemplate.
private GrantedCertTemplate createGrantedCertTemplate(CertTemplateData certTemplate, RequestorInfo requestor, boolean keyUpdate) throws OperationException {
ParamUtil.requireNonNull("certTemplate", certTemplate);
if (caInfo.getRevocationInfo() != null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked");
}
IdentifiedX509Certprofile certprofile = getX509Certprofile(certTemplate.getCertprofileName());
if (certprofile == null) {
throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certTemplate.getCertprofileName());
}
ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms());
if (signer == null) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
}
final NameId certprofileIdent = certprofile.getIdent();
if (certprofile.getVersion() != X509CertVersion.v3) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile.getVersion());
}
if (certprofile.isOnlyForRa()) {
if (requestor == null || !requestor.isRa()) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "profile " + certprofileIdent + " not applied to non-RA");
}
}
X500Name requestedSubject = removeEmptyRdns(certTemplate.getSubject());
if (!certprofile.isSerialNumberInReqPermitted()) {
RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN);
if (rdns != null && rdns.length > 0) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted");
}
}
Date now = new Date();
Date reqNotBefore;
if (certTemplate.getNotBefore() != null && certTemplate.getNotBefore().after(now)) {
reqNotBefore = certTemplate.getNotBefore();
} else {
reqNotBefore = now;
}
Date grantedNotBefore = certprofile.getNotBefore(reqNotBefore);
// notBefore in the past is not permitted
if (grantedNotBefore.before(now)) {
grantedNotBefore = now;
}
if (certprofile.hasMidnightNotBefore()) {
grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
}
if (grantedNotBefore.before(caInfo.getNotBefore())) {
grantedNotBefore = caInfo.getNotBefore();
if (certprofile.hasMidnightNotBefore()) {
grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
}
}
long time = caInfo.getNoNewCertificateAfter();
if (grantedNotBefore.getTime() > time) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(time));
}
SubjectPublicKeyInfo grantedPublicKeyInfo;
try {
grantedPublicKeyInfo = X509Util.toRfc3279Style(certTemplate.getPublicKeyInfo());
} catch (InvalidKeySpecException ex) {
LogUtil.warn(LOG, ex, "invalid SubjectPublicKeyInfo");
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo");
}
// public key
try {
grantedPublicKeyInfo = certprofile.checkPublicKey(grantedPublicKeyInfo);
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
// CHECK weak public key, like RSA key (ROCA)
if (grantedPublicKeyInfo.getAlgorithm().getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
try {
ASN1Sequence seq = ASN1Sequence.getInstance(grantedPublicKeyInfo.getPublicKeyData().getOctets());
if (seq.size() != 2) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
}
BigInteger modulus = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
if (RSABrokenKey.isAffected(modulus)) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "RSA public key is too weak");
}
} catch (IllegalArgumentException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
}
}
Date gsmckFirstNotBefore = null;
if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
gsmckFirstNotBefore = grantedNotBefore;
RDN[] cnRdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN);
if (cnRdns != null && cnRdns.length > 0) {
String requestedCn = X509Util.rdnValueToString(cnRdns[0].getFirst().getValue());
Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCommonName(requestedCn, certprofileIdent);
if (gsmckFirstNotBeforeInSecond != null) {
gsmckFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND);
}
// append the commonName with '-' + yyyyMMdd
SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");
dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
String yyyyMMdd = dateF.format(gsmckFirstNotBefore);
String suffix = "-" + yyyyMMdd;
// append the -yyyyMMdd to the commonName
RDN[] rdns = requestedSubject.getRDNs();
for (int i = 0; i < rdns.length; i++) {
if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) {
rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCn + suffix));
}
}
requestedSubject = new X500Name(rdns);
}
// end if
}
// end if
// subject
SubjectInfo subjectInfo;
try {
subjectInfo = certprofile.getSubject(requestedSubject);
} catch (CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileIdent);
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
X500Name grantedSubject = subjectInfo.getGrantedSubject();
// make sure that empty subject is not permitted
ASN1ObjectIdentifier[] attrTypes = grantedSubject.getAttributeTypes();
if (attrTypes == null || attrTypes.length == 0) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "empty subject is not permitted");
}
// make sure that the grantedSubject does not equal the CA's subject
if (X509Util.canonicalizName(grantedSubject).equals(caInfo.getPublicCaInfo().getC14nSubject())) {
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed");
}
boolean duplicateKeyPermitted = caInfo.isDuplicateKeyPermitted();
if (duplicateKeyPermitted && !certprofile.isDuplicateKeyPermitted()) {
duplicateKeyPermitted = false;
}
byte[] subjectPublicKeyData = grantedPublicKeyInfo.getPublicKeyData().getBytes();
long fpPublicKey = FpIdCalculator.hash(subjectPublicKeyData);
if (keyUpdate) {
CertStatus certStatus = certstore.getCertStatusForSubject(caIdent, grantedSubject);
if (certStatus == CertStatus.REVOKED) {
throw new OperationException(ErrorCode.CERT_REVOKED);
} else if (certStatus == CertStatus.UNKNOWN) {
throw new OperationException(ErrorCode.UNKNOWN_CERT);
}
} else {
if (!duplicateKeyPermitted) {
if (certstore.isCertForKeyIssued(caIdent, fpPublicKey)) {
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued");
}
}
// duplicateSubject check will be processed later
}
// end if(keyUpdate)
StringBuilder msgBuilder = new StringBuilder();
if (subjectInfo.getWarning() != null) {
msgBuilder.append(", ").append(subjectInfo.getWarning());
}
CertValidity validity = certprofile.getValidity();
if (validity == null) {
validity = caInfo.getMaxValidity();
} else if (validity.compareTo(caInfo.getMaxValidity()) > 0) {
validity = caInfo.getMaxValidity();
}
Date maxNotAfter = validity.add(grantedNotBefore);
if (maxNotAfter.getTime() > MAX_CERT_TIME_MS) {
maxNotAfter = new Date(MAX_CERT_TIME_MS);
}
// CHECKSTYLE:SKIP
Date origMaxNotAfter = maxNotAfter;
if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
String str = certprofile.setParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME);
long maxLifetimeInDays = Long.parseLong(str);
Date maxLifetime = new Date(gsmckFirstNotBefore.getTime() + maxLifetimeInDays * DAY_IN_MS - MS_PER_SECOND);
if (maxNotAfter.after(maxLifetime)) {
maxNotAfter = maxLifetime;
}
}
Date grantedNotAfter = certTemplate.getNotAfter();
if (grantedNotAfter != null) {
if (grantedNotAfter.after(maxNotAfter)) {
grantedNotAfter = maxNotAfter;
msgBuilder.append(", notAfter modified");
}
} else {
grantedNotAfter = maxNotAfter;
}
if (grantedNotAfter.after(caInfo.getNotAfter())) {
ValidityMode mode = caInfo.getValidityMode();
if (mode == ValidityMode.CUTOFF) {
grantedNotAfter = caInfo.getNotAfter();
} else if (mode == ValidityMode.STRICT) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted");
} else if (mode == ValidityMode.LAX) {
// permitted
} else {
throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode);
}
// end if (mode)
}
if (certprofile.hasMidnightNotBefore() && !maxNotAfter.equals(origMaxNotAfter)) {
Calendar cal = Calendar.getInstance(certprofile.getTimezone());
cal.setTime(new Date(grantedNotAfter.getTime() - DAY_IN_MS));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 0);
grantedNotAfter = cal.getTime();
}
String warning = null;
if (msgBuilder.length() > 2) {
warning = msgBuilder.substring(2);
}
GrantedCertTemplate gct = new GrantedCertTemplate(certTemplate.getExtensions(), certprofile, grantedNotBefore, grantedNotAfter, requestedSubject, grantedPublicKeyInfo, fpPublicKey, subjectPublicKeyData, signer, warning);
gct.setGrantedSubject(grantedSubject);
return gct;
}
use of org.bouncycastle.asn1.x509.Time in project xipki by xipki.
the class ExtensionsChecker method checkExtensionPrivateKeyUsagePeriod.
// method checkExtensionValidityModel
private void checkExtensionPrivateKeyUsagePeriod(StringBuilder failureMsg, byte[] extensionValue, Date certNotBefore, Date certNotAfter) {
ASN1GeneralizedTime notBefore = new ASN1GeneralizedTime(certNotBefore);
Date dateNotAfter;
CertValidity privateKeyUsagePeriod = certProfile.getPrivateKeyUsagePeriod();
if (privateKeyUsagePeriod == null) {
dateNotAfter = certNotAfter;
} else {
dateNotAfter = privateKeyUsagePeriod.add(certNotBefore);
if (dateNotAfter.after(certNotAfter)) {
dateNotAfter = certNotAfter;
}
}
ASN1GeneralizedTime notAfter = new ASN1GeneralizedTime(dateNotAfter);
org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod extValue = org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod.getInstance(extensionValue);
ASN1GeneralizedTime time = extValue.getNotBefore();
if (time == null) {
failureMsg.append("notBefore is absent but expected present; ");
} else if (!time.equals(notBefore)) {
addViolation(failureMsg, "notBefore", time.getTimeString(), notBefore.getTimeString());
}
time = extValue.getNotAfter();
if (time == null) {
failureMsg.append("notAfter is absent but expected present; ");
} else if (!time.equals(notAfter)) {
addViolation(failureMsg, "notAfter", time.getTimeString(), notAfter.getTimeString());
}
}
use of org.bouncycastle.asn1.x509.Time in project candlepin by candlepin.
the class X509CRLStreamWriter method writeNewTime.
/**
* Write a UTCTime or GeneralizedTime to an output stream.
*
* @param out
* @param newTime
* @param originalLength
* @throws IOException
*/
protected void writeNewTime(OutputStream out, ASN1Object newTime, int originalLength) throws IOException {
byte[] newEncodedTime = newTime.getEncoded();
InputStream timeIn = null;
try {
timeIn = new ByteArrayInputStream(newEncodedTime);
int newTag = readTag(timeIn, null);
readTagNumber(timeIn, newTag, null);
int newLength = readLength(timeIn, null);
/* If the length changes, it's going to create a discrepancy with the length
* reported in the TBSCertList sequence. The length could change with the addition
* or removal of time zone information for example. */
if (newLength != originalLength) {
throw new IllegalStateException("Length of generated time does not match " + "the original length. DER corruption would result.");
}
} finally {
IOUtils.closeQuietly(timeIn);
}
writeBytes(out, newEncodedTime);
}
use of org.bouncycastle.asn1.x509.Time in project candlepin by candlepin.
the class X509CRLStreamWriter method add.
/**
* Create an entry to be added to the CRL.
*
* @param serial
* @param date
* @param reason
* @throws IOException if an entry fails to generate
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void add(BigInteger serial, Date date, int reason) throws IOException {
if (locked) {
throw new IllegalStateException("Cannot add to a locked stream.");
}
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(serial));
v.add(new Time(date));
CRLReason crlReason = CRLReason.getInstance(new ASN1Enumerated(reason));
ExtensionsGenerator generator = new ExtensionsGenerator();
generator.addExtension(Extension.reasonCode, false, crlReason);
v.add(generator.generate());
newEntries.add(new DERSequence(v));
}
use of org.bouncycastle.asn1.x509.Time in project jruby-openssl by jruby.
the class ASN1 method createASN1.
public static void createASN1(final Ruby runtime, final RubyModule OpenSSL) {
final RubyModule ASN1 = OpenSSL.defineModuleUnder("ASN1");
final RubyClass OpenSSLError = OpenSSL.getClass("OpenSSLError");
ASN1.defineClassUnder("ASN1Error", OpenSSLError, OpenSSLError.getAllocator());
ASN1.defineAnnotatedMethods(ASN1.class);
final RubyArray UNIVERSAL_TAG_NAME = runtime.newArray(ASN1_INFO.length);
for (int i = 0; i < ASN1_INFO.length; i++) {
final String name = (String) ASN1_INFO[i][0];
if (name.charAt(0) != '[') {
UNIVERSAL_TAG_NAME.append(runtime.newString(name));
ASN1.setConstant(name, runtime.newFixnum(i));
} else {
UNIVERSAL_TAG_NAME.append(runtime.getNil());
}
}
ASN1.setConstant("UNIVERSAL_TAG_NAME", UNIVERSAL_TAG_NAME);
final ThreadContext context = runtime.getCurrentContext();
final ObjectAllocator asn1DataAllocator = ASN1Data.ALLOCATOR;
RubyClass _ASN1Data = ASN1.defineClassUnder("ASN1Data", runtime.getObject(), asn1DataAllocator);
_ASN1Data.addReadWriteAttribute(context, "value");
_ASN1Data.addReadWriteAttribute(context, "tag");
_ASN1Data.addReadWriteAttribute(context, "tag_class");
_ASN1Data.defineAnnotatedMethods(ASN1Data.class);
final ObjectAllocator primitiveAllocator = Primitive.ALLOCATOR;
RubyClass Primitive = ASN1.defineClassUnder("Primitive", _ASN1Data, primitiveAllocator);
Primitive.addReadWriteAttribute(context, "tagging");
Primitive.addReadAttribute(context, "infinite_length");
Primitive.defineAnnotatedMethods(Primitive.class);
final ObjectAllocator constructiveAllocator = Constructive.ALLOCATOR;
RubyClass Constructive = ASN1.defineClassUnder("Constructive", _ASN1Data, constructiveAllocator);
Constructive.includeModule(runtime.getModule("Enumerable"));
Constructive.addReadWriteAttribute(context, "tagging");
Constructive.addReadWriteAttribute(context, "infinite_length");
Constructive.defineAnnotatedMethods(Constructive.class);
// OpenSSL::ASN1::Boolean <=> value is a Boolean
ASN1.defineClassUnder("Boolean", Primitive, primitiveAllocator);
// OpenSSL::ASN1::Integer <=> value is a Number
ASN1.defineClassUnder("Integer", Primitive, primitiveAllocator);
// OpenSSL::ASN1::Null <=> value is always nil
ASN1.defineClassUnder("Null", Primitive, primitiveAllocator);
// OpenSSL::ASN1::Object <=> value is a String
ASN1.defineClassUnder("Object", Primitive, primitiveAllocator);
// OpenSSL::ASN1::Enumerated <=> value is a Number
ASN1.defineClassUnder("Enumerated", Primitive, primitiveAllocator);
RubyClass BitString = ASN1.defineClassUnder("BitString", Primitive, primitiveAllocator);
BitString.addReadWriteAttribute(context, "unused_bits");
ASN1.defineClassUnder("OctetString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("UTF8String", Primitive, primitiveAllocator);
ASN1.defineClassUnder("NumericString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("PrintableString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("T61String", Primitive, primitiveAllocator);
ASN1.defineClassUnder("VideotexString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("IA5String", Primitive, primitiveAllocator);
ASN1.defineClassUnder("GraphicString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("ISO64String", Primitive, primitiveAllocator);
ASN1.defineClassUnder("GeneralString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("UniversalString", Primitive, primitiveAllocator);
ASN1.defineClassUnder("BMPString", Primitive, primitiveAllocator);
// OpenSSL::ASN1::UTCTime <=> value is a Time
ASN1.defineClassUnder("UTCTime", Primitive, primitiveAllocator);
// OpenSSL::ASN1::GeneralizedTime <=> value is a Time
ASN1.defineClassUnder("GeneralizedTime", Primitive, primitiveAllocator);
// OpenSSL::ASN1::EndOfContent <=> value is always nil
ASN1.defineClassUnder("EndOfContent", Primitive, primitiveAllocator);
RubyClass ObjectId = ASN1.defineClassUnder("ObjectId", Primitive, primitiveAllocator);
ObjectId.defineAnnotatedMethods(ObjectId.class);
ASN1.defineClassUnder("Sequence", Constructive, Constructive.getAllocator());
ASN1.defineClassUnder("Set", Constructive, Constructive.getAllocator());
}
Aggregations