diff options
Diffstat (limited to 'src/main/model/asn1/Bool.java')
-rw-r--r-- | src/main/model/asn1/Bool.java | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/main/model/asn1/Bool.java b/src/main/model/asn1/Bool.java new file mode 100644 index 0000000..d9f1851 --- /dev/null +++ b/src/main/model/asn1/Bool.java @@ -0,0 +1,60 @@ +package model.asn1; + +import model.asn1.exceptions.ParseException; +import model.asn1.parsing.BytesReader; + +/** + * Represents the ASN.1 BOOLEAN type. It always has one byte length. Its content is either 0xFF (true) or 0x00 (false). + */ +public class Bool extends ASN1Object { + /** + * The X.680 universal class tag assignment. + */ + public static final Tag TAG = new Tag(TagClass.UNIVERSAL, false, 0x1); + + private final boolean value; + + /** + * EFFECTS: Initiate the BOOLEAN with the given tag, an optional context-specific tag number for explicit + * encoding, and its value. For more information, consult {@link ASN1Object}. + * REQUIRES: Consult {@link ASN1Object}. + */ + public Bool(Tag tag, Tag parentTag, boolean value) { + super(tag, parentTag); + this.value = value; + } + + /** + * EFFECTS: Parse input bytes. For more information on tags parsing, consult {@link ASN1Object}. + * Throws {@link ParseException} if the input data is invalid: + * - The length is not 1 + * - The value is neither 0x00 nor 0xFF + * - Other cases as denoted in {@link ASN1Object} + */ + public Bool(BytesReader encoded, boolean hasParentTag) throws ParseException { + super(encoded, hasParentTag); + if (getLength() != 1) { + throw new ParseException("Invalid boolean length: " + getLength()); + } + final Byte val = encoded.require(1, true)[0]; + if (val == 0) { + this.value = false; + } else if (val == -1) { + this.value = true; + } else { + throw new ParseException("Unknown boolean value: " + val); + } + } + + /** + * EFFECTS: Encode the boolean to either 0x00 or 0xFF. + */ + @Override + public Byte[] encodeValueDER() { + return new Byte[]{ value ? (byte) -1 : 0 }; + } + + public boolean getValue() { + return value; + } +} |