package model.asn1; import model.asn1.exceptions.ParseException; import model.asn1.parsing.BytesReader; import ui.Utils; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; /** * Common base-class for models like UTCTime and GeneralizedTime. Despite all the formatting and encoding differences, * it stores a timestamp and corresponding timezone. */ public abstract class ASN1Time extends ASN1Object { /** * The time. */ private ZonedDateTime timestamp; /** * EFFECTS: Initialize the time with the specific tag, parentTag, and timestamp. For tag and parentTag, consult * {@link ASN1Object}. */ public ASN1Time(Tag tag, Tag parentTag, ZonedDateTime timestamp) { super(tag, parentTag); this.timestamp = timestamp; } /** * EFFECTS: Parse and decode DER bytes into the corresponding time type. For more info on decoding, take a look at * {@link ASN1Object}. * Throws {@link ParseException} if the input is invalid: * - Invalid date format * - Zero length * - Other circumstances (e.g., early EOF) as seen in {@link ASN1Object} * MODIFIES: this, encoded */ public ASN1Time(BytesReader encoded, boolean hasParentTag) throws ParseException { super(encoded, hasParentTag); this.timestamp = toDate(new String(Utils.byteToByte(encoded.require(getLength(), true)))); } /** * EFFECTS: Generate the byte array for the formatted string. */ @Override public Byte[] encodeValueDER() { return Utils.byteToByte(toString().getBytes(StandardCharsets.UTF_8)); } /** * EFFECTS: Convert the given string into corresponding timestamp. * Throws {@link ParseException} if the time is malformed. */ public abstract ZonedDateTime toDate(String str) throws ParseException; /** * EFFECTS: Convert getTimestamp() into corresponding ASN.1 time format. */ @Override public abstract String toString(); public ZonedDateTime getTimestamp() { return timestamp; } }