code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _expand_subject_public_key_info(encoded): """Parse a SubjectPublicKeyInfo structure. It returns a triple with: * OID (string) * encoded public key (bytes) * Algorithm parameters (bytes or None) """ # # SubjectPublicKeyInfo ::= SEQUENCE { # algorithm AlgorithmIdentifier, # subjectPublicKey BIT STRING # } # # AlgorithmIdentifier ::= SEQUENCE { # algorithm OBJECT IDENTIFIER, # parameters ANY DEFINED BY algorithm OPTIONAL # } # spki = DerSequence().decode(encoded, nr_elements=2) algo = DerSequence().decode(spki[0], nr_elements=(1,2)) algo_oid = DerObjectId().decode(algo[0]) spk = DerBitString().decode(spki[1]).value if len(algo) == 1: algo_params = None else: try: DerNull().decode(algo[1]) algo_params = None except: algo_params = algo[1] return algo_oid.value, spk, algo_params
Parse a SubjectPublicKeyInfo structure. It returns a triple with: * OID (string) * encoded public key (bytes) * Algorithm parameters (bytes or None)
_expand_subject_public_key_info
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/PublicKey/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/__init__.py
MIT
def getrandbits(self, k): """Return a python long integer with k random bits.""" if self._randfunc is None: self._randfunc = Random.new().read mask = (1 << k) - 1 return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
Return a python long integer with k random bits.
getrandbits
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Random/random.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Random/random.py
MIT
def randrange(self, *args): """randrange([start,] stop[, step]): Return a randomly-selected element from range(start, stop, step).""" if len(args) == 3: (start, stop, step) = args elif len(args) == 2: (start, stop) = args step = 1 elif len(args) == 1: (stop,) = args start = 0 step = 1 else: raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),)) if (not isinstance(start, (int, long)) or not isinstance(stop, (int, long)) or not isinstance(step, (int, long))): raise TypeError("randrange requires integer arguments") if step == 0: raise ValueError("randrange step argument must not be zero") num_choices = ceil_div(stop - start, step) if num_choices < 0: num_choices = 0 if num_choices < 1: raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step)) # Pick a random number in the range of possible numbers r = num_choices while r >= num_choices: r = self.getrandbits(size(num_choices)) return start + (step * r)
randrange([start,] stop[, step]): Return a randomly-selected element from range(start, stop, step).
randrange
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Random/random.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Random/random.py
MIT
def choice(self, seq): """Return a random element from a (non-empty) sequence. If the seqence is empty, raises IndexError. """ if len(seq) == 0: raise IndexError("empty sequence") return seq[self.randrange(len(seq))]
Return a random element from a (non-empty) sequence. If the seqence is empty, raises IndexError.
choice
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Random/random.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Random/random.py
MIT
def sample(self, population, k): """Return a k-length list of unique elements chosen from the population sequence.""" num_choices = len(population) if k > num_choices: raise ValueError("sample larger than population") retval = [] selected = {} # we emulate a set using a dict here for i in xrange(k): r = None while r is None or selected.has_key(r): r = self.randrange(num_choices) retval.append(population[r]) selected[r] = 1 return retval
Return a k-length list of unique elements chosen from the population sequence.
sample
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Random/random.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Random/random.py
MIT
def load_tests(dir_comps, file_name, description, conversions): """Load and parse a test vector file This function returnis a list of objects, one per group of adjacent KV lines or for a single line in the form "[.*]". For a group of lines, the object has one attribute per line. """ file_in = open(pycryptodome_filename(dir_comps, file_name)) description = "%s test (%s)" % (description, file_name) line_number = 0 results = [] class TestVector(object): def __init__(self, description, count): self.desc = description self.count = count self.others = [] test_vector = None count = 0 new_group = True while True: line_number += 1 line = file_in.readline() if not line: if test_vector is not None: results.append(test_vector) break line = line.strip() # Skip comments and empty lines if line.startswith('#') or not line: new_group = True continue if line.startswith("["): if test_vector is not None: results.append(test_vector) test_vector = None results.append(line) continue if new_group: count += 1 new_group = False if test_vector is not None: results.append(test_vector) test_vector = TestVector("%s (#%d)" % (description, count), count) res = re.match("([A-Za-z0-9]+) = ?(.*)", line) if not res: test_vector.others += [line] else: token = res.group(1).lower() data = res.group(2).lower() conversion = conversions.get(token, None) if conversion is None: if len(data) % 2 != 0: data = "0" + data setattr(test_vector, token, unhexlify(data)) else: setattr(test_vector, token, conversion(data)) # This line is ignored return results
Load and parse a test vector file This function returnis a list of objects, one per group of adjacent KV lines or for a single line in the form "[.*]". For a group of lines, the object has one attribute per line.
load_tests
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/loader.py
MIT
def strip_whitespace(s): """Remove whitespace from a text or byte string""" if isinstance(s,str): return b("".join(s.split())) else: return b("").join(s.split())
Remove whitespace from a text or byte string
strip_whitespace
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/st_common.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/st_common.py
MIT
def run(module=None, verbosity=0, stream=None, tests=None, config=None, **kwargs): """Execute self-tests. This raises SelfTestError if any test is unsuccessful. You may optionally pass in a sub-module of SelfTest if you only want to perform some of the tests. For example, the following would test only the hash modules: Cryptodome.SelfTest.run(Cryptodome.SelfTest.Hash) """ if config is None: config = {} suite = unittest.TestSuite() if module is None: if tests is None: tests = get_tests(config=config) suite.addTests(tests) else: if tests is None: suite.addTests(module.get_tests(config=config)) else: raise ValueError("'module' and 'tests' arguments are mutually exclusive") if stream is None: kwargs['stream'] = StringIO() else: kwargs['stream'] = stream runner = unittest.TextTestRunner(verbosity=verbosity, **kwargs) result = runner.run(suite) if not result.wasSuccessful(): if stream is None: sys.stderr.write(kwargs['stream'].getvalue()) raise SelfTestError("Self-test failed", result) return result
Execute self-tests. This raises SelfTestError if any test is unsuccessful. You may optionally pass in a sub-module of SelfTest if you only want to perform some of the tests. For example, the following would test only the hash modules: Cryptodome.SelfTest.run(Cryptodome.SelfTest.Hash)
run
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/__init__.py
MIT
def _extract(d, k, default=_NoDefault): """Get an item from a dictionary, and remove it from the dictionary.""" try: retval = d[k] except KeyError: if default is _NoDefault: raise return default del d[k] return retval
Get an item from a dictionary, and remove it from the dictionary.
_extract
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/common.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/common.py
MIT
def test_eiter_encrypt_or_decrypt(self): """Verify that a cipher cannot be used for both decrypting and encrypting""" c1 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) c1.encrypt(b("8")) self.assertRaises(TypeError, c1.decrypt, b("9")) c2 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) c2.decrypt(b("8")) self.assertRaises(TypeError, c2.encrypt, b("9"))
Verify that a cipher cannot be used for both decrypting and encrypting
test_eiter_encrypt_or_decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_ChaCha20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_ChaCha20.py
MIT
def test_streaming(self): """Verify that an arbitrary number of bytes can be encrypted/decrypted""" from Cryptodome.Hash import SHA1 segments = (1, 3, 5, 7, 11, 17, 23) total = sum(segments) pt = b("") while len(pt) < total: pt += SHA1.new(pt).digest() cipher1 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) ct = cipher1.encrypt(pt) cipher2 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) cipher3 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) idx = 0 for segment in segments: self.assertEqual(cipher2.decrypt(ct[idx:idx+segment]), pt[idx:idx+segment]) self.assertEqual(cipher3.encrypt(pt[idx:idx+segment]), ct[idx:idx+segment]) idx += segment
Verify that an arbitrary number of bytes can be encrypted/decrypted
test_streaming
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_ChaCha20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_ChaCha20.py
MIT
def rws(t): """Remove white spaces, tabs, and new lines from a string""" for c in ['\n', '\t', ' ']: t = t.replace(c,'') return t
Remove white spaces, tabs, and new lines from a string
rws
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_15.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_15.py
MIT
def t2b(t): """Convert a text string with bytes in hex form to a byte string""" clean = b(rws(t)) if len(clean)%2 == 1: print clean raise ValueError("Even number of characters expected") return a2b_hex(clean)
Convert a text string with bytes in hex form to a byte string
t2b
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_15.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_15.py
MIT
def rws(t): """Remove white spaces, tabs, and new lines from a string""" for c in ['\n', '\t', ' ']: t = t.replace(c,'') return t
Remove white spaces, tabs, and new lines from a string
rws
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_oaep.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_oaep.py
MIT
def t2b(t): """Convert a text string with bytes in hex form to a byte string""" clean = rws(t) if len(clean)%2 == 1: raise ValueError("Even number of characters expected") return a2b_hex(clean)
Convert a text string with bytes in hex form to a byte string
t2b
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_oaep.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Cipher/test_pkcs1_oaep.py
MIT
def __init__(self, hashmods): """Initialize the test with a dictionary of hash modules indexed by their names""" unittest.TestCase.__init__(self) self.hashmods = hashmods self.description = ""
Initialize the test with a dictionary of hash modules indexed by their names
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Hash/test_HMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Hash/test_HMAC.py
MIT
def test2(self): """From draft-josefsson-scrypt-kdf-01, Chapter 10""" output_1 = t2b(""" 55 ac 04 6e 56 e3 08 9f ec 16 91 c2 25 44 b6 05 f9 41 85 21 6d de 04 65 e6 8b 9d 57 c2 0d ac bc 49 ca 9c cc f1 79 b6 45 99 16 64 b3 9d 77 ef 31 7c 71 b8 45 b1 e3 0b d5 09 11 20 41 d3 a1 97 83 """) output_2 = t2b(""" 4d dc d8 f6 0b 98 be 21 83 0c ee 5e f2 27 01 f9 64 1a 44 18 d0 4c 04 14 ae ff 08 87 6b 34 ab 56 a1 d4 25 a1 22 58 33 54 9a db 84 1b 51 c9 b3 17 6a 27 2b de bb a1 d0 78 47 8f 62 b3 97 f3 3c 8d """) prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest() output = PBKDF2(b("passwd"), b("salt"), 64, 1, prf=prf_hmac_sha256) self.assertEqual(output, output_1) output = PBKDF2(b("Password"), b("NaCl"), 64, 80000, prf=prf_hmac_sha256) self.assertEqual(output, output_2)
From draft-josefsson-scrypt-kdf-01, Chapter 10
test2
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_KDF.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_KDF.py
MIT
def test2(self): """Verify that no more than 127(AES) and 63(TDES) components are accepted.""" key = bchr(0) * 8 + bchr(255) * 8 for module in (AES, DES3): s2v = _S2V.new(key, module) max_comps = module.block_size*8-1 for i in xrange(max_comps): s2v.update(b("XX")) self.assertRaises(TypeError, s2v.update, b("YY"))
Verify that no more than 127(AES) and 63(TDES) components are accepted.
test2
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_KDF.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_KDF.py
MIT
def runTest (self): "Check converting English strings to keys" for key, words in test_data: key=binascii.a2b_hex(b(key)) self.assertEqual(RFC1751.english_to_key(words), key)
Check converting English strings to keys
runTest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_rfc1751.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Protocol/test_rfc1751.py
MIT
def _sws(s): """Remove whitespace from a text or byte string""" if isinstance(s,str): return "".join(s.split()) else: return b("").join(s.split())
Remove whitespace from a text or byte string
_sws
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_generate_1arg(self): """DSA (default implementation) generated key (1 argument)""" dsaObj = self.dsa.generate(1024) self._check_private_key(dsaObj) pub = dsaObj.publickey() self._check_public_key(pub)
DSA (default implementation) generated key (1 argument)
test_generate_1arg
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_generate_2arg(self): """DSA (default implementation) generated key (2 arguments)""" dsaObj = self.dsa.generate(1024, Random.new().read) self._check_private_key(dsaObj) pub = dsaObj.publickey() self._check_public_key(pub)
DSA (default implementation) generated key (2 arguments)
test_generate_2arg
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_construct_4tuple(self): """DSA (default implementation) constructed key (4-tuple)""" (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)] dsaObj = self.dsa.construct((y, g, p, q)) self._test_verification(dsaObj)
DSA (default implementation) constructed key (4-tuple)
test_construct_4tuple
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_construct_5tuple(self): """DSA (default implementation) constructed key (5-tuple)""" (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)] dsaObj = self.dsa.construct((y, g, p, q, x)) self._test_signing(dsaObj) self._test_verification(dsaObj)
DSA (default implementation) constructed key (5-tuple)
test_construct_5tuple
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_domain1(self): """Verify we can generate new keys in a given domain""" dsa_key_1 = DSA.generate(1024) domain_params = dsa_key_1.domain() dsa_key_2 = DSA.generate(1024, domain=domain_params) self.assertEqual(dsa_key_1.p, dsa_key_2.p) self.assertEqual(dsa_key_1.q, dsa_key_2.q) self.assertEqual(dsa_key_1.g, dsa_key_2.g) self.assertEqual(dsa_key_1.domain(), dsa_key_2.domain())
Verify we can generate new keys in a given domain
test_domain1
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_generate_error_weak_domain(self): """Verify that domain parameters with composite q are rejected""" domain_params = self._get_weak_domain() self.assertRaises(ValueError, DSA.generate, 1024, domain=domain_params)
Verify that domain parameters with composite q are rejected
test_generate_error_weak_domain
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def test_construct_error_weak_domain(self): """Verify that domain parameters with composite q are rejected""" from Cryptodome.Math.Numbers import Integer p, q, g = self._get_weak_domain() y = pow(g, 89, p) self.assertRaises(ValueError, DSA.construct, (y, g, p, q))
Verify that domain parameters with composite q are rejected
test_construct_error_weak_domain
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_DSA.py
MIT
def convert_tv(self, tv, as_longs=0): """Convert a test vector from textual form (hexadecimal ascii to either integers or byte strings.""" key_comps = 'p','g','y','x' tv2 = {} for c in tv.keys(): tv2[c] = a2b_hex(tv[c]) if as_longs or c in key_comps or c in ('sig1','sig2'): tv2[c] = bytes_to_long(tv2[c]) tv2['key']=[] for c in key_comps: tv2['key'] += [tv2[c]] del tv2[c] return tv2
Convert a test vector from textual form (hexadecimal ascii to either integers or byte strings.
convert_tv
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_ElGamal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_ElGamal.py
MIT
def test_import_key(self): """Verify importKey is an alias to import_key""" key_obj = DSA.import_key(self.der_public) self.failIf(key_obj.has_private()) self.assertEqual(self.y, key_obj.y) self.assertEqual(self.p, key_obj.p) self.assertEqual(self.q, key_obj.q) self.assertEqual(self.g, key_obj.g)
Verify importKey is an alias to import_key
test_import_key
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_DSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_DSA.py
MIT
def testImportKey1(self): """Verify import of RSAPrivateKey DER SEQUENCE""" key = RSA.importKey(self.rsaKeyDER) self.failUnless(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of RSAPrivateKey DER SEQUENCE
testImportKey1
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey2(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE""" key = RSA.importKey(self.rsaPublicKeyDER) self.failIf(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
Verify import of SubjectPublicKeyInfo DER SEQUENCE
testImportKey2
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey3unicode(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode""" key = RSA.importKey(self.rsaKeyPEM) self.assertEqual(key.has_private(),True) # assert_ self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode
testImportKey3unicode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey3bytes(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaKeyPEM)) self.assertEqual(key.has_private(),True) # assert_ self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string
testImportKey3bytes
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey4unicode(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode""" key = RSA.importKey(self.rsaPublicKeyPEM) self.assertEqual(key.has_private(),False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode
testImportKey4unicode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey4bytes(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaPublicKeyPEM)) self.assertEqual(key.has_private(),False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string
testImportKey4bytes
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey5(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyPEM) idem = key._encrypt(key._decrypt(89L)) self.assertEqual(idem, 89L)
Verifies that the imported key is still a valid RSA pair
testImportKey5
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey6(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyDER) idem = key._encrypt(key._decrypt(65L)) self.assertEqual(idem, 65L)
Verifies that the imported key is still a valid RSA pair
testImportKey6
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey7(self): """Verify import of OpenSSH public key""" key = RSA.importKey(self.rsaPublicKeyOpenSSH) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
Verify import of OpenSSH public key
testImportKey7
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey8(self): """Verify import of encrypted PrivateKeyInfo DER SEQUENCE""" for t in self.rsaKeyEncryptedPEM: key = RSA.importKey(t[1], t[0]) self.failUnless(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of encrypted PrivateKeyInfo DER SEQUENCE
testImportKey8
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey9(self): """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE""" key = RSA.importKey(self.rsaKeyDER8) self.failUnless(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of unencrypted PrivateKeyInfo DER SEQUENCE
testImportKey9
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey10(self): """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM""" key = RSA.importKey(self.rsaKeyPEM8) self.failUnless(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM
testImportKey10
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey11(self): """Verify import of RSAPublicKey DER SEQUENCE""" der = asn1.DerSequence([17, 3]).encode() key = RSA.importKey(der) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3)
Verify import of RSAPublicKey DER SEQUENCE
testImportKey11
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def testImportKey12(self): """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM""" der = asn1.DerSequence([17, 3]).encode() pem = der2pem(der) key = RSA.importKey(pem) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3)
Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM
testImportKey12
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def test_import_key(self): """Verify that import_key is an alias to importKey""" key = RSA.import_key(self.rsaPublicKeyDER) self.failIf(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
Verify that import_key is an alias to importKey
test_import_key
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
MIT
def test_generate_1arg(self): """RSA (default implementation) generated key (1 argument)""" rsaObj = self.rsa.generate(1024) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
RSA (default implementation) generated key (1 argument)
test_generate_1arg
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
MIT
def test_generate_2arg(self): """RSA (default implementation) generated key (2 arguments)""" rsaObj = self.rsa.generate(1024, Random.new().read) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
RSA (default implementation) generated key (2 arguments)
test_generate_2arg
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
MIT
def test_construct_5tuple(self): """RSA (default implementation) constructed key (5-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
RSA (default implementation) constructed key (5-tuple)
test_construct_5tuple
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
MIT
def test_construct_6tuple(self): """RSA (default implementation) constructed key (6-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
RSA (default implementation) constructed key (6-tuple)
test_construct_6tuple
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/PublicKey/test_RSA.py
MIT
def test_negative_unapproved_hashes(self): """Verify that unapproved hashes are rejected""" from Cryptodome.Hash import RIPEMD160 self.description = "Unapproved hash (RIPEMD160) test" hash_obj = RIPEMD160.new() signer = DSS.new(self.key_priv, 'fips-186-3') self.assertRaises(ValueError, signer.sign, hash_obj) self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
Verify that unapproved hashes are rejected
test_negative_unapproved_hashes
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
MIT
def test_negative_unknown_modes_encodings(self): """Verify that unknown modes/encodings are rejected""" self.description = "Unknown mode test" self.assertRaises(ValueError, DSS.new, self.key_priv, 'fips-186-0') self.description = "Unknown encoding test" self.assertRaises(ValueError, DSS.new, self.key_priv, 'fips-186-3', 'xml')
Verify that unknown modes/encodings are rejected
test_negative_unknown_modes_encodings
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
MIT
def test_negative_unapproved_hashes(self): """Verify that unapproved hashes are rejected""" from Cryptodome.Hash import SHA1 self.description = "Unapproved hash (SHA-1) test" hash_obj = SHA1.new() signer = DSS.new(self.key_priv, 'fips-186-3') self.assertRaises(ValueError, signer.sign, hash_obj) self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
Verify that unapproved hashes are rejected
test_negative_unapproved_hashes
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/SelfTest/Signature/test_dss.py
MIT
def __init__(self, key, encoding, order): """Create a new Digital Signature Standard (DSS) object. Do not instantiate this object directly, use `Cryptodome.Signature.DSS.new` instead. """ self._key = key self._encoding = encoding self._order = order self._order_bits = self._order.size_in_bits() self._order_bytes = (self._order_bits - 1) // 8 + 1
Create a new Digital Signature Standard (DSS) object. Do not instantiate this object directly, use `Cryptodome.Signature.DSS.new` instead.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/DSS.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/DSS.py
MIT
def sign(self, msg_hash): """Produce the DSS signature of a message. :Parameters: msg_hash : hash object The hash that was carried out over the message. The object belongs to the `Cryptodome.Hash` package. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. :Return: The signature encoded as a byte string. :Raise ValueError: If the hash algorithm is incompatible to the DSA key. :Raise TypeError: If the DSA key has no private half. """ if not self._valid_hash(msg_hash): raise ValueError("Hash is not sufficiently strong") # Generate the nonce k (critical!) nonce = self._compute_nonce(msg_hash) # Perform signature using the raw API z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) sig_pair = self._key._sign(z, nonce) # Encode the signature into a single byte string if self._encoding == 'binary': output = b("").join([long_to_bytes(x, self._order_bytes) for x in sig_pair]) else: # Dss-sig ::= SEQUENCE { # r OCTET STRING, # s OCTET STRING # } output = DerSequence(sig_pair).encode() return output
Produce the DSS signature of a message. :Parameters: msg_hash : hash object The hash that was carried out over the message. The object belongs to the `Cryptodome.Hash` package. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. :Return: The signature encoded as a byte string. :Raise ValueError: If the hash algorithm is incompatible to the DSA key. :Raise TypeError: If the DSA key has no private half.
sign
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/DSS.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/DSS.py
MIT
def verify(self, msg_hash, signature): """Verify that a certain DSS signature is authentic. This function checks if the party holding the private half of the key really signed the message. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. signature : byte string The signature that needs to be validated. :Raise ValueError: If the signature is not authentic. """ if not self._valid_hash(msg_hash): raise ValueError("Hash does not belong to SHS") if self._encoding == 'binary': if len(signature) != (2 * self._order_bytes): raise ValueError("The signature is not authentic (length)") r_prime, s_prime = [Integer.from_bytes(x) for x in (signature[:self._order_bytes], signature[self._order_bytes:])] else: try: der_seq = DerSequence().decode(signature) except (ValueError, IndexError): raise ValueError("The signature is not authentic (DER)") if len(der_seq) != 2 or not der_seq.hasOnlyInts(): raise ValueError("The signature is not authentic (DER content)") r_prime, s_prime = der_seq[0], der_seq[1] if not (0 < r_prime < self._order) or not (0 < s_prime < self._order): raise ValueError("The signature is not authentic (d)") z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) result = self._key._verify(z, (r_prime, s_prime)) if not result: raise ValueError("The signature is not authentic") # Make PyCryptodome code to fail return False
Verify that a certain DSS signature is authentic. This function checks if the party holding the private half of the key really signed the message. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. signature : byte string The signature that needs to be validated. :Raise ValueError: If the signature is not authentic.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/DSS.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/DSS.py
MIT
def _valid_hash(self, msg_hash): """Verify that SHA-[23] (256|384|512) bits are used to match the 128-bit security of P-256""" approved = ("2.16.840.1.101.3.4.2.1", "2.16.840.1.101.3.4.2.2", "2.16.840.1.101.3.4.2.3", "2.16.840.1.101.3.4.2.8", "2.16.840.1.101.3.4.2.9", "2.16.840.1.101.3.4.2.10") return msg_hash.oid in approved
Verify that SHA-[23] (256|384|512) bits are used to match the 128-bit security of P-256
_valid_hash
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/DSS.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/DSS.py
MIT
def new(key, mode, encoding='binary', randfunc=None): """Return a signature scheme object `DSS_SigScheme` that can be used to perform DSS signature or verification. :Parameters: key : a `Cryptodome.PublicKey.DSA` or `Cryptodome.PublicKey.ECC` key object If the key has got its private half, both signature and verification are possible. If it only has the public half, verification is possible but not signature generation. For DSA keys, let *L* and *N* be the bit lengths of the modules *p* and *q*: the combination *(L,N)* must appear in the following list, in compliance to section 4.2 of `FIPS-186`__: - (1024, 160) - (2048, 224) - (2048, 256) - (3072, 256) mode : string The parameter can take these values: - *'fips-186-3'*. The signature generation is carried out according to `FIPS-186`__: the nonce *k* is taken from the RNG. - *'deterministic-rfc6979'*. The signature generation process does not rely on a random generator. See RFC6979_. encoding : string How the signature is encoded. This value determines the output of ``sign`` and the input of ``verify``. The following values are accepted: - *'binary'* (default), the signature is the raw concatenation of *r* and *s*. The size in bytes of the signature is always two times the size of *q*. - *'der'*, the signature is a DER encoded SEQUENCE with two INTEGERs, *r* and *s*. The size of the signature is variable. randfunc : callable The source of randomness. If ``None``, the internal RNG is used. Only used for the *'fips-186-3'* mode. .. __: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf .. __: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf .. _RFC6979: http://tools.ietf.org/html/rfc6979 """ # The goal of the 'mode' parameter is to avoid to # have the current version of the standard as default. # # Over time, such version will be superseded by (for instance) # FIPS 186-4 and it will be odd to have -3 as default. if encoding not in ('binary', 'der'): raise ValueError("Unknown encoding '%s'" % encoding) if isinstance(key, EccKey): order = _curve.order private_key_attr = 'd' else: order = Integer(key.q) private_key_attr = 'x' if key.has_private(): private_key = getattr(key, private_key_attr) else: private_key = None if mode == 'deterministic-rfc6979': return DeterministicDsaSigScheme(key, encoding, order, private_key) elif mode == 'fips-186-3': if isinstance(key, EccKey): return FipsEcDsaSigScheme(key, encoding, order, randfunc) else: return FipsDsaSigScheme(key, encoding, order, randfunc) else: raise ValueError("Unknown DSS mode '%s'" % mode)
Return a signature scheme object `DSS_SigScheme` that can be used to perform DSS signature or verification. :Parameters: key : a `Cryptodome.PublicKey.DSA` or `Cryptodome.PublicKey.ECC` key object If the key has got its private half, both signature and verification are possible. If it only has the public half, verification is possible but not signature generation. For DSA keys, let *L* and *N* be the bit lengths of the modules *p* and *q*: the combination *(L,N)* must appear in the following list, in compliance to section 4.2 of `FIPS-186`__: - (1024, 160) - (2048, 224) - (2048, 256) - (3072, 256) mode : string The parameter can take these values: - *'fips-186-3'*. The signature generation is carried out according to `FIPS-186`__: the nonce *k* is taken from the RNG. - *'deterministic-rfc6979'*. The signature generation process does not rely on a random generator. See RFC6979_. encoding : string How the signature is encoded. This value determines the output of ``sign`` and the input of ``verify``. The following values are accepted: - *'binary'* (default), the signature is the raw concatenation of *r* and *s*. The size in bytes of the signature is always two times the size of *q*. - *'der'*, the signature is a DER encoded SEQUENCE with two INTEGERs, *r* and *s*. The size of the signature is variable. randfunc : callable The source of randomness. If ``None``, the internal RNG is used. Only used for the *'fips-186-3'* mode. .. __: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf .. __: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf .. _RFC6979: http://tools.ietf.org/html/rfc6979
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/DSS.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/DSS.py
MIT
def sign(self, msg_hash): """Produce the PKCS#1 v1.5 signature of a message. This function is named ``RSASSA-PKCS1-V1_5-SIGN``; it is specified in section 8.2.1 of RFC3447. :Parameters: msg_hash : hash object This is an object created with to the `Cryptodome.Hash` module. It was used used to hash the message to sign. :Return: The signature encoded as a byte string. :Raise ValueError: If the RSA key is not long enough when combined with the given hash algorithm. :Raise TypeError: If the RSA key has no private half. """ # See 8.2.1 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k) # Step 2a (OS2IP) em_int = bytes_to_long(em) # Step 2b (RSASP1) m_int = self._key._decrypt(em_int) # Step 2c (I2OSP) signature = long_to_bytes(m_int, k) return signature
Produce the PKCS#1 v1.5 signature of a message. This function is named ``RSASSA-PKCS1-V1_5-SIGN``; it is specified in section 8.2.1 of RFC3447. :Parameters: msg_hash : hash object This is an object created with to the `Cryptodome.Hash` module. It was used used to hash the message to sign. :Return: The signature encoded as a byte string. :Raise ValueError: If the RSA key is not long enough when combined with the given hash algorithm. :Raise TypeError: If the RSA key has no private half.
sign
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
MIT
def verify(self, msg_hash, signature): """Verify that a certain PKCS#1 v1.5 signature is valid. This method checks if the message really originates from someone that holds the RSA private key. really signed the message. This function is named ``RSASSA-PKCS1-V1_5-VERIFY``; it is specified in section 8.2.2 of RFC3447. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. signature : byte string The signature that needs to be validated. :Raise ValueError: if the signature is not valid. """ # See 8.2.2 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) k = ceil_div(modBits, 8) # Convert from bits to bytes # Step 1 if len(signature) != k: raise ValueError("Invalid signature") # Step 2a (O2SIP) signature_int = bytes_to_long(signature) # Step 2b (RSAVP1) em_int = self._key._encrypt(signature_int) # Step 2c (I2OSP) em1 = long_to_bytes(em_int, k) # Step 3 try: possible_em1 = [ _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, True) ] # MD2/4/5 hashes always require NULL params in AlgorithmIdentifier. # For all others, it is optional. try: algorithm_is_md = msg_hash.oid.startswith('1.2.840.113549.2.') except AttributeError: algorithm_is_md = False if not algorithm_is_md: # MD2/MD4/MD5 possible_em1.append(_EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, False)) except ValueError: raise ValueError("Invalid signature") # Step 4 # By comparing the full encodings (as opposed to checking each # of its components one at a time) we avoid attacks to the padding # scheme like Bleichenbacher's (see http://www.mail-archive.com/[email protected]/msg06537). # if em1 not in possible_em1: raise ValueError("Invalid signature") pass
Verify that a certain PKCS#1 v1.5 signature is valid. This method checks if the message really originates from someone that holds the RSA private key. really signed the message. This function is named ``RSASSA-PKCS1-V1_5-VERIFY``; it is specified in section 8.2.2 of RFC3447. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. signature : byte string The signature that needs to be validated. :Raise ValueError: if the signature is not valid.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
MIT
def _EMSA_PKCS1_V1_5_ENCODE(msg_hash, emLen, with_hash_parameters=True): """ Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.2). ``_EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: msg_hash : hash object The hash object that holds the digest of the message being signed. emLen : int The length the final encoding must have, in bytes. with_hash_parameters : bool If True (default), include NULL parameters for the hash algorithm in the ``digestAlgorithm`` SEQUENCE. :attention: the early standard (RFC2313) stated that ``DigestInfo`` had to be BER-encoded. This means that old signatures might have length tags in indefinite form, which is not supported in DER. Such encoding cannot be reproduced by this function. :Return: An ``emLen`` byte long string that encodes the hash. """ # First, build the ASN.1 DER object DigestInfo: # # DigestInfo ::= SEQUENCE { # digestAlgorithm AlgorithmIdentifier, # digest OCTET STRING # } # # where digestAlgorithm identifies the hash function and shall be an # algorithm ID with an OID in the set PKCS1-v1-5DigestAlgorithms. # # PKCS1-v1-5DigestAlgorithms ALGORITHM-IDENTIFIER ::= { # { OID id-md2 PARAMETERS NULL }| # { OID id-md5 PARAMETERS NULL }| # { OID id-sha1 PARAMETERS NULL }| # { OID id-sha256 PARAMETERS NULL }| # { OID id-sha384 PARAMETERS NULL }| # { OID id-sha512 PARAMETERS NULL } # } # # Appendix B.1 also says that for SHA-1/-2 algorithms, the parameters # should be omitted. They may be present, but when they are, they shall # have NULL value. digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ]) if with_hash_parameters: digestAlgo.append(DerNull().encode()) digest = DerOctetString(msg_hash.digest()) digestInfo = DerSequence([ digestAlgo.encode(), digest.encode() ]).encode() # We need at least 11 bytes for the remaining data: 3 fixed bytes and # at least 8 bytes of padding). if emLen<len(digestInfo)+11: raise TypeError("Selected hash algorith has a too long digest (%d bytes)." % len(digest)) PS = bchr(0xFF) * (emLen - len(digestInfo) - 3) return b("\x00\x01") + PS + bchr(0x00) + digestInfo
Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.2). ``_EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: msg_hash : hash object The hash object that holds the digest of the message being signed. emLen : int The length the final encoding must have, in bytes. with_hash_parameters : bool If True (default), include NULL parameters for the hash algorithm in the ``digestAlgorithm`` SEQUENCE. :attention: the early standard (RFC2313) stated that ``DigestInfo`` had to be BER-encoded. This means that old signatures might have length tags in indefinite form, which is not supported in DER. Such encoding cannot be reproduced by this function. :Return: An ``emLen`` byte long string that encodes the hash.
_EMSA_PKCS1_V1_5_ENCODE
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pkcs1_15.py
MIT
def __init__(self, key, mgfunc, saltLen, randfunc): """Initialize this PKCS#1 PSS signature scheme object. :Parameters: key : an RSA key object If a private half is given, both signature and verification are possible. If a public half is given, only verification is possible. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. saltLen : integer Length of the salt, in bytes. randfunc : callable A function that returns random bytes. """ self._key = key self._saltLen = saltLen self._mgfunc = mgfunc self._randfunc = randfunc
Initialize this PKCS#1 PSS signature scheme object. :Parameters: key : an RSA key object If a private half is given, both signature and verification are possible. If a public half is given, only verification is possible. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. saltLen : integer Length of the salt, in bytes. randfunc : callable A function that returns random bytes.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def sign(self, msg_hash): """Produce the PKCS#1 PSS signature of a message. This function is named ``RSASSA-PSS-SIGN``, and is specified in section 8.1.1 of RFC3447. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. :Return: The PSS signature encoded as a byte string. :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given hash algorithm. :Raise TypeError: If the RSA key has no private half. :attention: Modify the salt length and the mask generation function only if you know what you are doing. The receiver must use the same parameters too. """ # Set defaults for salt length and mask generation function if self._saltLen is None: sLen = msg_hash.digest_size else: sLen = self._saltLen if self._mgfunc is None: mgf = lambda x, y: MGF1(x, y, msg_hash) else: mgf = self._mgfunc modBits = Cryptodome.Util.number.size(self._key.n) # See 8.1.1 in RFC3447 k = ceil_div(modBits, 8) # k is length in bytes of the modulus # Step 1 em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen) # Step 2a (OS2IP) em_int = bytes_to_long(em) # Step 2b (RSASP1) m_int = self._key._decrypt(em_int) # Step 2c (I2OSP) signature = long_to_bytes(m_int, k) return signature
Produce the PKCS#1 PSS signature of a message. This function is named ``RSASSA-PSS-SIGN``, and is specified in section 8.1.1 of RFC3447. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. :Return: The PSS signature encoded as a byte string. :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given hash algorithm. :Raise TypeError: If the RSA key has no private half. :attention: Modify the salt length and the mask generation function only if you know what you are doing. The receiver must use the same parameters too.
sign
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def verify(self, msg_hash, signature): """Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: msg_hash : hash object The cryptographic hash computed over the message. This is an object belonging to the `Cryptodome.Hash` module. signature : byte string The signature that needs to be validated. :Raise ValueError: if the signature is incorrect. """ # Set defaults for salt length and mask generation function if self._saltLen is None: sLen = msg_hash.digest_size else: sLen = self._saltLen if self._mgfunc: mgf = self._mgfunc else: mgf = lambda x, y: MGF1(x, y, msg_hash) modBits = Cryptodome.Util.number.size(self._key.n) # See 8.1.2 in RFC3447 k = ceil_div(modBits, 8) # Convert from bits to bytes # Step 1 if len(signature) != k: raise ValueError("Incorrect signature") # Step 2a (O2SIP) signature_int = bytes_to_long(signature) # Step 2b (RSAVP1) em_int = self._key._encrypt(signature_int) # Step 2c (I2OSP) emLen = ceil_div(modBits - 1, 8) em = long_to_bytes(em_int, emLen) # Step 3/4 _EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: msg_hash : hash object The cryptographic hash computed over the message. This is an object belonging to the `Cryptodome.Hash` module. signature : byte string The signature that needs to be validated. :Raise ValueError: if the signature is incorrect.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen): """ Implement the ``EMSA-PSS-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.1). The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message being signed. emBits : int Maximum length of the final encoding, in bits. randFunc : callable An RNG function that accepts as only parameter an int, and returns a string of random bytes, to be used as salt. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Return: An ``emLen`` byte long string that encodes the hash (with ``emLen = \ceil(emBits/8)``). :Raise ValueError: When digest or salt length are too big. """ emLen = ceil_div(emBits, 8) # Bitmask of digits that fill up lmask = 0 for i in xrange(8*emLen-emBits): lmask = lmask >> 1 | 0x80 # Step 1 and 2 have been already done # Step 3 if emLen < mhash.digest_size+sLen+2: raise ValueError("Digest or salt length are too long" " for given key size.") # Step 4 salt = randFunc(sLen) # Step 5 m_prime = bchr(0)*8 + mhash.digest() + salt # Step 6 h = mhash.new() h.update(m_prime) # Step 7 ps = bchr(0)*(emLen-sLen-mhash.digest_size-2) # Step 8 db = ps + bchr(1) + salt # Step 9 dbMask = mgf(h.digest(), emLen-mhash.digest_size-1) # Step 10 maskedDB = strxor(db, dbMask) # Step 11 maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:] # Step 12 em = maskedDB + h.digest() + bchr(0xBC) return em
Implement the ``EMSA-PSS-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.1). The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message being signed. emBits : int Maximum length of the final encoding, in bits. randFunc : callable An RNG function that accepts as only parameter an int, and returns a string of random bytes, to be used as salt. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Return: An ``emLen`` byte long string that encodes the hash (with ``emLen = \ceil(emBits/8)``). :Raise ValueError: When digest or salt length are too big.
_EMSA_PSS_ENCODE
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen): """ Implement the ``EMSA-PSS-VERIFY`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.2). ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message to be verified. em : string The signature to verify, therefore proving that the sender really signed the message that was received. emBits : int Length of the final encoding (em), in bits. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Raise ValueError: When the encoding is inconsistent, or the digest or salt lengths are too big. """ emLen = ceil_div(emBits, 8) # Bitmask of digits that fill up lmask = 0 for i in xrange(8*emLen-emBits): lmask = lmask >> 1 | 0x80 # Step 1 and 2 have been already done # Step 3 if emLen < mhash.digest_size+sLen+2: return False # Step 4 if ord(em[-1:]) != 0xBC: raise ValueError("Incorrect signature") # Step 5 maskedDB = em[:emLen-mhash.digest_size-1] h = em[emLen-mhash.digest_size-1:-1] # Step 6 if lmask & bord(em[0]): raise ValueError("Incorrect signature") # Step 7 dbMask = mgf(h, emLen-mhash.digest_size-1) # Step 8 db = strxor(maskedDB, dbMask) # Step 9 db = bchr(bord(db[0]) & ~lmask) + db[1:] # Step 10 if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)): raise ValueError("Incorrect signature") # Step 11 if sLen > 0: salt = db[-sLen:] else: salt = b("") # Step 12 m_prime = bchr(0)*8 + mhash.digest() + salt # Step 13 hobj = mhash.new() hobj.update(m_prime) hp = hobj.digest() # Step 14 if h != hp: raise ValueError("Incorrect signature")
Implement the ``EMSA-PSS-VERIFY`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.2). ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message to be verified. em : string The signature to verify, therefore proving that the sender really signed the message that was received. emBits : int Length of the final encoding (em), in bits. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Raise ValueError: When the encoding is inconsistent, or the digest or salt lengths are too big.
_EMSA_PSS_VERIFY
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def new(rsa_key, **kwargs): """Return a signature scheme object `PSS_SigScheme` that can be used to perform PKCS#1 PSS signature or verification. :Parameters: rsa_key : RSA key object The key to use to sign or verify the message. This is a `Cryptodome.PublicKey.RSA` object. Signing is only possible if *key* is a private RSA key. :Keywords: mask_func : callable A mask generation function that accepts two parameters: a string to use as seed, and the length of the mask in bytes to generate. If not specified, the standard MGF1 is used. salt_bytes : int Length of the salt, in bytes. If not specified, it matches the output size of the hash function. If zero, the signature scheme becomes deterministic. rand_func : callable A function that returns random bytes. The default is `Cryptodome.Random.get_random_bytes`. """ mask_func = kwargs.pop("mask_func", None) salt_len = kwargs.pop("salt_bytes", None) rand_func = kwargs.pop("rand_func", None) if rand_func is None: rand_func = Random.get_random_bytes if kwargs: raise ValueError("Unknown keywords: " + str(kwargs.keys())) return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)
Return a signature scheme object `PSS_SigScheme` that can be used to perform PKCS#1 PSS signature or verification. :Parameters: rsa_key : RSA key object The key to use to sign or verify the message. This is a `Cryptodome.PublicKey.RSA` object. Signing is only possible if *key* is a private RSA key. :Keywords: mask_func : callable A mask generation function that accepts two parameters: a string to use as seed, and the length of the mask in bytes to generate. If not specified, the standard MGF1 is used. salt_bytes : int Length of the salt, in bytes. If not specified, it matches the output size of the hash function. If zero, the signature scheme becomes deterministic. rand_func : callable A function that returns random bytes. The default is `Cryptodome.Random.get_random_bytes`.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Signature/pss.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Signature/pss.py
MIT
def _convertTag(self, tag): """Check if *tag* is a real DER tag. Convert it from a character to number if necessary. """ if not _is_number(tag): if len(tag) == 1: tag = bord(tag[0]) # Ensure that tag is a low tag if not (_is_number(tag) and 0 <= tag < 0x1F): raise ValueError("Wrong DER tag") return tag
Check if *tag* is a real DER tag. Convert it from a character to number if necessary.
_convertTag
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _definite_form(length): """Build length octets according to BER/DER definite form. """ if length > 127: encoding = long_to_bytes(length) return bchr(len(encoding) + 128) + encoding return bchr(length)
Build length octets according to BER/DER definite form.
_definite_form
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return this DER element, fully encoded as a binary byte string.""" # Concatenate identifier octets, length octets, # and contents octets output_payload = self.payload # In case of an EXTERNAL tag, first encode the inner # element. if hasattr(self, "_inner_tag_octet"): output_payload = (bchr(self._inner_tag_octet) + self._definite_form(len(self.payload)) + self.payload) return (bchr(self._tag_octet) + self._definite_form(len(output_payload)) + output_payload)
Return this DER element, fully encoded as a binary byte string.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeLen(self, s): """Decode DER length octets from a file.""" length = s.read_byte() if length <= 127: return length payloadLength = bytes_to_long(s.read(length & 0x7F)) # According to DER (but not BER) the long form is used # only when the length doesn't fit into 7 bits. if payloadLength <= 127: raise ValueError("Not a DER length tag (but still valid BER).") return payloadLength
Decode DER length octets from a file.
_decodeLen
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def decode(self, derEle): """Decode a complete DER element, and re-initializes this object with it. :Parameters: derEle : byte string A complete DER element. :Raise ValueError: In case of parsing errors. """ if not byte_string(derEle): raise ValueError("Input is not a byte string") s = BytesIO_EOF(derEle) self._decodeFromStream(s) # There shouldn't be other bytes left if s.remaining_data() > 0: raise ValueError("Unexpected extra data after the DER structure") return self
Decode a complete DER element, and re-initializes this object with it. :Parameters: derEle : byte string A complete DER element. :Raise ValueError: In case of parsing errors.
decode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER element from a file.""" idOctet = s.read_byte() if self._tag_octet is not None: if idOctet != self._tag_octet: raise ValueError("Unexpected DER tag") else: self._tag_octet = idOctet length = self._decodeLen(s) self.payload = s.read(length) # In case of an EXTERNAL tag, further decode the inner # element. if hasattr(self, "_inner_tag_octet"): p = BytesIO_EOF(self.payload) inner_octet = p.read_byte() if inner_octet != self._inner_tag_octet: raise ValueError("Unexpected internal DER tag") length = self._decodeLen(p) self.payload = p.read(length) # There shouldn't be other bytes left if p.remaining_data() > 0: raise ValueError("Unexpected extra data after the DER structure")
Decode a complete DER element from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def __init__(self, value=0, implicit=None, explicit=None): """Initialize the DER object as an INTEGER. :Parameters: value : integer The value of the integer. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for INTEGER (2). """ DerObject.__init__(self, 0x02, b(''), implicit, False, explicit) self.value = value #: The integer value
Initialize the DER object as an INTEGER. :Parameters: value : integer The value of the integer. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for INTEGER (2).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return the DER INTEGER, fully encoded as a binary string.""" number = self.value self.payload = b('') while True: self.payload = bchr(int(number & 255)) + self.payload if 128 <= number <= 255: self.payload = bchr(0x00) + self.payload if -128 <= number <= 255: break number >>= 8 return DerObject.encode(self)
Return the DER INTEGER, fully encoded as a binary string.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER INTEGER from a file.""" # Fill up self.payload DerObject._decodeFromStream(self, s) # Derive self.value from self.payload self.value = 0 bits = 1 for i in self.payload: self.value *= 256 self.value += bord(i) bits <<= 8 if self.payload and bord(self.payload[0]) & 0x80: self.value -= bits
Decode a complete DER INTEGER from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def __init__(self, startSeq=None, implicit=None): """Initialize the DER object as a SEQUENCE. :Parameters: startSeq : Python sequence A sequence whose element are either integers or other DER objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SEQUENCE (16). """ DerObject.__init__(self, 0x10, b(''), implicit, True) if startSeq is None: self._seq = [] else: self._seq = startSeq
Initialize the DER object as a SEQUENCE. :Parameters: startSeq : Python sequence A sequence whose element are either integers or other DER objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SEQUENCE (16).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def hasInts(self, only_non_negative=True): """Return the number of items in this sequence that are integers. :Parameters: only_non_negative : boolean If True, negative integers are not counted in. """ def _is_number2(x): return _is_number(x, only_non_negative) return len(filter(_is_number2, self._seq))
Return the number of items in this sequence that are integers. :Parameters: only_non_negative : boolean If True, negative integers are not counted in.
hasInts
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return this DER SEQUENCE, fully encoded as a binary string. :Raises ValueError: If some elements in the sequence are neither integers nor byte strings. """ self.payload = b('') for item in self._seq: if byte_string(item): self.payload += item elif _is_number(item): self.payload += DerInteger(item).encode() else: self.payload += item.encode() return DerObject.encode(self)
Return this DER SEQUENCE, fully encoded as a binary string. :Raises ValueError: If some elements in the sequence are neither integers nor byte strings.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def decode(self, derEle, nr_elements=None, only_ints_expected=False): """Decode a complete DER SEQUENCE, and re-initializes this object with it. :Parameters: derEle : byte string A complete SEQUENCE DER element. nr_elements : None, integer or list of integers The number of members the SEQUENCE can have only_ints_expected : boolean Whether the SEQUENCE is expected to contain only integers. :Raise ValueError: In case of parsing errors. DER INTEGERs are decoded into Python integers. Any other DER element is not decoded. Its validity is not checked. """ self._nr_elements = nr_elements result = DerObject.decode(self, derEle) if only_ints_expected and not self.hasOnlyInts(): raise ValueError("Some members are not INTEGERs") return result
Decode a complete DER SEQUENCE, and re-initializes this object with it. :Parameters: derEle : byte string A complete SEQUENCE DER element. nr_elements : None, integer or list of integers The number of members the SEQUENCE can have only_ints_expected : boolean Whether the SEQUENCE is expected to contain only integers. :Raise ValueError: In case of parsing errors. DER INTEGERs are decoded into Python integers. Any other DER element is not decoded. Its validity is not checked.
decode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER SEQUENCE from a file.""" self._seq = [] # Fill up self.payload DerObject._decodeFromStream(self, s) # Add one item at a time to self.seq, by scanning self.payload p = BytesIO_EOF(self.payload) while p.remaining_data() > 0: p.set_bookmark() der = DerObject() der._decodeFromStream(p) # Parse INTEGERs differently if der._tag_octet != 0x02: self._seq.append(p.data_since_bookmark()) else: derInt = DerInteger() derInt.decode(p.data_since_bookmark()) self._seq.append(derInt.value) ok = True if self._nr_elements is not None: try: ok = len(self._seq) in self._nr_elements except TypeError: ok = len(self._seq) == self._nr_elements if not ok: raise ValueError("Unexpected number of members (%d)" " in the sequence" % len(self._seq))
Decode a complete DER SEQUENCE from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def __init__(self, value='', implicit=None, explicit=None): """Initialize the DER object as an OBJECT ID. :Parameters: value : string The initial Object Identifier (e.g. "1.2.0.0.6.2"). implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OBJECT ID (6). explicit : integer The EXPLICIT tag to use for the encoded object. """ DerObject.__init__(self, 0x06, b(''), implicit, False, explicit) self.value = value #: The Object ID, a dot separated list of integers
Initialize the DER object as an OBJECT ID. :Parameters: value : string The initial Object Identifier (e.g. "1.2.0.0.6.2"). implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OBJECT ID (6). explicit : integer The EXPLICIT tag to use for the encoded object.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return the DER OBJECT ID, fully encoded as a binary string.""" comps = map(int, self.value.split(".")) if len(comps) < 2: raise ValueError("Not a valid Object Identifier string") self.payload = bchr(40*comps[0]+comps[1]) for v in comps[2:]: enc = [] while v: enc.insert(0, (v & 0x7F) | 0x80) v >>= 7 enc[-1] &= 0x7F self.payload += b('').join(map(bchr, enc)) return DerObject.encode(self)
Return the DER OBJECT ID, fully encoded as a binary string.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER OBJECT ID from a file.""" # Fill up self.payload DerObject._decodeFromStream(self, s) # Derive self.value from self.payload p = BytesIO_EOF(self.payload) comps = list(map(str, divmod(p.read_byte(), 40))) v = 0 while p.remaining_data(): c = p.read_byte() v = v*128 + (c & 0x7F) if not (c & 0x80): comps.append(str(v)) v = 0 self.value = '.'.join(comps)
Decode a complete DER OBJECT ID from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def __init__(self, value=b(''), implicit=None, explicit=None): """Initialize the DER object as a BIT STRING. :Parameters: value : byte string or DER object The initial, packed bit string. If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object. """ DerObject.__init__(self, 0x03, b(''), implicit, False, explicit) # The bitstring value (packed) if isinstance(value, DerObject): self.value = value.encode() else: self.value = value
Initialize the DER object as a BIT STRING. :Parameters: value : byte string or DER object The initial, packed bit string. If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return the DER BIT STRING, fully encoded as a binary string.""" # Add padding count byte self.payload = b('\x00') + self.value return DerObject.encode(self)
Return the DER BIT STRING, fully encoded as a binary string.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER BIT STRING DER from a file.""" # Fill-up self.payload DerObject._decodeFromStream(self, s) if self.payload and bord(self.payload[0]) != 0: raise ValueError("Not a valid BIT STRING") # Fill-up self.value self.value = b('') # Remove padding count byte if self.payload: self.value = self.payload[1:]
Decode a complete DER BIT STRING DER from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def __init__(self, startSet=None, implicit=None): """Initialize the DER object as a SET OF. :Parameters: startSet : container The initial set of integers or DER encoded objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SET OF (17). """ DerObject.__init__(self, 0x11, b(''), implicit, True) self._seq = [] # All elements must be of the same type (and therefore have the # same leading octet) self._elemOctet = None if startSet: for e in startSet: self.add(e)
Initialize the DER object as a SET OF. :Parameters: startSet : container The initial set of integers or DER encoded objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SET OF (17).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def add(self, elem): """Add an element to the set. :Parameters: elem : byte string or integer An element of the same type of objects already in the set. It can be an integer or a DER encoded object. """ if _is_number(elem): eo = 0x02 elif isinstance(elem, DerObject): eo = self._tag_octet else: eo = bord(elem[0]) if self._elemOctet != eo: if self._elemOctet is not None: raise ValueError("New element does not belong to the set") self._elemOctet = eo if elem not in self._seq: self._seq.append(elem)
Add an element to the set. :Parameters: elem : byte string or integer An element of the same type of objects already in the set. It can be an integer or a DER encoded object.
add
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def _decodeFromStream(self, s): """Decode a complete DER SET OF from a file.""" self._seq = [] # Fill up self.payload DerObject._decodeFromStream(self, s) # Add one item at a time to self.seq, by scanning self.payload p = BytesIO_EOF(self.payload) setIdOctet = -1 while p.remaining_data() > 0: p.set_bookmark() der = DerObject() der._decodeFromStream(p) # Verify that all members are of the same type if setIdOctet < 0: setIdOctet = der._tag_octet else: if setIdOctet != der._tag_octet: raise ValueError("Not all elements are of the same DER type") # Parse INTEGERs differently if setIdOctet != 0x02: self._seq.append(p.data_since_bookmark()) else: derInt = DerInteger() derInt.decode(p.data_since_bookmark()) self._seq.append(derInt.value) # end
Decode a complete DER SET OF from a file.
_decodeFromStream
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def encode(self): """Return this SET OF DER element, fully encoded as a binary string. """ # Elements in the set must be ordered in lexicographic order ordered = [] for item in self._seq: if _is_number(item): bys = DerInteger(item).encode() elif isinstance(item, DerObject): bys = item.encode() else: bys = item ordered.append(bys) ordered.sort() self.payload = b('').join(ordered) return DerObject.encode(self)
Return this SET OF DER element, fully encoded as a binary string.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/asn1.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/asn1.py
MIT
def new(nbits, prefix=b(""), suffix=b(""), initial_value=1, little_endian=False, allow_wraparound=False): """Create a stateful counter block function suitable for CTR encryption modes. Each call to the function returns the next counter block. Each counter block is made up by three parts:: prefix || counter value || postfix The counter value is incremented by 1 at each call. :Parameters: nbits : integer Length of the desired counter value, in bits. It must be a multiple of 8. prefix : byte string The constant prefix of the counter block. By default, no prefix is used. suffix : byte string The constant postfix of the counter block. By default, no suffix is used. initial_value : integer The initial value of the counter. Default value is 1. little_endian : boolean If *True*, the counter number will be encoded in little endian format. If *False* (default), in big endian format. allow_wraparound : boolean This parameter is ignored. :Returns: An object that can be passed with the 'counter' parameter to a CTR mode cipher. It must hold that ``len(prefix) + nbits//8 + len(suffix)`` matches the block size of the underlying block cipher. """ if (nbits % 8) != 0: raise ValueError("'nbits' must be a multiple of 8") # Ignore wraparound return {"counter_len": nbits // 8, "prefix": prefix, "suffix": suffix, "initial_value": initial_value, "little_endian": little_endian }
Create a stateful counter block function suitable for CTR encryption modes. Each call to the function returns the next counter block. Each counter block is made up by three parts:: prefix || counter value || postfix The counter value is incremented by 1 at each call. :Parameters: nbits : integer Length of the desired counter value, in bits. It must be a multiple of 8. prefix : byte string The constant prefix of the counter block. By default, no prefix is used. suffix : byte string The constant postfix of the counter block. By default, no suffix is used. initial_value : integer The initial value of the counter. Default value is 1. little_endian : boolean If *True*, the counter number will be encoded in little endian format. If *False* (default), in big endian format. allow_wraparound : boolean This parameter is ignored. :Returns: An object that can be passed with the 'counter' parameter to a CTR mode cipher. It must hold that ``len(prefix) + nbits//8 + len(suffix)`` matches the block size of the underlying block cipher.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/Counter.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/Counter.py
MIT
def size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits = 0 while N >> bits: bits += 1 return bits
size(N:long) : int Returns the size of the number N in bits.
size
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/number.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/number.py
MIT
def GCD(x,y): """GCD(x:long, y:long): long Return the GCD of x and y. """ x = abs(x) ; y = abs(y) while x > 0: x, y = y % x, x return y
GCD(x:long, y:long): long Return the GCD of x and y.
GCD
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/number.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/number.py
MIT
def inverse(u, v): """inverse(u:long, v:long):long Return the inverse of u mod v. """ u3, v3 = long(u), long(v) u1, v1 = 1, 0 while v3 > 0: q = u3 // v3 u1, v1 = v1, u1 - v1*q u3, v3 = v3, u3 - v3*q while u1<0: u1 = u1 + v return u1
inverse(u:long, v:long):long Return the inverse of u mod v.
inverse
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/number.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/number.py
MIT
def long_to_bytes(n, blocksize=0): """long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # after much testing, this algorithm was deemed to be the fastest s = b('') n = int(n) pack = struct.pack while n > 0: s = pack('>I', n & 0xffffffffL) + s n = n >> 32 # strip off leading zeros for i in range(len(s)): if s[i] != b('\000')[0]: break else: # only happens when n == 0 s = b('\000') i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * b('\000') + s return s
long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize.
long_to_bytes
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/number.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/number.py
MIT
def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer (big endian). This is (essentially) the inverse of long_to_bytes(). """ acc = 0 unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = b('\000') * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] return acc
bytes_to_long(string) : long Convert a byte string to a long integer (big endian). This is (essentially) the inverse of long_to_bytes().
bytes_to_long
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/number.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/number.py
MIT
def _key2bin(s): "Convert a key into a string of binary digits" kl=map(lambda x: bord(x), s) kl=map(lambda x: binary[x>>4]+binary[x&15], kl) return ''.join(kl)
Convert a key into a string of binary digits
_key2bin
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/RFC1751.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/RFC1751.py
MIT
def _extract(key, start, length): """Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.""" k=key[start:start+length] return reduce(lambda x,y: x*2+ord(y)-48, k, 0)
Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.
_extract
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/RFC1751.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/RFC1751.py
MIT
def key_to_english (key): """key_to_english(key:string(2.x)/bytes(3.x)) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8. """ english='' for index in range(0, len(key), 8): # Loop over 8-byte subkeys subkey=key[index:index+8] # Compute the parity of the key skbin=_key2bin(subkey) ; p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) # Append parity bits to the subkey skbin=_key2bin(subkey+bchr((p<<6) & 255)) for i in range(0, 64, 11): english=english+wordlist[_extract(skbin, i, 11)]+' ' return english[:-1] # Remove the trailing space
key_to_english(key:string(2.x)/bytes(3.x)) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8.
key_to_english
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/RFC1751.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/RFC1751.py
MIT
def english_to_key (s): """english_to_key(string):string(2.x)/bytes(2.x) Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6. """ L=s.upper().split() ; key=b('') for index in range(0, len(L), 6): sublist=L[index:index+6] ; char=9*[0] ; bits=0 for i in sublist: index = wordlist.index(i) shift = (8-(bits+11)%8) %8 y = index << shift cl, cc, cr = (y>>16), (y>>8)&0xff, y & 0xff if (shift>5): char[bits>>3] = char[bits>>3] | cl char[(bits>>3)+1] = char[(bits>>3)+1] | cc char[(bits>>3)+2] = char[(bits>>3)+2] | cr elif shift>-3: char[bits>>3] = char[bits>>3] | cc char[(bits>>3)+1] = char[(bits>>3)+1] | cr else: char[bits>>3] = char[bits>>3] | cr bits=bits+11 subkey=reduce(lambda x,y:x+bchr(y), char, b('')) # Check the parity of the resulting key skbin=_key2bin(subkey) p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) if (p&3) != _extract(skbin, 64, 2): raise ValueError, "Parity error in resulting key" key=key+subkey[0:8] return key
english_to_key(string):string(2.x)/bytes(2.x) Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6.
english_to_key
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/RFC1751.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/RFC1751.py
MIT
def strxor(term1, term2): """Return term1 xored with term2. The two byte strings must have equal length.""" expect_byte_string(term1) expect_byte_string(term2) if len(term1) != len(term2): raise ValueError("Only byte strings of equal length can be xored") result = create_string_buffer(len(term1)) _raw_strxor.strxor(term1, term2, result, c_size_t(len(term1))) return get_raw_buffer(result)
Return term1 xored with term2. The two byte strings must have equal length.
strxor
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/Cryptodome/Util/strxor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/strxor.py
MIT