From 7ca5acb7a59fb1703cbda808e5e16aa3458d3e43 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 16 Mar 2020 16:57:58 -0400 Subject: [PATCH 1/2] Ran black, updated to pylint 2.x --- .pylintrc | 3 +- adafruit_rsa/__init__.py | 13 ++- adafruit_rsa/_compat.py | 16 ++-- adafruit_rsa/asn1.py | 22 +++-- adafruit_rsa/common.py | 10 +- adafruit_rsa/core.py | 23 ++--- adafruit_rsa/key.py | 178 ++++++++++++++++++++--------------- adafruit_rsa/machine_size.py | 11 +-- adafruit_rsa/pem.py | 28 +++--- adafruit_rsa/pkcs1.py | 6 +- adafruit_rsa/prime.py | 9 +- adafruit_rsa/randnum.py | 3 +- adafruit_rsa/transform.py | 31 +++--- docs/conf.py | 112 +++++++++++++--------- examples/rsa_sign_verify.py | 6 +- examples/rsa_tests.py | 8 +- setup.py | 52 +++++----- util/decode_priv_key.py | 8 +- 18 files changed, 298 insertions(+), 241 deletions(-) diff --git a/.pylintrc b/.pylintrc index 32dc0ab..d8f0ee8 100644 --- a/.pylintrc +++ b/.pylintrc @@ -52,7 +52,7 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" # disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error +disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -124,7 +124,6 @@ notes=FIXME,XXX [TYPECHECK] -disable=bad-option-value # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that diff --git a/adafruit_rsa/__init__.py b/adafruit_rsa/__init__.py index e50bb9d..1036fda 100755 --- a/adafruit_rsa/__init__.py +++ b/adafruit_rsa/__init__.py @@ -24,8 +24,17 @@ """ from adafruit_rsa.key import newkeys, PrivateKey, PublicKey -from adafruit_rsa.pkcs1 import encrypt, decrypt, sign, verify, DecryptionError, \ - VerificationError, find_signature_hash, sign_hash, compute_hash +from adafruit_rsa.pkcs1 import ( + encrypt, + decrypt, + sign, + verify, + DecryptionError, + VerificationError, + find_signature_hash, + sign_hash, + compute_hash, +) __author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly" __date__ = "2018-09-16" diff --git a/adafruit_rsa/_compat.py b/adafruit_rsa/_compat.py index bb4b4e2..56497c2 100755 --- a/adafruit_rsa/_compat.py +++ b/adafruit_rsa/_compat.py @@ -39,10 +39,7 @@ MACHINE_WORD_SIZE = 64 -INTEGER_TYPES = (int, ) -# pylint: disable=redefined-builtin, invalid-name -range = range -zip = zip +INTEGER_TYPES = (int,) def write_to_stdout(data): @@ -112,8 +109,7 @@ def xor_bytes(bytes_1, bytes_2): return bytes(x ^ y for x, y in zip(bytes_1, bytes_2)) -def get_word_alignment(num, force_arch=64, - _machine_word_size=MACHINE_WORD_SIZE): +def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE): """ Returns alignment details for the given number based on the platform Python is running on. @@ -132,10 +128,10 @@ def get_word_alignment(num, force_arch=64, (word_bits, word_bytes, max_uint, packing_format_type) """ - max_uint64 = 0xffffffffffffffff - max_uint32 = 0xffffffff - max_uint16 = 0xffff - max_uint8 = 0xff + max_uint64 = 0xFFFFFFFFFFFFFFFF + max_uint32 = 0xFFFFFFFF + max_uint16 = 0xFFFF + max_uint8 = 0xFF if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32: # 64-bit unsigned integer. diff --git a/adafruit_rsa/asn1.py b/adafruit_rsa/asn1.py index f25cfac..a50ae3b 100755 --- a/adafruit_rsa/asn1.py +++ b/adafruit_rsa/asn1.py @@ -25,22 +25,28 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + class PubKeyHeader(univ.Sequence): """OpenSSL Public Key Header""" + componentType = namedtype.NamedTypes( - namedtype.NamedType('oid', univ.ObjectIdentifier()), - namedtype.NamedType('parameters', univ.Null()), + namedtype.NamedType("oid", univ.ObjectIdentifier()), + namedtype.NamedType("parameters", univ.Null()), ) class OpenSSLPubKey(univ.Sequence): """Creates a PKCS#1 DER-encoded NamedType.""" - componentType = namedtype.NamedTypes( - namedtype.NamedType('header', PubKeyHeader()), + componentType = namedtype.NamedTypes( + namedtype.NamedType("header", PubKeyHeader()), # This little hack (the implicit tag) allows us to get a Bit String as Octet String - namedtype.NamedType('key', univ.OctetString().subtype( - implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3))), + namedtype.NamedType( + "key", + univ.OctetString().subtype( + implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3) + ), + ), ) @@ -53,6 +59,6 @@ class AsnPubKey(univ.Sequence): """ componentType = namedtype.NamedTypes( - namedtype.NamedType('modulus', univ.Integer()), - namedtype.NamedType('publicExponent', univ.Integer()), + namedtype.NamedType("modulus", univ.Integer()), + namedtype.NamedType("publicExponent", univ.Integer()), ) diff --git a/adafruit_rsa/common.py b/adafruit_rsa/common.py index 2316a2f..7ca9f13 100755 --- a/adafruit_rsa/common.py +++ b/adafruit_rsa/common.py @@ -15,12 +15,12 @@ # limitations under the License. """Common functionality shared by several modules.""" -# pylint: disable=redefined-builtin, invalid-name -from adafruit_rsa._compat import zip +# pylint: disable=invalid-name __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + def bit_length(int_type): """Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros""" @@ -33,9 +33,11 @@ def bit_length(int_type): class NotRelativePrimeError(ValueError): """Raises if provided a and b not relatively prime.""" + def __init__(self, a, b, d, msg=None): super(NotRelativePrimeError, self).__init__( - msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d)) + msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d) + ) self.a = a self.b = b self.d = d @@ -66,7 +68,7 @@ def bit_size(num): try: return bit_length(num) except AttributeError: - raise TypeError('bit_size(num) only supports integers, not %r' % type(num)) + raise TypeError("bit_size(num) only supports integers, not %r" % type(num)) def byte_size(number): diff --git a/adafruit_rsa/core.py b/adafruit_rsa/core.py index 7e9a727..8aeaa72 100755 --- a/adafruit_rsa/core.py +++ b/adafruit_rsa/core.py @@ -26,6 +26,7 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + def fast_pow(x, e, m): """Performs fast modular exponentiation, saves RAM on small CPUs/micros. :param int x: Base @@ -38,7 +39,7 @@ def fast_pow(x, e, m): while E > 0: if E % 2 == 0: X = (X * X) % m - E = E//2 + E = E // 2 else: Y = (X * Y) % m E = E - 1 @@ -50,33 +51,33 @@ def assert_int(var, name): if is_integer(var): return - raise TypeError('%s should be an integer, not %s' % (name, var.__class__)) + raise TypeError("%s should be an integer, not %s" % (name, var.__class__)) def encrypt_int(message, ekey, n): """Encrypts a message using encryption key 'ekey', working modulo n""" - assert_int(message, 'message') - assert_int(ekey, 'ekey') - assert_int(n, 'n') + assert_int(message, "message") + assert_int(ekey, "ekey") + assert_int(n, "n") if message < 0: - raise ValueError('Only non-negative numbers are supported') + raise ValueError("Only non-negative numbers are supported") if message > n: raise OverflowError("The message %i is too long for n=%i" % (message, n)) - #return pow(message, ekey, n) - #print('fast_pow({},{},{})'.format(message,ekey,n)) + # return pow(message, ekey, n) + # print('fast_pow({},{},{})'.format(message,ekey,n)) return fast_pow(message, ekey, n) def decrypt_int(cyphertext, dkey, n): """Decrypts a cypher text using the decryption key 'dkey', working modulo n""" - assert_int(cyphertext, 'cyphertext') - assert_int(dkey, 'dkey') - assert_int(n, 'n') + assert_int(cyphertext, "cyphertext") + assert_int(dkey, "dkey") + assert_int(n, "n") message = fast_pow(cyphertext, dkey, n) return message diff --git a/adafruit_rsa/key.py b/adafruit_rsa/key.py index a46b03a..5c6d86a 100755 --- a/adafruit_rsa/key.py +++ b/adafruit_rsa/key.py @@ -49,10 +49,11 @@ DEFAULT_EXPONENT = 65537 + class AbstractKey(object): """Abstract superclass for private and public keys.""" - __slots__ = ('n', 'e') + __slots__ = ("n", "e") def __init__(self, n, e): self.n = n @@ -97,7 +98,7 @@ def _save_pkcs1_der(self): """ @classmethod - def load_pkcs1(cls, keyfile, format='PEM'): + def load_pkcs1(cls, keyfile, format="PEM"): """Loads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains @@ -109,15 +110,17 @@ def load_pkcs1(cls, keyfile, format='PEM'): :return: the loaded key :rtype: AbstractKey """ - raise NotImplementedError("Loading PEM Files not supported by this CircuitPython library.") + raise NotImplementedError( + "Loading PEM Files not supported by this CircuitPython library." + ) # methods = { # 'PEM': cls._load_pkcs1_pem, # 'DER': cls._load_pkcs1_der, - #} + # } - #method = cls._assert_format_exists(format, methods) - #return method(keyfile) + # method = cls._assert_format_exists(format, methods) + # return method(keyfile) @staticmethod def _assert_format_exists(file_format, methods): @@ -127,11 +130,12 @@ def _assert_format_exists(file_format, methods): try: return methods[file_format] except KeyError: - formats = ', '.join(sorted(methods.keys())) - raise ValueError('Unsupported format: %r, try one of %s' % (file_format, - formats)) + formats = ", ".join(sorted(methods.keys())) + raise ValueError( + "Unsupported format: %r, try one of %s" % (file_format, formats) + ) - def save_pkcs1(self, format='PEM'): + def save_pkcs1(self, format="PEM"): """Saves the key in PKCS#1 DER or PEM format. :param format: the format to save; 'PEM' or 'DER' @@ -141,8 +145,8 @@ def save_pkcs1(self, format='PEM'): """ methods = { - 'PEM': self._save_pkcs1_pem, - 'DER': self._save_pkcs1_der, + "PEM": self._save_pkcs1_pem, + "DER": self._save_pkcs1_der, } method = self._assert_format_exists(format, methods) @@ -179,6 +183,7 @@ def unblind(self, blinded, r): return (adafruit_rsa.common.inverse(r, self.n) * blinded) % self.n + # pylint: disable=abstract-method class PublicKey(AbstractKey): """Represents a public RSA key. @@ -204,13 +209,13 @@ class PublicKey(AbstractKey): """ - __slots__ = ('n', 'e') + __slots__ = ("n", "e") def __getitem__(self, key): return getattr(self, key) def __repr__(self): - return 'PublicKey(%i, %i)' % (self.n, self.e) + return "PublicKey(%i, %i)" % (self.n, self.e) def __getstate__(self): """Returns the key as tuple for pickling.""" @@ -255,12 +260,12 @@ def _load_pkcs1_der(cls, keyfile): PublicKey(2367317549, 65537) """ - + # pylint: disable=import-outside-toplevel from adafruit_rsa.tools.pyasn1.codec.der import decoder from adafruit_rsa.asn1 import AsnPubKey (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) - return cls(n=int(priv['modulus']), e=int(priv['publicExponent'])) + return cls(n=int(priv["modulus"]), e=int(priv["publicExponent"])) def _save_pkcs1_der(self): """Saves the public key in PKCS#1 DER format. @@ -268,14 +273,14 @@ def _save_pkcs1_der(self): :returns: the DER-encoded public key. :rtype: bytes """ - + # pylint: disable=import-outside-toplevel from pyasn1.codec.der import encoder from rsa.asn1 import AsnPubKey # Create the ASN object asn_key = AsnPubKey() - asn_key.setComponentByName('modulus', self.n) - asn_key.setComponentByName('publicExponent', self.e) + asn_key.setComponentByName("modulus", self.n) + asn_key.setComponentByName("publicExponent", self.e) return encoder.encode(asn_key) @@ -291,7 +296,7 @@ def _load_pkcs1_pem(cls, keyfile): :return: a PublicKey object """ - der = adafruit_rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY') + der = adafruit_rsa.pem.load_pem(keyfile, "RSA PUBLIC KEY") return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self): @@ -302,7 +307,7 @@ def _save_pkcs1_pem(self): """ der = self._save_pkcs1_der() - return adafruit_rsa.pem.save_pem(der, 'RSA PUBLIC KEY') + return adafruit_rsa.pem.save_pem(der, "RSA PUBLIC KEY") @classmethod def load_pkcs1_openssl_pem(cls, keyfile): @@ -320,7 +325,7 @@ def load_pkcs1_openssl_pem(cls, keyfile): :return: a PublicKey object """ - der = adafruit_rsa.pem.load_pem(keyfile, 'PUBLIC KEY') + der = adafruit_rsa.pem.load_pem(keyfile, "PUBLIC KEY") return cls.load_pkcs1_openssl_der(der) @classmethod @@ -333,17 +338,17 @@ def load_pkcs1_openssl_der(cls, keyfile): :rtype: bytes """ - + # pylint: disable=import-outside-toplevel from adafruit_rsa.asn1 import OpenSSLPubKey from pyasn1.codec.der import decoder from pyasn1.type import univ (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) - if keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'): + if keyinfo["header"]["oid"] != univ.ObjectIdentifier("1.2.840.113549.1.1.1"): raise TypeError("This is not a DER-encoded OpenSSL-compatible public key") - return cls._load_pkcs1_der(keyinfo['key'][1:]) + return cls._load_pkcs1_der(keyinfo["key"][1:]) class PrivateKey(AbstractKey): @@ -370,7 +375,7 @@ class PrivateKey(AbstractKey): """ - __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef') + __slots__ = ("n", "e", "d", "p", "q", "exp1", "exp2", "coef") # pylint: disable=too-many-arguments def __init__(self, n, e, d, p, q): @@ -388,8 +393,13 @@ def __getitem__(self, key): return getattr(self, key) def __repr__(self): - return 'PrivateKey(%i, %i, %i, %i, %i)' % (self.n, self.e, self.d, - self.p, self.q) + return "PrivateKey(%i, %i, %i, %i, %i)" % ( + self.n, + self.e, + self.d, + self.p, + self.q, + ) def __getstate__(self): """Returns the key as tuple for pickling.""" @@ -406,20 +416,24 @@ def __eq__(self, other): if not isinstance(other, PrivateKey): return False - return (self.n == other.n and - self.e == other.e and - self.d == other.d and - self.p == other.p and - self.q == other.q and - self.exp1 == other.exp1 and - self.exp2 == other.exp2 and - self.coef == other.coef) + return ( + self.n == other.n + and self.e == other.e + and self.d == other.d + and self.p == other.p + and self.q == other.q + and self.exp1 == other.exp1 + and self.exp2 == other.exp2 + and self.coef == other.coef + ) def __ne__(self, other): return not self == other def __hash__(self): - return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) + return hash( + (self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef) + ) def blinded_decrypt(self, encrypted): """Decrypts the message using blinding to prevent side-channel attacks. @@ -474,7 +488,10 @@ def _load_pkcs1_der(cls, keyfile): """ - from adafruit_rsa.tools.pyasn1.codec.der import decoder + from adafruit_rsa.tools.pyasn1.codec.der import ( # pylint: disable=import-outside-toplevel + decoder, + ) + (priv, _) = decoder.decode(keyfile) # ASN.1 contents of DER encoded private key: @@ -493,7 +510,7 @@ def _load_pkcs1_der(cls, keyfile): # } if priv[0] != 0: - raise ValueError('Unable to read this file, version %s != 0' % priv[0]) + raise ValueError("Unable to read this file, version %s != 0" % priv[0]) as_ints = map(int, priv[1:6]) key = cls(*as_ints) @@ -501,8 +518,10 @@ def _load_pkcs1_der(cls, keyfile): exp1, exp2, coef = map(int, priv[6:9]) if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef): - log.debug('You have providied a malformed keyfile. Either the exponents' - 'or the coefficient are incorrect.') + log.debug( + "You have providied a malformed keyfile. Either the exponents" + "or the coefficient are incorrect." + ) return key @@ -512,35 +531,36 @@ def _save_pkcs1_der(self): :returns: the DER-encoded private key. :rtype: bytes """ - + # pylint: disable=import-outside-toplevel from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence): """Creates PKCS#1 DER Formatted AsnPrivKey""" + componentType = namedtype.NamedTypes( - namedtype.NamedType('version', univ.Integer()), - namedtype.NamedType('modulus', univ.Integer()), - namedtype.NamedType('publicExponent', univ.Integer()), - namedtype.NamedType('privateExponent', univ.Integer()), - namedtype.NamedType('prime1', univ.Integer()), - namedtype.NamedType('prime2', univ.Integer()), - namedtype.NamedType('exponent1', univ.Integer()), - namedtype.NamedType('exponent2', univ.Integer()), - namedtype.NamedType('coefficient', univ.Integer()), + namedtype.NamedType("version", univ.Integer()), + namedtype.NamedType("modulus", univ.Integer()), + namedtype.NamedType("publicExponent", univ.Integer()), + namedtype.NamedType("privateExponent", univ.Integer()), + namedtype.NamedType("prime1", univ.Integer()), + namedtype.NamedType("prime2", univ.Integer()), + namedtype.NamedType("exponent1", univ.Integer()), + namedtype.NamedType("exponent2", univ.Integer()), + namedtype.NamedType("coefficient", univ.Integer()), ) # Create the ASN object asn_key = AsnPrivKey() - asn_key.setComponentByName('version', 0) - asn_key.setComponentByName('modulus', self.n) - asn_key.setComponentByName('publicExponent', self.e) - asn_key.setComponentByName('privateExponent', self.d) - asn_key.setComponentByName('prime1', self.p) - asn_key.setComponentByName('prime2', self.q) - asn_key.setComponentByName('exponent1', self.exp1) - asn_key.setComponentByName('exponent2', self.exp2) - asn_key.setComponentByName('coefficient', self.coef) + asn_key.setComponentByName("version", 0) + asn_key.setComponentByName("modulus", self.n) + asn_key.setComponentByName("publicExponent", self.e) + asn_key.setComponentByName("privateExponent", self.d) + asn_key.setComponentByName("prime1", self.p) + asn_key.setComponentByName("prime2", self.q) + asn_key.setComponentByName("exponent1", self.exp1) + asn_key.setComponentByName("exponent2", self.exp2) + asn_key.setComponentByName("coefficient", self.coef) return encoder.encode(asn_key) @@ -557,7 +577,7 @@ def _load_pkcs1_pem(cls, keyfile): :return: a PrivateKey object """ - der = adafruit_rsa.pem.load_pem(keyfile, b'RSA PRIVATE KEY') + der = adafruit_rsa.pem.load_pem(keyfile, b"RSA PRIVATE KEY") return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self): @@ -568,7 +588,7 @@ def _save_pkcs1_pem(self): """ der = self._save_pkcs1_der() - return adafruit_rsa.pem.save_pem(der, b'RSA PRIVATE KEY') + return adafruit_rsa.pem.save_pem(der, b"RSA PRIVATE KEY") def find_p_q(nbits, getprime_func=adafruit_rsa.prime.getprime, accurate=True): @@ -611,9 +631,9 @@ def find_p_q(nbits, getprime_func=adafruit_rsa.prime.getprime, accurate=True): qbits = nbits - shift # Choose the two initial primes - log.debug('find_p_q(%i): Finding p', nbits) + log.debug("find_p_q(%i): Finding p", nbits) p = getprime_func(pbits) - log.debug('find_p_q(%i): Finding q', nbits) + log.debug("find_p_q(%i): Finding q", nbits) q = getprime_func(qbits) def is_acceptable(p, q): @@ -668,13 +688,18 @@ def calculate_keys_custom_exponent(p, q, exponent): d = adafruit_rsa.common.inverse(exponent, phi_n) except adafruit_rsa.common.NotRelativePrimeError as ex: raise adafruit_rsa.common.NotRelativePrimeError( - exponent, phi_n, ex.d, - msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" % - (exponent, phi_n, ex.d)) + exponent, + phi_n, + ex.d, + msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" + % (exponent, phi_n, ex.d), + ) if (exponent * d) % phi_n != 1: - raise ValueError("e (%d) and d (%d) are not mult. inv. modulo " - "phi_n (%d)" % (exponent, d, phi_n)) + raise ValueError( + "e (%d) and d (%d) are not mult. inv. modulo " + "phi_n (%d)" % (exponent, d, phi_n) + ) return exponent, d @@ -720,7 +745,9 @@ def gen_keys(nbits, getprime_func, accurate=True, exponent=DEFAULT_EXPONENT): return p, q, e, d -def newkeys(nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT, log_level="INFO"): +def newkeys( + nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT, log_level="INFO" +): """Generates public and private keys, and returns them as (pub, priv). The public key is also known as the 'encryption key', and is a @@ -748,10 +775,10 @@ def newkeys(nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT, log_lev """ if nbits < 16: - raise ValueError('Key too small') + raise ValueError("Key too small") if poolsize < 1: - raise ValueError('Pool size (%i) should be >= 1' % poolsize) + raise ValueError("Pool size (%i) should be >= 1" % poolsize) if log_level == "DEBUG": log.setLevel(logging.DEBUG) @@ -764,10 +791,7 @@ def newkeys(nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT, log_lev # Create the key objects n = p * q - return ( - PublicKey(n, e), - PrivateKey(n, e, d, p, q) - ) + return (PublicKey(n, e), PrivateKey(n, e, d, p, q)) -__all__ = ['PublicKey', 'PrivateKey', 'newkeys'] +__all__ = ["PublicKey", "PrivateKey", "newkeys"] diff --git a/adafruit_rsa/machine_size.py b/adafruit_rsa/machine_size.py index fa4f4a8..3d50353 100755 --- a/adafruit_rsa/machine_size.py +++ b/adafruit_rsa/machine_size.py @@ -38,8 +38,7 @@ MACHINE_WORD_SIZE = 64 -def get_word_alignment(num, force_arch=64, - _machine_word_size=MACHINE_WORD_SIZE): +def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE): """ Returns alignment details for the given number based on the platform Python is running on. @@ -58,10 +57,10 @@ def get_word_alignment(num, force_arch=64, (word_bits, word_bytes, max_uint, packing_format_type) """ - max_uint64 = 0xffffffffffffffff - max_uint32 = 0xffffffff - max_uint16 = 0xffff - max_uint8 = 0xff + max_uint64 = 0xFFFFFFFFFFFFFFFF + max_uint32 = 0xFFFFFFFF + max_uint16 = 0xFFFF + max_uint8 = 0xFF if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32: # 64-bit unsigned integer. diff --git a/adafruit_rsa/pem.py b/adafruit_rsa/pem.py index 810cb25..b43d450 100755 --- a/adafruit_rsa/pem.py +++ b/adafruit_rsa/pem.py @@ -16,22 +16,26 @@ """Functions that load and write PEM-encoded files.""" from adafruit_binascii import a2b_base64, b2a_base64 + # pylint: disable=redefined-builtin -from adafruit_rsa._compat import is_bytes, range +from adafruit_rsa._compat import is_bytes __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + def _markers(pem_marker): """ Returns the start and end PEM markers, as bytes. """ if not is_bytes(pem_marker): - pem_marker = pem_marker.encode('ascii') + pem_marker = pem_marker.encode("ascii") - return (b'-----BEGIN ' + pem_marker + b'-----', - b'-----END ' + pem_marker + b'-----') + return ( + b"-----BEGIN " + pem_marker + b"-----", + b"-----END " + pem_marker + b"-----", + ) def load_pem(contents, pem_marker): @@ -51,14 +55,14 @@ def load_pem(contents, pem_marker): # We want bytes, not text. If it's text, it can be converted to ASCII bytes. if not is_bytes(contents): - contents = contents.encode('ascii') + contents = contents.encode("ascii") (pem_start, pem_end) = _markers(pem_marker) pem_lines = [] in_pem_part = False - for line in contents.split(b'\n'): + for line in contents.split(b"\n"): line = line.strip() # Skip empty lines @@ -83,7 +87,7 @@ def load_pem(contents, pem_marker): break # Load fields - if b':' in line: + if b":" in line: continue pem_lines.append(line) @@ -96,7 +100,7 @@ def load_pem(contents, pem_marker): raise ValueError('No PEM end marker "%s" found' % pem_end) # Base64-decode the contents - pem = b''.join(pem_lines) + pem = b"".join(pem_lines) return a2b_base64(pem) @@ -114,14 +118,14 @@ def save_pem(contents, pem_marker): (pem_start, pem_end) = _markers(pem_marker) - b64 = b2a_base64(contents).replace(b'\n', b'') + b64 = b2a_base64(contents).replace(b"\n", b"") pem_lines = [pem_start] for block_start in range(0, len(b64), 64): - block = b64[block_start:block_start + 64] + block = b64[block_start : block_start + 64] pem_lines.append(block) pem_lines.append(pem_end) - pem_lines.append(b'') + pem_lines.append(b"") - return b'\n'.join(pem_lines) + return b"\n".join(pem_lines) diff --git a/adafruit_rsa/pkcs1.py b/adafruit_rsa/pkcs1.py index ab9f3ab..24df3cc 100755 --- a/adafruit_rsa/pkcs1.py +++ b/adafruit_rsa/pkcs1.py @@ -38,10 +38,10 @@ HASH_ASN1 = { "MD5": b"\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10", "SHA-1": b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14", - "SHA-224": b'\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c', + "SHA-224": b"\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c", "SHA-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20", - 'SHA-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30', - 'SHA-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40', + "SHA-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30", + "SHA-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40", } HASH_METHODS = { diff --git a/adafruit_rsa/prime.py b/adafruit_rsa/prime.py index 2c74242..59c48f1 100755 --- a/adafruit_rsa/prime.py +++ b/adafruit_rsa/prime.py @@ -19,15 +19,14 @@ Implementation based on the book Algorithm Design by Michael T. Goodrich and Roberto Tamassia, 2002. """ -# pylint: disable=redefined-builtin, invalid-name -from adafruit_rsa._compat import range +# pylint: disable=invalid-name import adafruit_rsa.common import adafruit_rsa.randnum __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" -__all__ = ['getprime', 'are_relatively_prime'] +__all__ = ["getprime", "are_relatively_prime"] def gcd(p, q): @@ -104,7 +103,7 @@ def miller_rabin_primality_testing(n, k): x = adafruit_rsa.core.fast_pow(a, d, n) - if x in (1, n-1): + if x in (1, n - 1): continue for _ in range(r - 1): @@ -120,6 +119,7 @@ def miller_rabin_primality_testing(n, k): return False return True + def pow_mod(x, y, z): "Calculate (x ** y) % z efficiently." number = 1 @@ -130,6 +130,7 @@ def pow_mod(x, y, z): x = x * x % z return number + def is_prime(number): """Returns True if the number is prime, and False otherwise. diff --git a/adafruit_rsa/randnum.py b/adafruit_rsa/randnum.py index f4c19c5..255e67a 100755 --- a/adafruit_rsa/randnum.py +++ b/adafruit_rsa/randnum.py @@ -26,6 +26,7 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + def read_random_bits(nbits): """Reads 'nbits' random bits. @@ -41,7 +42,7 @@ def read_random_bits(nbits): # Add the remaining random bits if rbits > 0: randomvalue = ord(os.urandom(1)) - randomvalue >>= (8 - rbits) + randomvalue >>= 8 - rbits randomdata = byte(randomvalue) + randomdata return randomdata diff --git a/adafruit_rsa/transform.py b/adafruit_rsa/transform.py index c0a41da..922a1ab 100755 --- a/adafruit_rsa/transform.py +++ b/adafruit_rsa/transform.py @@ -30,6 +30,7 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" + def bytes2int(raw_bytes): """Converts a list of bytes or an 8-bit string to an integer. @@ -76,16 +77,17 @@ def _int2bytes(number, block_size=None): # Type checking if not is_integer(number): - raise TypeError("You must pass an integer for 'number', not %s" % - number.__class__) + raise TypeError( + "You must pass an integer for 'number', not %s" % number.__class__ + ) if number < 0: - raise ValueError('Negative numbers cannot be used: %i' % number) + raise ValueError("Negative numbers cannot be used: %i" % number) # Do some bounds checking if number == 0: needed_bytes = 1 - raw_bytes = [b'\x00'] + raw_bytes = [b"\x00"] else: needed_bytes = common.byte_size(number) raw_bytes = [] @@ -93,8 +95,10 @@ def _int2bytes(number, block_size=None): # You cannot compare None > 0 in Python 3x. It will fail with a TypeError. if block_size and block_size > 0: if needed_bytes > block_size: - raise OverflowError('Needed %i bytes for number, but block size ' - 'is %i' % (needed_bytes, block_size)) + raise OverflowError( + "Needed %i bytes for number, but block size " + "is %i" % (needed_bytes, block_size) + ) # Convert the number to bytes. while number > 0: @@ -103,14 +107,14 @@ def _int2bytes(number, block_size=None): # Pad with zeroes to fill the block if block_size and block_size > 0: - padding = (block_size - needed_bytes) * b'\x00' + padding = (block_size - needed_bytes) * b"\x00" else: - padding = b'' + padding = b"" - return padding + b''.join(raw_bytes) + return padding + b"".join(raw_bytes) -def bytes_leading(raw_bytes, needle=b'\x00'): +def bytes_leading(raw_bytes, needle=b"\x00"): """ Finds the number of prefixed byte occurrences in the haystack. @@ -176,7 +180,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): # Ensure these are integers. assert number & 1 == 0, "Number must be an unsigned integer, not a float." - raw_bytes = b'' + raw_bytes = b"" # Pack the integer one machine word at a time into bytes. num = number @@ -188,7 +192,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): # Obtain the index of the first non-zero byte. zero_leading = bytes_leading(raw_bytes) if number == 0: - raw_bytes = b'\x00' + raw_bytes = b"\x00" # De-padding. raw_bytes = raw_bytes[zero_leading:] @@ -196,8 +200,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False): if fill_size and fill_size > 0: if not overflow and length > fill_size: raise OverflowError( - "Need %d bytes for number, but fill size is %d" % - (length, fill_size) + "Need %d bytes for number, but fill size is %d" % (length, fill_size) ) raw_bytes = "% {}s".format(fill_size).encode() % raw_bytes elif chunk_size and chunk_size > 0: diff --git a/docs/conf.py b/docs/conf.py index cbc92f7..de9e667 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,10 +11,10 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # TODO: Please Read! @@ -23,29 +24,32 @@ autodoc_mock_imports = ["adafruit_logging", "adafruit_binascii", "adafruit_hashlib"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit RSA Library' -copyright = u'2019 Brent Rubell' -author = u'Brent Rubell' +project = "Adafruit RSA Library" +copyright = "2019 Brent Rubell" +author = "Brent Rubell" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -57,7 +61,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -69,7 +73,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -84,59 +88,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitRsaLibrarydoc' +htmlhelp_basename = "AdafruitRsaLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitRSALibrary.tex', u'AdafruitRSA Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitRSALibrary.tex", + "AdafruitRSA Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -144,8 +151,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitRSAlibrary', u'Adafruit RSA Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitRSAlibrary", + "Adafruit RSA Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -154,7 +166,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitRSALibrary', u'Adafruit RSA Library Documentation', - author, 'AdafruitRSALibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitRSALibrary", + "Adafruit RSA Library Documentation", + author, + "AdafruitRSALibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/rsa_sign_verify.py b/examples/rsa_sign_verify.py index d87e719..2838ac6 100755 --- a/examples/rsa_sign_verify.py +++ b/examples/rsa_sign_verify.py @@ -10,7 +10,7 @@ (public_key, private_key) = adafruit_rsa.newkeys(496) # Create a new secret message -message = 'Meet me at 6pm' +message = "Meet me at 6pm" # Hash the message using SHA-224 hash_method = "SHA-256" @@ -18,4 +18,6 @@ # Verify Message Signature if adafruit_rsa.verify(message, signature, public_key) != hash_method: - raise ValueError("Verification failed - signature does not match secret message sent!") + raise ValueError( + "Verification failed - signature does not match secret message sent!" + ) diff --git a/examples/rsa_tests.py b/examples/rsa_tests.py index c8c118d..ab615e1 100755 --- a/examples/rsa_tests.py +++ b/examples/rsa_tests.py @@ -3,6 +3,7 @@ import time import adafruit_rsa + def test_encrypt_decrypt(): # Generate general purpose keys (pub, priv) = adafruit_rsa.newkeys(256, log_level="DEBUG") @@ -26,6 +27,7 @@ def test_mod_msg(): except adafruit_rsa.pkcs1.DecryptionError: pass + # pylint: disable=unused-variable def test_randomness(): """Encrypt msg 2x yields diff. encrypted values. @@ -95,8 +97,10 @@ def test_sign_verify_fail(): start_time = time.monotonic() # pylint: disable=consider-using-enumerate for test_num, test_name in enumerate(all_tests, start=0): -#for i in range(0, len(all_tests)): + # for i in range(0, len(all_tests)): print("Testing: {}".format(test_name)) all_tests[test_num]() print("OK!") -print("Ran {} tests in {} seconds".format(len(all_tests), time.monotonic() - start_time)) +print( + "Ran {} tests in {} seconds".format(len(all_tests), time.monotonic() - start_time) +) diff --git a/setup.py b/setup.py index 0ded9dc..c15a3cd 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ """ from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -13,51 +14,40 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-rsa', - + name="adafruit-circuitpython-rsa", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='RSA implementation based on python-rsa', + setup_requires=["setuptools_scm"], + description="RSA implementation based on python-rsa", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_RSA', - + url="https://github.com/adafruit/Adafruit_CircuitPython_RSA", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=[ - 'Adafruit-Blinka' - ], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit blinka circuitpython micropython rsa rsa, encryption, cryptography', - + keywords="adafruit blinka circuitpython micropython rsa rsa, encryption, cryptography", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=['adafruit_rsa'], + py_modules=["adafruit_rsa"], ) diff --git a/util/decode_priv_key.py b/util/decode_priv_key.py index 93d0354..2ef5c9d 100644 --- a/util/decode_priv_key.py +++ b/util/decode_priv_key.py @@ -45,12 +45,10 @@ import rsa # Generate private and public RSA keys -proc = subprocess.Popen( - ["openssl", "genrsa", "-out", "rsa_private.pem", "2048"]) +proc = subprocess.Popen(["openssl", "genrsa", "-out", "rsa_private.pem", "2048"]) proc.wait() proc = subprocess.Popen( - ["openssl", "rsa", "-in", "rsa_private.pem", - "-pubout", "-out", "rsa_public.pem"] + ["openssl", "rsa", "-in", "rsa_private.pem", "-pubout", "-out", "rsa_public.pem"] ) proc.wait() @@ -63,4 +61,4 @@ pk = rsa.PrivateKey.load_pkcs1(private_key) print("Copy and paste this into your secrets.py file:\n") -print("\"private_key\": " + str(pk)[10:] + ",") +print('"private_key": ' + str(pk)[10:] + ",") From a71ae0360b3ec912214b44481903212d67ab4b2c Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 16 Mar 2020 17:08:41 -0400 Subject: [PATCH 2/2] Fixed build.yml --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint