Skip to content

Commit

Permalink
Some PEP8/pyflakes love
Browse files Browse the repository at this point in the history
  • Loading branch information
nmaier committed Jan 6, 2013
1 parent ecf5536 commit dffe776
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 31 deletions.
9 changes: 7 additions & 2 deletions scripts/xpisign
Expand Up @@ -8,6 +8,7 @@ from optparse import OptionParser

from xpisign import xpisign, BytesIO, __version__


def main(args):
global smime_pkcs7_der_sign

Expand All @@ -23,7 +24,9 @@ def main(args):
dest="force",
action="store_true",
default=False,
help="Force signing, i.e. overwrite outfile if it already exists"
help=("Force signing, i.e. "
"overwrite outfile if it already exists"
)
)
optparse.add_option("-p",
"--plain",
Expand All @@ -36,7 +39,9 @@ def main(args):
"--signer",
dest="signer",
default=None,
help="Force signing with a particular implementation (m2, openssl)"
help=("Force signing with a particular implementation "
"(m2, openssl)"
)
)
optparse.add_option("-v",
"--version",
Expand Down
20 changes: 9 additions & 11 deletions xpisign/api.py
Expand Up @@ -33,8 +33,6 @@

import os
import re
import warnings
import zlib

from base64 import b64encode as base64
from hashlib import md5, sha1
Expand All @@ -47,7 +45,8 @@

__all__ = ["xpisign", "__version__"]
__version__ = "2.0.1"
__versioninfo__ = "xpisign.py (version: %s; https://github.com/nmaier/xpisign.py)" % __version__
__website__ = "https://github.com/nmaier/xpisign.py"
__versioninfo__ = "xpisign.py (version: %s; %s)" % (__version__, __website__)

RE_ALREADY_COMPRESSED = re.compile(".(png|xpt)$", re.I)
RE_ARCHIVES = re.compile("\.(jar|zip)$", re.I)
Expand All @@ -62,12 +61,13 @@ class Digests(object):

@property
def __manifest_version(self):
return "Manifest-Version: 1.0\nCreated-By: %s; %s\n" % (__versioninfo__, self.signer.generator)
vals = __versioninfo__, self.signer.generator
return "Manifest-Version: 1.0\nCreated-By: %s; %s\n" % vals

@property
def __signature_version(self):
return "Signature-Version: 1.0\nCreated-By: %s; %s\n" % (__versioninfo__, self.signer.generator)

vals = __versioninfo__, self.signer.generator
return "Signature-Version: 1.0\nCreated-By: %s; %s\n" % vals

def __init__(self, signer, keyfile, algos=["MD5", "SHA1"]):
self.signer = signer
Expand Down Expand Up @@ -154,7 +154,7 @@ def maybe_optimize_inner_archive(name, content):
rv = BytesIO()
with StreamPositionRestore(rv):
with ZipFile(rv, "w", ZIP_STORED) as zp:
for i,c in files:
for i, c in files:
zp.writestr(i, c)
return name, rv.read()

Expand Down Expand Up @@ -200,7 +200,7 @@ def xpisign(xpifile,
return xpisign(zp,
keyfile,
outfile,
optimize_signature,
optimize_signatures,
optimize_compression,
signer
)
Expand Down Expand Up @@ -230,14 +230,13 @@ def xpisign(xpifile,
if not signer:
raise RuntimeError("Signing algorithm is not available on this system")


# read file list and contents, skipping any existing meta files
with StreamPositionRestore(xpifile):
with ZipFile(xpifile, "r") as xp:
files = [maybe_optimize_inner_archive(n, xp.read(n))
for n in sorted(xp.namelist(), key=file_key)
if not RE_META.match(n) and not RE_DIRECTORY.search(n)
]
]

# generate all digests
dkw = {"signer": signer,
Expand Down Expand Up @@ -267,4 +266,3 @@ def xpisign(xpifile,
zp.writestr(name, content, ZIP_DEFLATED)

return outfile

14 changes: 11 additions & 3 deletions xpisign/compat.py
@@ -1,15 +1,21 @@
import zipfile

try:
from io import BytesIO
import io
BytesIO = io.BytesIO
except ImportError:
_BytesIO = None
try:
from cStringIO import cStringIO as _BytesIO
import cStringIO
_BytesIO = cStringIO.cStringIO
except ImportError:
from StringIO import StringIO as _BytesIO
import StringIO
_BytesIO = StringIO.StringIO

class BytesIO(_BytesIO):
def __enter__(self):
return self

def __exit__(self, type, value, traceback):
self.close()

Expand All @@ -21,8 +27,10 @@ def __exit__(self, type, value, traceback):
class ZipFile(zipfile.ZipFile):
def __enter__(self):
return self

def __exit__(self, type, value, traceback):
self.close()

def writestr(self, info, bytes, compression=None):
if compression is not None:
_compression = self.compression
Expand Down
2 changes: 1 addition & 1 deletion xpisign/context.py
@@ -1,5 +1,6 @@
import zlib


class StreamPositionRestore(object):
'''Stream position restore contextmanager helper'''

Expand Down Expand Up @@ -45,4 +46,3 @@ def __exit__(self, type, value, traceback):
if self.__minor_compression:
zlib.compressobj = self.__orig_compressobj
return False

33 changes: 19 additions & 14 deletions xpisign/crypto.py
Expand Up @@ -4,13 +4,14 @@
import re
import warnings

from .compat import BytesIO

RE_KEY = re.compile(r"-----BEGIN ((ENCRYPTED|RSA) )?PRIVATE KEY-----.+?-----END ((ENCRYPTED|RSA) )?PRIVATE KEY-----", re.S)
RE_CERTS = re.compile(r'-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----', re.S)
RE_KEY = re.compile("-----BEGIN ((ENCRYPTED|RSA) )?PRIVATE KEY-----"
".+?-----END ((ENCRYPTED|RSA) )?PRIVATE KEY-----", re.S)
RE_CERTS = re.compile("-----BEGIN CERTIFICATE-----"
".+?-----END CERTIFICATE-----", re.S)

__all__ = ["sign_m2", "sign_openssl", "sign"]


def parse_keyfile(keyfile):
"""
Parse a keyfile into private key, signing cert and CA stack
Expand All @@ -31,22 +32,21 @@ def parse_keyfile(keyfile):
from tempfile import NamedTemporaryFile
from functools import wraps


try:
check_output = subprocess.check_output
except AttributeError:
def check_output(*args, **kw):
kw["stdout"] = subprocess.PIPE
return subprocess.Popen(*args, **kw).communicate()[0]


def find_executable(name):
"""
Find an executable in path
See which(1)
"""

is_windows = os.name != "nt"

def check(path):
return (os.path.isfile(path) and
(not is_windows or os.access(path, os.X_OK)))
Expand All @@ -68,7 +68,6 @@ def check(path):
if not openssl:
raise ImportError("Failed to find openssl executable")


def sign_openssl(keyfile, content):
"""
Sign content with a keyfile using OpenSSL (and various tmp files :p)
Expand Down Expand Up @@ -96,10 +95,17 @@ def sign_openssl(keyfile, content):

@wraps(sign_openssl)
def sign_openssl_warn(*args, **kw):
warnings.warn("Using openssl (%s) compatibilty layer due to lack of M2Crypto. This will produce slightly larger signatures, as the CA root certificate will be included." % (openssl,), RuntimeWarning)
warnings.warn("Using openssl (%s) compatibilty layer due to lack "
"of M2Crypto. This will produce slightly larger "
"signatures, as the CA root certificate will be "
"included." % (openssl,),
RuntimeWarning
)
return sign_openssl(*args, **kw)

sign_openssl_warn.generator = sign_openssl.generator = check_output((openssl, "version")).strip()
sign_openssl_warn.generator = \
sign_openssl.generator = \
check_output((openssl, "version")).strip()

except ImportError:
sign_openssl_warn = sign_openssl = None
Expand All @@ -111,7 +117,6 @@ def sign_openssl_warn(*args, **kw):
from M2Crypto.BIO import MemoryBuffer as M2Buffer
from M2Crypto.EVP import EVPError as M2EVPError


def sign_m2(keyfile, content):
"""
Sign content with a keyfile using M2Crypto
Expand All @@ -125,7 +130,7 @@ def sign_m2(keyfile, content):
cert = M2X509.load_cert_string(c)
# skip the main CA cert, as this must be built-in anyway
if (cert.check_ca()
and str(cert.get_issuer()) == str(cert.get_subject())):
and str(cert.get_issuer()) == str(cert.get_subject())):
continue
stack.push(cert)

Expand All @@ -145,12 +150,12 @@ def sign_m2(keyfile, content):
raise ValueError("Key file does not contain a private key")
raise ValueError("Signing failed. Wrong password?")

sign_m2.generator = "M2Crypto %s" % M2.version
sign_m2.generator = "M2Crypto %s" % M2.version

except ImportError:
sign_m2 = None

sign = sign_m2 or sign_openssl_warn
if not sign:
raise ImportError("No signing implementation available! Either install M2Crypto or add openssl to your $PATH")

raise ImportError("No signing implementation available! Either install "
"M2Crypto or add openssl to your $PATH")

0 comments on commit dffe776

Please sign in to comment.