From d342a45d98c4795b3a3fe1aaef5236ad4a782b55 Mon Sep 17 00:00:00 2001 From: Yuuta Liang Date: Thu, 12 Oct 2023 12:10:33 +0800 Subject: Implement data structures from X.680, X.501, X.509, and PKCS#10, with X.690 encoding / decoding support The implementation took four days, and it is still a little bit rough. Updated version should arrive soon. Signed-off-by: Yuuta Liang --- src/main/model/asn1/ASN1Time.java | 66 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/main/model/asn1/ASN1Time.java (limited to 'src/main/model/asn1/ASN1Time.java') diff --git a/src/main/model/asn1/ASN1Time.java b/src/main/model/asn1/ASN1Time.java new file mode 100644 index 0000000..08f861e --- /dev/null +++ b/src/main/model/asn1/ASN1Time.java @@ -0,0 +1,66 @@ +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; + } +} -- cgit v1.2.3