Path: blob/master/src/java.security.jgss/share/classes/sun/security/krb5/internal/KerberosTime.java
41161 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324/*25*26* (C) Copyright IBM Corp. 1999 All Rights Reserved.27* Copyright 1997 The Open Group Research Institute. All rights reserved.28*/2930package sun.security.krb5.internal;3132import sun.security.krb5.Asn1Exception;33import sun.security.krb5.Config;34import sun.security.krb5.KrbException;35import sun.security.util.DerInputStream;36import sun.security.util.DerOutputStream;37import sun.security.util.DerValue;3839import java.io.IOException;40import java.time.Instant;41import java.util.Calendar;42import java.util.Date;43import java.util.TimeZone;4445/**46* Implements the ASN.1 KerberosTime type. This is an immutable class.47*48* {@code KerberosTime ::= GeneralizedTime} -- with no fractional seconds49*50* The timestamps used in Kerberos are encoded as GeneralizedTimes. A51* KerberosTime value shall not include any fractional portions of the52* seconds. As required by the DER, it further shall not include any53* separators, and it shall specify the UTC time zone (Z).54*55* <p>56* This definition reflects the Network Working Group RFC 412057* specification available at58* <a href="http://www.ietf.org/rfc/rfc4120.txt">59* http://www.ietf.org/rfc/rfc4120.txt</a>.60*61* The implementation also includes the microseconds info so that the62* same class can be used as a precise timestamp in Authenticator etc.63*/6465public class KerberosTime {6667private final long kerberosTime; // milliseconds since epoch, Date.getTime()68private final int microSeconds; // last 3 digits of the real microsecond6970// The time when this class is loaded. Used in setNow()71private static long initMilli = System.currentTimeMillis();72private static long initMicro = System.nanoTime() / 1000;7374private static boolean DEBUG = Krb5.DEBUG;7576// Do not make this public. It's a little confusing that micro77// is only the last 3 digits of microsecond.78private KerberosTime(long time, int micro) {79kerberosTime = time;80microSeconds = micro;81}8283/**84* Creates a KerberosTime object from milliseconds since epoch.85*/86public KerberosTime(long time) {87this(time, 0);88}8990// Warning: called by NativeCreds.c and nativeccache.c91public KerberosTime(String time) throws Asn1Exception {92this(toKerberosTime(time), 0);93}9495private static long toKerberosTime(String time) throws Asn1Exception {96// ASN.1 GeneralizedTime format:9798// "19700101000000Z"99// | | | | | | |100// 0 4 6 8 | | |101// 10 | |102// 12 |103// 14104105if (time.length() != 15)106throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);107if (time.charAt(14) != 'Z')108throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);109int year = Integer.parseInt(time.substring(0, 4));110Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));111calendar.clear(); // so that millisecond is zero112calendar.set(year,113Integer.parseInt(time.substring(4, 6)) - 1,114Integer.parseInt(time.substring(6, 8)),115Integer.parseInt(time.substring(8, 10)),116Integer.parseInt(time.substring(10, 12)),117Integer.parseInt(time.substring(12, 14)));118return calendar.getTimeInMillis();119}120121/**122* Creates a KerberosTime object from a Date object.123*/124public KerberosTime(Date time) {125this(time.getTime(), 0);126}127128/**129* Creates a KerberosTime object from an Instant object130*/131public KerberosTime(Instant instant) {132this(instant.getEpochSecond()*1000 + instant.getNano()/1000000L,133instant.getNano()/1000%1000);134}135136/**137* Creates a KerberosTime object for now. It uses System.nanoTime()138* to get a more precise time than "new Date()".139*/140public static KerberosTime now() {141long newMilli = System.currentTimeMillis();142long newMicro = System.nanoTime() / 1000;143long microElapsed = newMicro - initMicro;144long calcMilli = initMilli + microElapsed/1000;145if (calcMilli - newMilli > 100 || newMilli - calcMilli > 100) {146if (DEBUG) {147System.out.println("System time adjusted");148}149initMilli = newMilli;150initMicro = newMicro;151return new KerberosTime(newMilli, 0);152} else {153return new KerberosTime(calcMilli, (int)(microElapsed % 1000));154}155}156157/**158* Returns a string representation of KerberosTime object.159* @return a string representation of this object.160*/161public String toGeneralizedTimeString() {162Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));163calendar.clear();164165calendar.setTimeInMillis(kerberosTime);166return String.format("%04d%02d%02d%02d%02d%02dZ",167calendar.get(Calendar.YEAR),168calendar.get(Calendar.MONTH) + 1,169calendar.get(Calendar.DAY_OF_MONTH),170calendar.get(Calendar.HOUR_OF_DAY),171calendar.get(Calendar.MINUTE),172calendar.get(Calendar.SECOND));173}174175/**176* Encodes this object to a byte array.177* @return a byte array of encoded data.178* @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.179* @exception IOException if an I/O error occurs while reading encoded data.180*/181public byte[] asn1Encode() throws Asn1Exception, IOException {182DerOutputStream out = new DerOutputStream();183out.putGeneralizedTime(this.toDate());184return out.toByteArray();185}186187public long getTime() {188return kerberosTime;189}190191public Date toDate() {192return new Date(kerberosTime);193}194195public int getMicroSeconds() {196int temp_int = (int) ((kerberosTime % 1000L) * 1000L);197return temp_int + microSeconds;198}199200/**201* Returns a new KerberosTime object with the original seconds202* and the given microseconds.203*/204public KerberosTime withMicroSeconds(int usec) {205return new KerberosTime(206kerberosTime - kerberosTime%1000L + usec/1000L,207usec%1000);208}209210private boolean inClockSkew(int clockSkew) {211return java.lang.Math.abs(kerberosTime - System.currentTimeMillis())212<= clockSkew * 1000L;213}214215public boolean inClockSkew() {216return inClockSkew(getDefaultSkew());217}218219public boolean greaterThanWRTClockSkew(KerberosTime time, int clockSkew) {220if ((kerberosTime - time.kerberosTime) > clockSkew * 1000L)221return true;222return false;223}224225public boolean greaterThanWRTClockSkew(KerberosTime time) {226return greaterThanWRTClockSkew(time, getDefaultSkew());227}228229public boolean greaterThan(KerberosTime time) {230return kerberosTime > time.kerberosTime ||231kerberosTime == time.kerberosTime &&232microSeconds > time.microSeconds;233}234235public boolean equals(Object obj) {236if (this == obj) {237return true;238}239240if (!(obj instanceof KerberosTime)) {241return false;242}243244return kerberosTime == ((KerberosTime)obj).kerberosTime &&245microSeconds == ((KerberosTime)obj).microSeconds;246}247248public int hashCode() {249int result = 37 * 17 + (int)(kerberosTime ^ (kerberosTime >>> 32));250return result * 17 + microSeconds;251}252253public boolean isZero() {254return kerberosTime == 0 && microSeconds == 0;255}256257public int getSeconds() {258return (int) (kerberosTime / 1000L);259}260261/**262* Parse (unmarshal) a kerberostime from a DER input stream. This form263* parsing might be used when expanding a value which is part of264* a constructed sequence and uses explicitly tagged type.265*266* @exception Asn1Exception on error.267* @param data the Der input stream value, which contains268* one or more marshaled value.269* @param explicitTag tag number.270* @param optional indicates if this data field is optional271* @return an instance of KerberosTime.272*273*/274public static KerberosTime parse(275DerInputStream data, byte explicitTag, boolean optional)276throws Asn1Exception, IOException {277if ((optional) && (((byte)data.peekByte() & (byte)0x1F)!= explicitTag))278return null;279DerValue der = data.getDerValue();280if (explicitTag != (der.getTag() & (byte)0x1F)) {281throw new Asn1Exception(Krb5.ASN1_BAD_ID);282}283else {284DerValue subDer = der.getData().getDerValue();285Date temp = subDer.getGeneralizedTime();286return new KerberosTime(temp.getTime(), 0);287}288}289290public static int getDefaultSkew() {291int tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;292try {293if ((tdiff = Config.getInstance().getIntValue(294"libdefaults", "clockskew"))295== Integer.MIN_VALUE) { //value is not defined296tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;297}298} catch (KrbException e) {299if (DEBUG) {300System.out.println("Exception in getting clockskew from " +301"Configuration " +302"using default value: " +303e.getMessage());304}305}306return tdiff;307}308309public String toString() {310return toGeneralizedTimeString();311}312}313314315