use of java.util.SimpleTimeZone 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 java.util.SimpleTimeZone in project Bytecoder by mirkosertic.
the class ZoneInfo method inDaylightTime.
/**
* Queries if the specified date is in Daylight Saving Time.
*/
public boolean inDaylightTime(Date date) {
if (date == null) {
throw new NullPointerException();
}
if (transitions == null) {
return false;
}
long utc = date.getTime() - rawOffsetDiff;
int index = getTransitionIndex(utc, UTC_TIME);
// before transitions in the transition table
if (index < 0) {
return false;
}
// the time is in the table range.
if (index < transitions.length) {
return (transitions[index] & DST_MASK) != 0;
}
// beyond the transition table
SimpleTimeZone tz = getLastRule();
if (tz != null) {
return tz.inDaylightTime(date);
}
return false;
}
use of java.util.SimpleTimeZone in project Bytecoder by mirkosertic.
the class SimpleDateFormat method readObject.
/**
* After reading an object from the input stream, the format
* pattern in the object is verified.
*
* @exception InvalidObjectException if the pattern is invalid
*/
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
compiledPattern = compile(pattern);
} catch (Exception e) {
throw new InvalidObjectException("invalid pattern");
}
if (serialVersionOnStream < 1) {
// didn't have defaultCenturyStart field
initializeDefaultCentury();
} else {
// fill in dependent transient field
parseAmbiguousDatesAsAfter(defaultCenturyStart);
}
serialVersionOnStream = currentSerialVersion;
// If the deserialized object has a SimpleTimeZone, try
// to replace it with a ZoneInfo equivalent in order to
// be compatible with the SimpleTimeZone-based
// implementation as much as possible.
TimeZone tz = getTimeZone();
if (tz instanceof SimpleTimeZone) {
String id = tz.getID();
TimeZone zi = TimeZone.getTimeZone(id);
if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
setTimeZone(zi);
}
}
}
use of java.util.SimpleTimeZone in project components by Talend.
the class ApiObjectMapper method makeDateFormat.
public static DateFormat makeDateFormat(String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
dateFormat.setCalendar(cal);
return dateFormat;
}
use of java.util.SimpleTimeZone in project mssql-jdbc by Microsoft.
the class SQLServerBulkCopy method getTemporalObjectFromCSV.
private Object getTemporalObjectFromCSV(Object value, int srcJdbcType, int srcColOrdinal) throws SQLServerException {
// TIME_WITH_TIMEZONE and TIMESTAMP_WITH_TIMEZONE are not supported with encrypted columns.
if (2013 == srcJdbcType) {
MessageFormat form1 = new MessageFormat(SQLServerException.getErrString("R_UnsupportedDataTypeAE"));
Object[] msgArgs1 = { "TIME_WITH_TIMEZONE" };
throw new SQLServerException(this, form1.format(msgArgs1), null, 0, false);
} else if (2014 == srcJdbcType) {
MessageFormat form2 = new MessageFormat(SQLServerException.getErrString("R_UnsupportedDataTypeAE"));
Object[] msgArgs2 = { "TIMESTAMP_WITH_TIMEZONE" };
throw new SQLServerException(this, form2.format(msgArgs2), null, 0, false);
}
String valueStr = null;
String valueStrUntrimmed = null;
if (null != value && value instanceof String) {
valueStrUntrimmed = (String) value;
valueStr = valueStrUntrimmed.trim();
}
// Handle null case
if (null == valueStr) {
switch(srcJdbcType) {
case java.sql.Types.TIMESTAMP:
case java.sql.Types.TIME:
case java.sql.Types.DATE:
case microsoft.sql.Types.DATETIMEOFFSET:
return null;
}
}
// If we are here value is non-null.
Calendar cal;
// Get the temporal values from the formatter
DateTimeFormatter dateTimeFormatter = srcColumnMetadata.get(srcColOrdinal).dateTimeFormatter;
if (null != dateTimeFormatter) {
return getTemporalObjectFromCSVWithFormatter(valueStrUntrimmed, srcJdbcType, srcColOrdinal, dateTimeFormatter);
}
// If we are here that means datetimeformatter is not present. Only default format is supported in this case.
try {
switch(srcJdbcType) {
case java.sql.Types.TIMESTAMP:
// For CSV, value will be of String type.
return Timestamp.valueOf(valueStr);
case java.sql.Types.TIME:
{
String time = connection.baseYear() + "-01-01 " + valueStr;
Timestamp ts = java.sql.Timestamp.valueOf(time);
return ts;
}
case java.sql.Types.DATE:
return java.sql.Date.valueOf(valueStr);
case microsoft.sql.Types.DATETIMEOFFSET:
int endIndx = valueStr.indexOf('-', 0);
int year = Integer.parseInt(valueStr.substring(0, endIndx));
// skip the -
int startIndx = ++endIndx;
endIndx = valueStr.indexOf('-', startIndx);
int month = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip the -
startIndx = ++endIndx;
endIndx = valueStr.indexOf(' ', startIndx);
int day = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip the space
startIndx = ++endIndx;
endIndx = valueStr.indexOf(':', startIndx);
int hour = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip the :
startIndx = ++endIndx;
endIndx = valueStr.indexOf(':', startIndx);
int minute = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip the :
startIndx = ++endIndx;
endIndx = valueStr.indexOf('.', startIndx);
int seconds, offsethour, offsetMinute, totalOffset = 0, fractionalSeconds = 0;
boolean isNegativeOffset = false;
boolean hasTimeZone = false;
int fractionalSecondsLength = 0;
if (// has fractional seconds, has a '.'
-1 != endIndx) {
seconds = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip the .
startIndx = ++endIndx;
endIndx = valueStr.indexOf(' ', startIndx);
if (// has time zone
-1 != endIndx) {
fractionalSeconds = Integer.parseInt(valueStr.substring(startIndx, endIndx));
fractionalSecondsLength = endIndx - startIndx;
hasTimeZone = true;
} else // no timezone
{
fractionalSeconds = Integer.parseInt(valueStr.substring(startIndx));
fractionalSecondsLength = valueStr.length() - startIndx;
}
} else {
endIndx = valueStr.indexOf(' ', startIndx);
if (-1 != endIndx) {
hasTimeZone = true;
seconds = Integer.parseInt(valueStr.substring(startIndx, endIndx));
} else {
seconds = Integer.parseInt(valueStr.substring(startIndx));
// skip the space
++endIndx;
}
}
if (hasTimeZone) {
// skip the space
startIndx = ++endIndx;
if ('+' == valueStr.charAt(startIndx))
// skip +
startIndx++;
else if ('-' == valueStr.charAt(startIndx)) {
isNegativeOffset = true;
// skip -
startIndx++;
}
endIndx = valueStr.indexOf(':', startIndx);
offsethour = Integer.parseInt(valueStr.substring(startIndx, endIndx));
// skip :
startIndx = ++endIndx;
offsetMinute = Integer.parseInt(valueStr.substring(startIndx));
totalOffset = offsethour * 60 + offsetMinute;
if (isNegativeOffset)
totalOffset = -totalOffset;
}
cal = new GregorianCalendar(new SimpleTimeZone(totalOffset * 60 * 1000, ""), Locale.US);
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, seconds);
cal.set(Calendar.DATE, day);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.YEAR, year);
for (int i = 0; i < (9 - fractionalSecondsLength); i++) fractionalSeconds *= 10;
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(fractionalSeconds);
return microsoft.sql.DateTimeOffset.valueOf(ts, totalOffset);
}
} catch (IndexOutOfBoundsException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError"));
Object[] msgArgs = { JDBCType.of(srcJdbcType) };
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
} catch (NumberFormatException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError"));
Object[] msgArgs = { JDBCType.of(srcJdbcType) };
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
} catch (IllegalArgumentException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError"));
Object[] msgArgs = { JDBCType.of(srcJdbcType) };
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
// unreachable code. Need to do to compile from Eclipse.
return value;
}
Aggregations