Bug 1205962 - Address some pylint complaints about pycert.py and pykey.py, r=keeler
authorCykesiopka <cykesiopka.bmo@gmail.com>
Mon, 05 Oct 2015 23:24:14 -0700
changeset 266783 ec07ca6a4679a2e5fba3c23167c4013c8df79720
parent 266782 8181c8fd433e74a1064881ad66f0af7c9270cefc
child 266784 ecd8d7abd47f791c413df3d50fa0b10f01f1c204
push id29497
push usercbook@mozilla.com
push dateThu, 08 Oct 2015 13:27:17 +0000
treeherdermozilla-central@1f4cf75c8948 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerskeeler
bugs1205962
milestone44.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1205962 - Address some pylint complaints about pycert.py and pykey.py, r=keeler Also adds more uses of enumerate() to simplify code.
security/manager/ssl/tests/unit/pycert.py
security/manager/ssl/tests/unit/pykey.py
--- a/security/manager/ssl/tests/unit/pycert.py
+++ b/security/manager/ssl/tests/unit/pycert.py
@@ -106,16 +106,17 @@ class NameConstraints(univ.Sequence):
         namedtype.OptionalNamedType('excludedSubtrees', rfc2459.GeneralSubtrees().subtype(
             implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))
     )
 
 
 class UnknownBaseError(Exception):
     """Base class for handling unexpected input in this module."""
     def __init__(self, value):
+        super(UnknownBaseError, self).__init__()
         self.value = value
         self.category = 'input'
 
     def __str__(self):
         return 'Unknown %s type "%s"' % (self.category, repr(self.value))
 
 
 class UnknownAlgorithmTypeError(UnknownBaseError):
@@ -212,25 +213,24 @@ def stringToDN(string, tag=None):
     """Takes a string representing a distinguished name or directory
     name and returns a Name for use by pyasn1. See the documentation
     for the issuer and subject fields for more details. Takes an
     optional implicit tag in cases where the Name needs to be tagged
     differently."""
     if '/' not in string:
         string = '/CN=%s' % string
     rdns = rfc2459.RDNSequence()
-    pos = 0
     pattern = '/(C|ST|L|O|OU|CN|emailAddress)='
     split = re.split(pattern, string)
     # split should now be [[encoding], <type>, <value>, <type>, <value>, ...]
     if split[0]:
         encoding = split[0]
     else:
         encoding = 'utf8String'
-    for (nameType, value) in zip(split[1::2], split[2::2]):
+    for pos, (nameType, value) in enumerate(zip(split[1::2], split[2::2])):
         ava = rfc2459.AttributeTypeAndValue()
         if nameType == 'C':
             ava.setComponentByName('type', rfc2459.id_at_countryName)
             nameComponent = rfc2459.X520countryName(value)
         elif nameType == 'ST':
             ava.setComponentByName('type', rfc2459.id_at_stateOrProvinceName)
             nameComponent = rfc2459.X520StateOrProvinceName()
         elif nameType == 'L':
@@ -254,17 +254,16 @@ def stringToDN(string, tag=None):
             # The value may have things like '\0' (i.e. a slash followed by
             # the number zero) that have to be decoded into the resulting
             # '\x00' (i.e. a byte with value zero).
             nameComponent.setComponentByName(encoding, value.decode(encoding='string_escape'))
         ava.setComponentByName('value', nameComponent)
         rdn = rfc2459.RelativeDistinguishedName()
         rdn.setComponentByPosition(0, ava)
         rdns.setComponentByPosition(pos, rdn)
-        pos = pos + 1
     if tag:
         name = rfc2459.Name().subtype(implicitTag=tag)
     else:
         name = rfc2459.Name()
     name.setComponentByPosition(0, rdns)
     return name
 
 def stringToAlgorithmIdentifiers(string):
@@ -293,17 +292,17 @@ def stringToAlgorithmIdentifiers(string)
 
 def datetimeToTime(dt):
     """Takes a datetime object and returns an rfc2459.Time object with
     that time as its value as a GeneralizedTime"""
     time = rfc2459.Time()
     time.setComponentByName('generalTime', useful.GeneralizedTime(dt.strftime('%Y%m%d%H%M%SZ')))
     return time
 
-class Certificate:
+class Certificate(object):
     """Utility class for reading a certificate specification and
     generating a signed x509 certificate"""
 
     def __init__(self, paramStream):
         self.versionValue = 2 # a value of 2 is X509v3
         self.signature = 'sha256WithRSAEncryption'
         self.issuer = 'Default Issuer'
         actualNow = datetime.datetime.utcnow()
@@ -390,17 +389,17 @@ class Certificate:
             self.notBefore = datetime.datetime.strptime(match.group(1), '%Y%m%d')
             self.notAfter = datetime.datetime.strptime(match.group(2), '%Y%m%d')
         else:
             delta = datetime.timedelta(days=(int(duration) / 2))
             self.notBefore = self.now - delta
             self.notAfter = self.now + delta
 
     def decodeExtension(self, extension):
-        match = re.search('([a-zA-Z]+)(\[critical\])?:(.*)', extension)
+        match = re.search(r'([a-zA-Z]+)(\[critical\])?:(.*)', extension)
         if not match:
             raise UnknownExtensionTypeError(extension)
         extensionType = match.group(1)
         critical = match.group(2)
         value = match.group(3)
         if extensionType == 'basicConstraints':
             self.addBasicConstraints(value, critical)
         elif extensionType == 'keyUsage':
@@ -474,33 +473,29 @@ class Certificate:
         if keyPurpose == 'OCSPSigning':
             return univ.ObjectIdentifier('1.3.6.1.5.5.7.3.9')
         if keyPurpose == 'timeStamping':
             return rfc2459.id_kp_timeStamping
         raise UnknownKeyPurposeTypeError(keyPurpose)
 
     def addExtKeyUsage(self, extKeyUsage, critical):
         extKeyUsageExtension = rfc2459.ExtKeyUsageSyntax()
-        count = 0
-        for keyPurpose in extKeyUsage.split(','):
+        for count, keyPurpose in enumerate(extKeyUsage.split(',')):
             extKeyUsageExtension.setComponentByPosition(count, self.keyPurposeToOID(keyPurpose))
-            count += 1
         self.addExtension(rfc2459.id_ce_extKeyUsage, extKeyUsageExtension, critical)
 
     def addSubjectAlternativeName(self, dNSNames, critical):
         subjectAlternativeName = rfc2459.SubjectAltName()
-        count = 0
-        for dNSName in dNSNames.split(','):
+        for count, dNSName in enumerate(dNSNames.split(',')):
             generalName = rfc2459.GeneralName()
             # The string may have things like '\0' (i.e. a slash
             # followed by the number zero) that have to be decoded into
             # the resulting '\x00' (i.e. a byte with value zero).
             generalName.setComponentByName('dNSName', dNSName.decode(encoding='string_escape'))
             subjectAlternativeName.setComponentByPosition(count, generalName)
-            count += 1
         self.addExtension(rfc2459.id_ce_subjectAltName, subjectAlternativeName, critical)
 
     def addAuthorityInformationAccess(self, ocspURI, critical):
         sequence = univ.Sequence()
         accessDescription = stringToAccessDescription(ocspURI)
         sequence.setComponentByPosition(0, accessDescription)
         self.addExtension(rfc2459.id_pe_authorityInfoAccess, sequence, critical)
 
@@ -520,37 +515,35 @@ class Certificate:
             (subtreesType, subtreesTag) = ('permittedSubtrees', 0)
         elif constraints.startswith('excluded:'):
             (subtreesType, subtreesTag) = ('excludedSubtrees', 1)
         else:
             raise UnknownNameConstraintsSpecificationError(constraints)
         generalSubtrees = rfc2459.GeneralSubtrees().subtype(
             implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, subtreesTag))
         subtrees = constraints[(constraints.find(':') + 1):]
-        pos = 0
-        for name in subtrees.split(','):
+        for pos, name in enumerate(subtrees.split(',')):
             generalName = rfc2459.GeneralName()
             if '/' in name:
                 directoryName = stringToDN(name,
-                  tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))
+                                           tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))
                 generalName.setComponentByName('directoryName', directoryName)
             else:
                 generalName.setComponentByName('dNSName', name)
             generalSubtree = GeneralSubtree()
             generalSubtree.setComponentByName('base', generalName)
             generalSubtrees.setComponentByPosition(pos, generalSubtree)
-            pos = pos + 1
         nameConstraints.setComponentByName(subtreesType, generalSubtrees)
         self.addExtension(rfc2459.id_ce_nameConstraints, nameConstraints, critical)
 
     def addNSCertType(self, certType, critical):
         if certType != 'sslServer':
             raise UnknownNSCertTypeError(certType)
         self.addExtension(univ.ObjectIdentifier('2.16.840.1.113730.1.1'), univ.BitString("'01'B"),
-            critical)
+                          critical)
 
     def getVersion(self):
         return rfc2459.Version(self.versionValue).subtype(
             explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))
 
     def getSerialNumber(self):
         return decoder.decode(self.serialNumber)[0]
 
@@ -581,20 +574,18 @@ class Certificate:
         tbsCertificate.setComponentByName('issuer', self.getIssuer())
         tbsCertificate.setComponentByName('validity', self.getValidity())
         tbsCertificate.setComponentByName('subject', self.getSubject())
         tbsCertificate.setComponentByName('subjectPublicKeyInfo',
                                           self.subjectKey.asSubjectPublicKeyInfo())
         if self.extensions:
             extensions = rfc2459.Extensions().subtype(
                 explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))
-            count = 0
-            for extension in self.extensions:
+            for count, extension in enumerate(self.extensions):
                 extensions.setComponentByPosition(count, extension)
-                count += 1
             tbsCertificate.setComponentByName('extensions', extensions)
         certificate = rfc2459.Certificate()
         certificate.setComponentByName('tbsCertificate', tbsCertificate)
         certificate.setComponentByName('signatureAlgorithm', signatureOID)
         tbsDER = encoder.encode(tbsCertificate)
         certificate.setComponentByName('signatureValue', self.issuerKey.sign(tbsDER, hashName))
         return encoder.encode(certificate)
 
--- a/security/manager/ssl/tests/unit/pykey.py
+++ b/security/manager/ssl/tests/unit/pykey.py
@@ -30,33 +30,33 @@ secp384r1: an ECC key on the curve secp3
 secp521r1: an ECC key on the curve secp521r1
 """
 
 from pyasn1.codec.der import encoder
 from pyasn1.type import univ, namedtype
 from pyasn1_modules import rfc2459
 from ecc import encoding
 from ecc import Key
-from ecc.ecdsa import randkey
 import base64
 import binascii
 import mock
 import rsa
 import sys
 
 def byteStringToHexifiedBitString(string):
     """Takes a string of bytes and returns a hex string representing
     those bytes for use with pyasn1.type.univ.BitString. It must be of
     the form "'<hex bytes>'H", where the trailing 'H' indicates to
     pyasn1 that the input is a hex string."""
     return "'%s'H" % binascii.hexlify(string)
 
 class UnknownBaseError(Exception):
     """Base class for handling unexpected input in this module."""
     def __init__(self, value):
+        super(UnknownBaseError, self).__init__()
         self.value = value
         self.category = 'input'
 
     def __str__(self):
         return 'Unknown %s type "%s"' % (self.category, repr(self.value))
 
 
 class UnknownKeySpecificationError(UnknownBaseError):
@@ -100,17 +100,17 @@ class PrivateKeyInfo(univ.Sequence):
     """Helper type for encoding a PKCS #8 private key info"""
     componentType = namedtype.NamedTypes(
         namedtype.NamedType('version', univ.Integer()),
         namedtype.NamedType('privateKeyAlgorithm', rfc2459.AlgorithmIdentifier()),
         namedtype.NamedType('privateKey', univ.OctetString())
     )
 
 
-class RSAKey:
+class RSAKey(object):
     # For reference, when encoded as a subject public key info, the
     # base64-encoded sha-256 hash of this key is
     # VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=
     sharedRSA_N = long(
         '00ba8851a8448e16d641fd6eb6880636103d3c13d9eae4354ab4ecf56857'
         '6c247bc1c725a8e0d81fbdb19c069b6e1a86f26be2af5a756b6a6471087a'
         'a55aa74587f71cd5249c027ecd43fc1e69d038202993ab20c349e4dbb94c'
         'c26b6c0eed15820ff17ead691ab1d3023a8b2a41eea770e00f0d8dfd660b'
@@ -285,17 +285,17 @@ class RSAKey:
         '2c06e1a31b118afd1f9a2f396cced425c501d91435ca8656766ced2b93bb'
         'b8669fce9bacd727d1dacb3dafabc3293e35389eef8ea0b58e1aeb1a20e6'
         'a61f9fcd453f7567fe31d123b616a26fef4df1d6c9f7490111d028eefd1d'
         '972045b1a242273dd7a67ebf111db2741a5a93c7b2289cc4a236f5a99a6e'
         'c7a8206fdae1c1d04bdbb1980d4a298c5a17dae4186474a5f7835d882bce'
         'f24aef4ed6f149f94d96c9f7d78e647fc778a9017ff208d3b4a1768b1821'
         '62102cdab032fabbab38d5200a324649', 16)
     evRSA2040_P = long(
-         '0f3844d0d4d4d6a21acd76a6fc370b8550e1d7ec5a6234172e790f0029ae'
+        '0f3844d0d4d4d6a21acd76a6fc370b8550e1d7ec5a6234172e790f0029ae'
         '651f6d5c59330ab19802b9d7a207de7a1fb778e3774fdbdc411750633d8d'
         '1b3fe075006ffcfd1d10e763c7a9227d2d5f0c2dade1c9e659c350a159d3'
         '6bb986f12636d4f9942b288bc0fe21da8799477173144249ca2e389e6c5c'
         '25aa78c8cad7d4df', 16)
     evRSA2040_Q = long(
         '0d4d0bedd1962f07a1ead6b23a4ed67aeaf1270f052a6d29ba074945c636'
         '1a5c4f8f07bf859e067aed3f4e6e323ef2aa8a6acd340b0bdc7cfe4fd329'
         'e3c97f870c7f7735792c6aa9d0f7e7542a28ed6f01b0e55a2b8d9c24a65c'
@@ -585,17 +585,17 @@ def longToEvenLengthHexString(val):
     h = format(val, 'x')
     if not len(h) % 2 == 0:
         h = '0' + h
     return h
 
 def notRandom(n):
     return n * '\x04'
 
-class ECCKey:
+class ECCKey(object):
     secp256k1Encoded = str('08fd87b04fba98090100004035ee7c7289d8fef7a8'
         '6afe5da66d8bc2ebb6a8543fd2fead089f45ce7acd0fa64382a9500c41dad'
         '770ffd4b511bf4b492eb1238800c32c4f76c73a3f3294e7c5002067cebc20'
         '8a5fa3df16ec2bb34acc59a42ab4abb0538575ca99b92b6a2149a04f')
 
     secp224r1Encoded = str('0ee5587c4d18526f00e00038668d72cca6fd6a1b35'
         '57b5366104d84408ecb637f08e8c86bbff82cc00e88f0066d7af63c3298ba'
         '377348a1202b03b37fd6b1ff415aa311e001c04389459926c3296c242b83e'
@@ -617,17 +617,17 @@ class ECCKey:
         '6bc9cc66752ec27f597734fa66c62b792f88c519d6d37f0d16ea1c483a182'
         '7a010b9128e3a08070ca33ef5f57835b7c1ba251f6cc3521dc42b01065345'
         '1981b445d343eed3782a35d6cff0ff484f5a883d209f1b9042b726703568b'
         '2f326e18b833bdd8aa0734392bcd19501e10d698a79f53e11e0a22bdd2aad'
         '900042014f3284fa698dd9fe1118dd331851cdfaac5a3829278eb8994839d'
         'e9471c940b858c69d2d05e8c01788a7d0b6e235aa5e783fc1bee807dcc386'
         '5f920e12cf8f2d29')
 
-    def __init__(self, specification = None):
+    def __init__(self, specification=None):
         if specification == 'secp256k1':
             self.key = Key.Key.decode(binascii.unhexlify(self.secp256k1Encoded))
             self.keyOID = secp256k1
         elif specification == 'secp224r1':
             self.key = Key.Key.decode(binascii.unhexlify(self.secp224r1Encoded))
             self.keyOID = secp224r1
         elif specification == 'secp256r1':
             self.key = Key.Key.decode(binascii.unhexlify(self.secp256r1Encoded))