Files
roytam1 688c3af674 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1235021 - Re-emit ChromeManifestEntries from the jar manifest handler code in the FasterMake backend. r=gps (a8d899a6da)
- Bug 1233282 - Make CONFIGURE_DEFINE_FILES considered more as GENERATED_FILES in the emitter. r=gps (d29506fb55)
- Bug 1235021 - Add a RenamedSourcePath helper class. r=gps (62e78b867b)
- Bug 1235021 - Re-emit FinalTarget{,Preprocessed}Files from the jar manifest handler code in the FasterMake backend. r=gps (c37287a5d7)
- Bug 1235021 - Avoid passing defines to FasterMakeBackend._consume_jar_manifest. r=gps (dc0d17c3a6)
- Bug 1235021 - Move FasterMakeBackend._consume_jar_manifest to CommonBackend. r=gps (b9bb6b7d1e)
- Bug 1239217 - Add the notion of Partial and Hybrid build backends. r=gps Make the FasterMake backend a partial build backend. (219c0811e6)
- Bug 1239217 - Stop making the FasterMake build system refresh the backend on its own. r=gps (4f79f966ce)
- Bug 1241398 - Show the diff for created and deleted files in `mach build-backend --diff`. r=gps (d497d3aef8)
- Bug 1214885 - Add a "ChromeUrl" build backend to write out information useful for resolving chrome urls. r=glandium (83ad13d109)
- Bug 1216817 - Part 1: Add install_callback to artifacts. r=gps (95b4860d09)
- Bug 1216817 - Part 2: Narrow distdir to bindir in artifacts. r=gps (e48b531455)
- Bug 1216817 - Part 4: Add --enable-artifact-builds and MOZ_ARTIFACT_BUILDS. r=glandium (8d7ed76621)
- bug 1164816 - Import concurrent.futures into the tree. r=gps (bc83211833)
- bug 1190603 - import PyECC library r=gps,gerv (e0c5afeee0)
- Bug 1216817 - Part 5: Run |mach artifact install| automatically when asked. r=glandium (835c27d9c2)
- Bug 1216817 - Follow-up: Fix "KeyError: uMOZ_ARTIFACT_BUILDS" in config.status. r=bustage (e87e04e23b)
- Bug 1216817 - Follow-up: Fix "KeyError: u'MOZ_ARTIFACT_BUILDS'". r=bustage (797331293b)
- Bug 1207897 - Add a configure option to build multiple build backends. r=gps (35f62c27ca)
- Bug 1241398 - Allow to pass the --verbose flag down to config.status from `mach build-backend`. r=gps (78610c40d0)
- Bug 1236111 - part 1: avoid configure.in Windows-only goop when running with disable-compile-environment, r=gps (d27a7e522a)
- Bug 1236111 - part 2: fix mozbuild to use the file mode modifiers specified for opening when writing a FileAvoidWrite, r=gps,nalexander (e240c613b7)
- Bug 1207890 - Part 1: Add rich ArtifactJob extension point. r=glandium (e402f5fcec)
- Bug 1207890 - Part 2: Stop extracting build ID from artifacts. r=glandium (314d6895c1)
- Bug 1207890 - Part 3: Post-process downloaded artifacts. r=glandium (09d60ac030)
- Bug 1207890 - Part 4: Download and process Mac OS X artifacts. r=glandium (181ba370b1)
- Bug 1207890 - Pre: Make JarWriter handle inputs with read() but not seek(). r=glandium (6ebb5dfe94)
- Bug 1207890 - Post: Hacks to make --disable-compile-environment work on Mac OS X. r=glandium (c5f88b6adf)
- Bug 1207890 - Post: Move |mach artifact| command out of mobile/android. r=glandium (a06f97dfb9)
- Bug 1207890 - Post: Hack to make |mach run| for Mac OS X artifact builds. r=me (4c6d2f6bfe)
- Bug 1207890 - Follow-up: Fix |mach artifact install| for mobile/android. r=me (a2e4347ca9)
- Bug 1236111 - part 3: ensure calls to hg and mach work on Windows, and that we use the right file mode when writing artifacts, r=nalexander,gps (d0090a5a56)
- Bug 1236111 - part 4: actually add Windows support to artifact code, r=nalexander,gps (ab40057ffa)
- Bug 1236111 - part 0: improve logging from process mixin, r=gps (d85265c134)
- Bug 1241398 - Add a dry-run mode to mach build-backend. r=gps (b300169915)
- Bug 1239217 - Make the RecursiveMake build system create backend files generically. r=gps (fba90d6bcb)
- fix minor misspatch of 1240990 (b7d44692bc)
- Bug 1239296 - Use telemetry_handler to store build resource data r=gps (58d7c3a260)
- Bug 1244143 - Record whether or not an artifact build was used in build telemetry data r=gps (d1821d1987)
- Bug 1246264 - Ensure cache directory exists for artifacts installation r=chmanchester (ef5c4a0fba)
- bug 1237619: save resource usage for "what" builds r=gps (6a311c71bc)
- Bug 1239296 - Add telemetry_handler function to mach context r=gps (4a7a67740d)
- Bug 1246402 - Environment variable to disable mercurial setup check. r=gps (d9cf129b6c)
- Bug 1239296 - add post_dispatch_handler hook to mach r=gps (aa55c9a36e)
- Bug 1236110 - Extend mach artifact to handle Linux Desktop builds. r=gps (cb29ca6d1d)
- Bug 1234912 - Check for mozext and pushlog entries after |mach artifact install| hg failure. r=gps (7bfb064c7c)
- Bug 1239096 - Improve English is artifacts.py comments. r=me (38aa5ecb19)
- Bug 1238320 - Part 1 (Linux): Download test binaries necessary to run xpcshell tests and mochitests in artifact builds. r=nalexander (f6407791ae)
- Bug 1238320 - Part 2 (Mac): Download test binaries necessary to run xpcshell tests and mochitests in artifact builds. r=nalexander (4d72cfc6f2)
- Bug 1238320 - Part 3 (Windows): Download test binaries necessary to run xpcshell tests and mochitests in artifact builds. r=nalexander# Please enter the commit message for your changes. Lines starting (40ac9f9f7d)
- Bug 1239678 - fix dll inclusion pattern on Windows and the placement of nested dlls like browsercomps and clearkey, r=nalexander (ad9015c9d9)
- Bug 1239738 - Handle artifact builds with no test binaries cleanly. r=ahunt (ba1593837a)
- Bug 1240323 - Fix installation of binary components in a subdir of dist/bin for linux artifact builds. r=nalexander (2f4b719ea3)
- Bug 1240239 - Install test plugins in artifact based builds. r=nalexander (edc24f4fd2)
- Bug 1240667 - Detect a tree to use for artifact builds based on recent changesets. r=nalexander (947879cb19)
- Bug 1244941 - Don't fill install manifest with artifacts. r=nalexander (8fa9793c53)
- Bug 1237619: Record build objects in resource_usage.json r=gps (c323d21c9f)
- bug 1237619: Add system and command metadata to resouce_usage.json r=gps (c93fb18c37)
- Bug 1240059 - Treat psutil as optional in record_resource_usage. r=gps (c91103ebce)
- Bug 1244160 - Create json-schema for build telemetry data r=gps (d8b3419cfd)
- Bug 1250624 - Overall system resources is displayed twice; r=chmanchester (a115c86902)
- Bug 1144842 (part 1) - Don't use MOZ_PROFILING before all the places it can be set. r=glandium. (3c12a2e29a)
- Bug 1144842 (part 2) - Make --enable-dmd imply --enable-profiling. r=glandium. (85c9ff5c32)
- Bug 1144842 (part 3) - Remove --enable-dmd code from js/src/configure.in. r=glandium. (52cf663bc7)
- Bug 1204260 - Pre: Don't expose ANDROID_{BUILD,PLATFORM}_TOOLS. r=glandium,gbrown (d4f560dd46)
- Bug 1219803 - Support 'mach run' for Android; r=jmaher (5a1a1ab16e)
- Bug 1219807 - Add tooltool manifests for jimdb; r=jmaher (4d7a211569)
- Bug 1221846 - Get Task Tracer building on desktop r=cyu. (5d1a0fabe9)
- Bug 1216681 - Add a fileid utility to extract the breakpad GUID from object files for identification in fix_stack_using_bpsyms. r=ted (e53eb5acc6)
- Bug 1237156 - Only build the fileid utility when MOZ_CRASHREPORTER is set. r=ted.mielczarek (328a80ae18)
- Bug 1239866 - Remove signaling standalone tests. r=bwc (b05b091059)
2023-09-27 11:04:31 +08:00

321 lines
12 KiB
Python

# ====================================================================
#
# ELLIPTIC CURVE KEY ENCAPSULATION
# Version 2011-01-26
#
# Copyright (c) 2010 - 2011 | Toni Mattis
#
# ====================================================================
"""
== Elliptic Curve Key Encapsulation ==
Keypairs
--------
Keypairs are generated using: Key.generate(bits)
The number of bits is tied to the NIST-proposed elliptic curves
and has to be 192, 224, 256, 384 or 521 (not 512!).
The result is a Key object containing public and private key.
private() is a method for checking whether the Key object is a
pure public key or also includes the private part.
Exchange
--------
Public keys have to be exported using the export()-Method without
passing an argument. The result is a string which can be safely
transmitted.
Using Key.decode(<encoded key>) the receiver obtains a new
public Key object of the sender.
Storage
-------
For storing a key, export(True) exports both private and public
key as a string. Make sure this information is properly encrypted
when stored.
Key.decode(<encoded key>) obtains the full Key object from the
encoded keypair.
Public Keys
-----------
A public Key object can perform the following cryptographic
operations:
* validate() Checks key integrity, i.e. after loading the
key from a file. Returns True if the key is
valid. Invalid keys should be discarded.
* fingerprint() Returns the public key fingerprint used to
identify the key. Optional arguments:
1. as_hex - True, if output should be formatted
as hexadecimal number (default: True).
2. hashfunc - The official name of the hash
function being used (default: 'sha1')
For supported hash functions see below.
* keyid() Returns a (mostly) unique Key ID, which is
shorter than the fingerprint. The result
is an integer of max. 64 bits.
* verify() Verifies whether the given data (argument 1)
matches the signature (argument 2) issued
by the owner of this key. A falsification
can have multiple causes:
- Data, public key or signature were altered
during transmission/storage.
- The siganture was not issued by the owner
of this key but may be valid with another
key.
- The signature was issued for different data.
- The signature was issued using a different
hash function. Another hash function may work.
Optionally, the name of a hash algorithm
can be provided. For hash names see below.
* encrypt() Encrypts a packet of data destined for the owner
of this key*. After encryption only the holder
of this Key's private part is able to decrypt
the message.
Private Keys / Keypairs
-----------------------
If the key object is private, then it is a keypair consisting of
a public and a private key. Therefore all Public key operations
are supported.
Additional functions:
* sign() Signs given data using this private key. The
result is a signature which can be passed as
argument to the verify() function in addition
to the data being verified.
As additional argument the name of the hash
function can be provided (defaults to 'sha256').
For hash names see below.
* auth_encrypt() Performs authenticated encryption of data
(argument 1) for the holder of the key provided
as second argument. Only the receiver whose
public key is given is able to derypt and verify
the message. The message will be implicitly
signed using the own private key. *
* decrypt() Decrypts a message which has been encrypted
using the public key of this keypair*. If
decryption yields random data, this can have
multiple causes:
- You were not the intended receiver, a different
private key may be able to decrypt it.
- The message was altered.
- Your private key is damaged.
* auth_decrypt() Decrypts a message while verifying whether
it has been authentically issued by the holder
of the given key (argument 2). When
authentication failed, a
SecurityViolationException is thrown. Reasons
for this to happen are those mentioned with
decrypt() and verify(). *
*) The encryption used here depends on the "eccrypt" module imported
by this module. Default implementation should use RABBIT as cipher
and do the asymmetric part using an optimized El-Gamal scheme.
Hash functions
--------------
The following hash functions can be passed at the moment:
name | hash size | security level
| (bits, bytes, hex digits)
---------+------------------------+----------------
'sha1' 160 / 20 / 40 medium
'sha224' 224 / 28 / 56 medium-strong
'sha256' 256 / 32 / 64 strong
'sha384' 384 / 48 / 96 very strong
'sha512' 512 / 64 / 128 very strong
'md5' 128 / 16 / 32 weak (not recommended!)
Curves
------
According to FIPS 186-3, Appendix D.1.2 there are 5 elliptic
curves recommended. All of those are strong, but those with
a higher bit number even stronger.
192 and 224 bits are sufficient for most purposes.
256 bits offer an additional magnitude of security.
(i.e. for classified / strongly confidential data)
384 and 521 bits provide exceptionally strong security. According
to current research they most probably keep this level for
decades in the future.
FIPS also recommends curves over polynomial fields but actually
only prime fields are implemented here. (Because 2^521-1 is a mersenne
prime having great security characteristics, 521 bits are preferred
over a constructed 512 bit field.)
"""
from encoding import *
from eccrypt import *
import ecdsa
import hashlib
from SecurityViolationException import *
class Key:
# --- KEY SETUP ------------------------------------------------------------
def __init__(self, public_key, private_key = None):
'''Create a Key(pair) from numeric keys.'''
self._pub = public_key
self._priv = private_key
self._fingerprint = {}
self._id = None
@staticmethod
def generate(bits):
'''Generate a new ECDSA keypair'''
return Key(*ecdsa.keypair(bits))
# --- BINARY REPRESENTATION ------------------------------------------------
def encode(self, include_private = False):
'''Returns a strict binary representation of this Key'''
e = Encoder().int(self.keyid(), 8)
e.int(self._pub[0], 2).point(self._pub[1], 2)
if include_private and self._priv:
e.long(self._priv[1], 2)
else:
e.long(0, 2)
return e.out()
def compress(self):
'''Returns a compact public key representation'''
@staticmethod
def decode(s):
'''Constructs a new Key object from its binary representation'''
kid, ksize, pub, priv = Decoder(s).int(8).int(2).point(2).long(2).out()
k = Key((ksize, pub), (ksize, priv) if priv else None)
if kid == k.keyid():
return k
else:
raise ValueError, "Invalid Key ID"
# --- IDENTIFICATION AND VALIDATION ----------------------------------------
def private(self):
'''Checks whether Key object contains private key'''
return bool(self._priv)
def validate(self):
'''Checks key validity'''
if ecdsa.validate_public_key(self._pub):
if self._priv: # ? validate and match private key
return ecdsa.validate_private_key(self._priv) and \
ecdsa.match_keys(self._pub, self._priv)
else:
return True # : everything valid
else:
return False
def fingerprint(self, as_hex = True, hashfunc = 'sha1'):
'''Get the public key fingerprint'''
if hashfunc in self._fingerprint:
return self._fingerprint[hashfunc] if not as_hex else \
self._fingerprint[hashfunc].encode("hex")
else:
h = hashlib.new(hashfunc, enc_point(self._pub[1]))
d = h.digest()
self._fingerprint[hashfunc] = d
return d.encode("hex") if as_hex else d
def keyid(self):
'''Get a short, unique identifier'''
if not self._id:
self._id = dec_long(self.fingerprint(False, 'sha1')[:8])
return self._id
# --- DIGITAL SIGNATURES ---------------------------------------------------
def sign(self, data, hashfunc = 'sha256'):
'''Sign data using the specified hash function'''
if self._priv:
h = dec_long(hashlib.new(hashfunc, data).digest())
s = ecdsa.sign(h, self._priv)
return enc_point(s)
else:
raise AttributeError, "Private key needed for signing."
def verify(self, data, sig, hashfunc = 'sha256'):
'''Verify the signature of data using the specified hash function'''
h = dec_long(hashlib.new(hashfunc, data).digest())
s = dec_point(sig)
return ecdsa.verify(h, s, self._pub)
# --- HYBRID ENCRYPTION ----------------------------------------------------
def encrypt(self, data):
'''Encrypt a message using this public key'''
ctext, mkey = encrypt(data, self._pub)
return Encoder().point(mkey).str(ctext, 4).out()
def decrypt(self, data):
'''Decrypt an encrypted message using this private key'''
mkey, ctext = Decoder(data).point().str(4).out()
return decrypt(ctext, mkey, self._priv)
# --- AUTHENTICATED ENCRYPTION ---------------------------------------------
def auth_encrypt(self, data, receiver):
'''Sign and encrypt a message'''
sgn = self.sign(data)
ctext, mkey = encrypt(data, receiver._pub)
return Encoder().point(mkey).str(ctext, 4).str(sgn, 2).out()
def auth_decrypt(self, data, source):
'''Decrypt and verify a message'''
mkey, ctext, sgn = Decoder(data).point().str(4).str(2).out()
text = decrypt(ctext, mkey, self._priv)
if source.verify(text, sgn):
return text
else:
raise SecurityViolationException, "Invalid Signature"
if __name__ == "__main__":
import time
def test_overhead():
print "sender", "receiver", "+bytes", "+enctime", "+dectime"
for s in [192, 224, 256, 384, 521]:
sender = Key.generate(s)
for r in [192, 224, 256, 384, 521]:
receiver = Key.generate(r)
t = time.time()
e = sender.auth_encrypt("", receiver)
t1 = time.time() - t
t = time.time()
receiver.auth_decrypt(e, sender)
t2 = time.time() - t
print s, r, len(e), t1, t2