]> Cypherpunks.ru repositories - pyderasn.git/blobdiff - pyderasn.py
Raised copyright years
[pyderasn.git] / pyderasn.py
index 4a27bbe5e1c5222388bf4fc4056b250ac6447e67..116ef6e9e8d899fb2dfa95e431b6915045993c4c 100755 (executable)
@@ -4,7 +4,7 @@
 # pylint: disable=line-too-long,superfluous-parens,protected-access,too-many-lines
 # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements
 # PyDERASN -- Python ASN.1 DER/CER/BER codec with abstract structures
-# Copyright (C) 2017-2021 Sergey Matveev <stargrave@stargrave.org>
+# Copyright (C) 2017-2022 Sergey Matveev <stargrave@stargrave.org>
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU Lesser General Public License as
@@ -971,12 +971,12 @@ _____________
 UTCTime
 _______
 .. autoclass:: pyderasn.UTCTime
-   :members: __init__, todatetime
+   :members: __init__, todatetime, totzdatetime
 
 GeneralizedTime
 _______________
 .. autoclass:: pyderasn.GeneralizedTime
-   :members: __init__, todatetime
+   :members: __init__, todatetime, totzdatetime
 
 Special types
 -------------
@@ -1159,8 +1159,6 @@ Now you can print only the specified tree, for example signature algorithm::
 """
 
 from array import array
-from codecs import getdecoder
-from codecs import getencoder
 from collections import namedtuple
 from collections import OrderedDict
 from copy import copy
@@ -1182,7 +1180,13 @@ except ImportError:  # pragma: no cover
     def colored(what, *args, **kwargs):
         return what
 
-__version__ = "9.0"
+try:
+    from dateutil.tz import UTC as tzUTC
+except ImportError:  # pragma: no cover
+    tzUTC = "missing"
+
+
+__version__ = "9.1"
 
 __all__ = (
     "agg_octet_string",
@@ -1441,20 +1445,16 @@ class BoundsError(ASN1Error):
 # Basic coders
 ########################################################################
 
-_hexdecoder = getdecoder("hex")
-_hexencoder = getencoder("hex")
-
-
 def hexdec(data):
     """Binary data to hexadecimal string convert
     """
-    return _hexdecoder(data)[0]
+    return bytes.fromhex(data)
 
 
 def hexenc(data):
     """Hexadecimal string to binary data convert
     """
-    return _hexencoder(data)[0].decode("ascii")
+    return data.hex()
 
 
 def int_bytes_len(num, byte_len=8):
@@ -4784,6 +4784,8 @@ class UTF8String(CommonString):
 
 
 class AllowableCharsMixin:
+    __slots__ = ()
+
     @property
     def allowable_chars(self):
         return frozenset(chr(c) for c in self._allowable_chars)
@@ -4795,6 +4797,9 @@ class AllowableCharsMixin:
         return value
 
 
+NUMERIC_ALLOWABLE_CHARS = frozenset(digits.encode("ascii") + b" ")
+
+
 class NumericString(AllowableCharsMixin, CommonString):
     """Numeric string
 
@@ -4804,11 +4809,14 @@ class NumericString(AllowableCharsMixin, CommonString):
     >>> NumericString().allowable_chars
     frozenset(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' '])
     """
-    __slots__ = ()
+    __slots__ = ("_allowable_chars",)
     tag_default = tag_encode(18)
     encoding = "ascii"
     asn1_type_name = "NumericString"
-    _allowable_chars = frozenset(digits.encode("ascii") + b" ")
+
+    def __init__(self, *args, **kwargs):
+        self._allowable_chars = NUMERIC_ALLOWABLE_CHARS
+        super().__init__(*args, **kwargs)
 
 
 PrintableStringState = namedtuple(
@@ -4818,6 +4826,11 @@ PrintableStringState = namedtuple(
 )
 
 
+PRINTABLE_ALLOWABLE_CHARS = frozenset(
+    (ascii_letters + digits + " '()+,-./:=?").encode("ascii")
+)
+
+
 class PrintableString(AllowableCharsMixin, CommonString):
     """Printable string
 
@@ -4830,13 +4843,10 @@ class PrintableString(AllowableCharsMixin, CommonString):
     >>> obj.allow_asterisk, obj.allow_ampersand
     (True, False)
     """
-    __slots__ = ()
+    __slots__ = ("_allowable_chars",)
     tag_default = tag_encode(19)
     encoding = "ascii"
     asn1_type_name = "PrintableString"
-    _allowable_chars = frozenset(
-        (ascii_letters + digits + " '()+,-./:=?").encode("ascii")
-    )
     _asterisk = frozenset("*".encode("ascii"))
     _ampersand = frozenset("&".encode("ascii"))
 
@@ -4857,11 +4867,13 @@ class PrintableString(AllowableCharsMixin, CommonString):
         :param allow_asterisk: allow asterisk character
         :param allow_ampersand: allow ampersand character
         """
+        allowable_chars = PRINTABLE_ALLOWABLE_CHARS
         if allow_asterisk:
-            self._allowable_chars |= self._asterisk
+            allowable_chars |= self._asterisk
         if allow_ampersand:
-            self._allowable_chars |= self._ampersand
-        super(PrintableString, self).__init__(
+            allowable_chars |= self._ampersand
+        self._allowable_chars = allowable_chars
+        super().__init__(
             value, bounds, impl, expl, default, optional, _decoded, ctx,
         )
 
@@ -4930,6 +4942,11 @@ class VideotexString(CommonString):
     asn1_type_name = "VideotexString"
 
 
+IA5_ALLOWABLE_CHARS = frozenset(b"".join(
+    chr(c).encode("ascii") for c in range(128)
+))
+
+
 class IA5String(AllowableCharsMixin, CommonString):
     """IA5 string
 
@@ -4944,13 +4961,14 @@ class IA5String(AllowableCharsMixin, CommonString):
     >>> IA5String().allowable_chars
     frozenset(["NUL", ... "DEL"])
     """
-    __slots__ = ()
+    __slots__ = ("_allowable_chars",)
     tag_default = tag_encode(22)
     encoding = "ascii"
     asn1_type_name = "IA5"
-    _allowable_chars = frozenset(b"".join(
-        chr(c).encode("ascii") for c in range(128)
-    ))
+
+    def __init__(self, *args, **kwargs):
+        self._allowable_chars = IA5_ALLOWABLE_CHARS
+        super().__init__(*args, **kwargs)
 
 
 LEN_YYMMDDHHMMSSZ = len("YYMMDDHHMMSSZ")
@@ -4961,6 +4979,11 @@ LEN_YYYYMMDDHHMMSSZ = len("YYYYMMDDHHMMSSZ")
 LEN_LEN_YYYYMMDDHHMMSSZ = len_encode(LEN_YYYYMMDDHHMMSSZ)
 
 
+VISIBLE_ALLOWABLE_CHARS = frozenset(b"".join(
+    chr(c).encode("ascii") for c in range(ord(" "), ord("~") + 1)
+))
+
+
 class VisibleString(AllowableCharsMixin, CommonString):
     """Visible string
 
@@ -4970,13 +4993,14 @@ class VisibleString(AllowableCharsMixin, CommonString):
     >>> VisibleString().allowable_chars
     frozenset([" ", ... "~"])
     """
-    __slots__ = ()
+    __slots__ = ("_allowable_chars",)
     tag_default = tag_encode(26)
     encoding = "ascii"
     asn1_type_name = "VisibleString"
-    _allowable_chars = frozenset(b"".join(
-        chr(c).encode("ascii") for c in range(ord(" "), ord("~") + 1)
-    ))
+
+    def __init__(self, *args, **kwargs):
+        self._allowable_chars = VISIBLE_ALLOWABLE_CHARS
+        super().__init__(*args, **kwargs)
 
 
 class ISO646String(VisibleString):
@@ -5014,6 +5038,8 @@ class UTCTime(VisibleString):
     datetime.datetime(2017, 9, 30, 22, 7, 50)
     >>> UTCTime(datetime(2057, 9, 30, 22, 7, 50)).todatetime()
     datetime.datetime(1957, 9, 30, 22, 7, 50)
+    >>> UTCTime(datetime(2057, 9, 30, 22, 7, 50)).totzdatetime()
+    datetime.datetime(1957, 9, 30, 22, 7, 50, tzinfo=tzutc())
 
     If BER encoded value was met, then ``ber_raw`` attribute will hold
     its raw representation.
@@ -5223,6 +5249,12 @@ class UTCTime(VisibleString):
     def todatetime(self):
         return self._value
 
+    def totzdatetime(self):
+        try:
+            return self._value.replace(tzinfo=tzUTC)
+        except TypeError as err:
+            raise NotImplementedError("Missing dateutil.tz") from err
+
     def __repr__(self):
         return pp_console_row(next(self.pps()))
 
@@ -6083,7 +6115,9 @@ SequenceState = namedtuple(
 )
 
 
-class SequenceEncode1stMixing:
+class SequenceEncode1stMixin:
+    __slots__ = ()
+
     def _encode1st(self, state):
         state.append(0)
         idx = len(state) - 1
@@ -6095,7 +6129,7 @@ class SequenceEncode1stMixing:
         return len(self.tag) + len_size(vlen) + vlen, state
 
 
-class Sequence(SequenceEncode1stMixing, Obj):
+class Sequence(SequenceEncode1stMixin, Obj):
     """``SEQUENCE`` structure type
 
     You have to make specification of sequence::
@@ -6593,7 +6627,7 @@ class Sequence(SequenceEncode1stMixing, Obj):
             yield pp
 
 
-class Set(Sequence, SequenceEncode1stMixing):
+class Set(Sequence, SequenceEncode1stMixin):
     """``SET`` structure type
 
     Its usage is identical to :py:class:`pyderasn.Sequence`.
@@ -6796,7 +6830,7 @@ SequenceOfState = namedtuple(
 )
 
 
-class SequenceOf(SequenceEncode1stMixing, Obj):
+class SequenceOf(SequenceEncode1stMixin, Obj):
     """``SEQUENCE OF`` sequence type
 
     For that kind of type you must specify the object it will carry on