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 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/osx64/Cryptodome/SelfTest/PublicKey/test_import_DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_import_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/PublicKey/test_RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/Signature/test_dss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/SelfTest/Signature/test_dss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/DSS.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/DSS.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/DSS.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/DSS.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/DSS.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pkcs1_15.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/cryptography@metzdowd.com/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/osx64/Cryptodome/Signature/pkcs1_15.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pkcs1_15.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Signature/pss.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/asn1.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/Counter.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/number.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/number.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/number.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/number.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/RFC1751.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/RFC1751.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/RFC1751.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/RFC1751.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/Cryptodome/Util/strxor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/strxor.py
|
MIT
|
def strxor_c(term, c):
"""Return term xored with a sequence of characters c."""
expect_byte_string(term)
if not 0 <= c < 256:
raise ValueError("c must be in range(256)")
result = create_string_buffer(len(term))
_raw_strxor.strxor_c(term, c, result, c_size_t(len(term)))
return get_raw_buffer(result)
|
Return term xored with a sequence of characters c.
|
strxor_c
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/strxor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/strxor.py
|
MIT
|
def pycryptodome_filename(dir_comps, filename):
"""Return the complete file name for the module
dir_comps : list of string
The list of directory names in the PyCryptodome package.
The first element must be "Cryptodome".
filename : string
The filename (inclusing extension) in the target directory.
"""
if dir_comps[0] != "Cryptodome":
raise ValueError("Only available for modules under 'Cryptodome'")
dir_comps = list(dir_comps[1:]) + [filename]
util_lib, _ = os.path.split(os.path.abspath(__file__))
root_lib = os.path.join(util_lib, "..")
return os.path.join(root_lib, *dir_comps)
|
Return the complete file name for the module
dir_comps : list of string
The list of directory names in the PyCryptodome package.
The first element must be "Cryptodome".
filename : string
The filename (inclusing extension) in the target directory.
|
pycryptodome_filename
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_file_system.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_file_system.py
|
MIT
|
def ceil_shift(n, b):
"""Return ceil(n / 2**b) without performing any floating-point or division operations.
This is done by right-shifting n by b bits and incrementing the result by 1
if any '1' bits were shifted out.
"""
if not isinstance(n, (int, long)) or not isinstance(b, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(n).__name__, type(b).__name__))
assert n >= 0 and b >= 0 # I haven't tested or even thought about negative values
mask = (1 << b) - 1
if n & mask:
return (n >> b) + 1
else:
return n >> b
|
Return ceil(n / 2**b) without performing any floating-point or division operations.
This is done by right-shifting n by b bits and incrementing the result by 1
if any '1' bits were shifted out.
|
ceil_shift
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
MIT
|
def ceil_div(a, b):
"""Return ceil(a / b) without performing any floating-point operations."""
if not isinstance(a, (int, long)) or not isinstance(b, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__))
(q, r) = divmod(a, b)
if r:
return q + 1
else:
return q
|
Return ceil(a / b) without performing any floating-point operations.
|
ceil_div
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
MIT
|
def exact_log2(num):
"""Find and return an integer i >= 0 such that num == 2**i.
If no such integer exists, this function raises ValueError.
"""
if not isinstance(num, (int, long)):
raise TypeError("unsupported operand type: %r" % (type(num).__name__,))
n = long(num)
if n <= 0:
raise ValueError("cannot compute logarithm of non-positive number")
i = 0
while n != 0:
if (n & 1) and n != 1:
raise ValueError("No solution could be found")
i += 1
n >>= 1
i -= 1
assert num == (1 << i)
return i
|
Find and return an integer i >= 0 such that num == 2**i.
If no such integer exists, this function raises ValueError.
|
exact_log2
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
MIT
|
def exact_div(p, d, allow_divzero=False):
"""Find and return an integer n such that p == n * d
If no such integer exists, this function raises ValueError.
Both operands must be integers.
If the second operand is zero, this function will raise ZeroDivisionError
unless allow_divzero is true (default: False).
"""
if not isinstance(p, (int, long)) or not isinstance(d, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(p).__name__, type(d).__name__))
if d == 0 and allow_divzero:
n = 0
if p != n * d:
raise ValueError("No solution could be found")
else:
(n, r) = divmod(p, d)
if r != 0:
raise ValueError("No solution could be found")
assert p == n * d
return n
|
Find and return an integer n such that p == n * d
If no such integer exists, this function raises ValueError.
Both operands must be integers.
If the second operand is zero, this function will raise ZeroDivisionError
unless allow_divzero is true (default: False).
|
exact_div
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_number_new.py
|
MIT
|
def load_lib(name, cdecl):
"""Load a shared library and return a handle to it.
@name, either an absolute path or the name of a library
in the system search path.
@cdecl, the C function declarations.
"""
lib = ffi.dlopen(name)
ffi.cdef(cdecl)
return lib
|
Load a shared library and return a handle to it.
@name, either an absolute path or the name of a library
in the system search path.
@cdecl, the C function declarations.
|
load_lib
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_raw_api.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_raw_api.py
|
MIT
|
def load_pycryptodome_raw_lib(name, cdecl):
"""Load a shared library and return a handle to it.
@name, the name of the library expressed as a PyCryptodome module,
for instance Cryptodome.Cipher._raw_cbc.
@cdecl, the C function declarations.
"""
split = name.split(".")
dir_comps, basename = split[:-1], split[-1]
for ext, mod, typ in imp.get_suffixes():
if typ == imp.C_EXTENSION:
try:
return load_lib(pycryptodome_filename(dir_comps, basename + ext), cdecl)
except OSError:
pass
raise OSError("Cannot load native module '%s'" % name)
|
Load a shared library and return a handle to it.
@name, the name of the library expressed as a PyCryptodome module,
for instance Cryptodome.Cipher._raw_cbc.
@cdecl, the C function declarations.
|
load_pycryptodome_raw_lib
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/Cryptodome/Util/_raw_api.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Util/_raw_api.py
|
MIT
|
def __init__(self, listener, locals=None, banner=None, **server_args):
"""
:keyword locals: If given, a dictionary of "builtin" values that will be available
at the top-level.
:keyword banner: If geven, a string that will be printed to each connecting user.
"""
StreamServer.__init__(self, listener, spawn=_Greenlet_stdreplace.spawn, **server_args)
_locals = {'__doc__': None, '__name__': '__console__'}
if locals:
_locals.update(locals)
self.locals = _locals
self.banner = banner
self.stderr = sys.stderr
|
:keyword locals: If given, a dictionary of "builtin" values that will be available
at the top-level.
:keyword banner: If geven, a string that will be printed to each connecting user.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/backdoor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/backdoor.py
|
MIT
|
def handle(self, conn, address):
"""
Interact with one remote user.
.. versionchanged:: 1.1b2 Each connection gets its own
``locals`` dictionary. Previously they were shared in a
potentially unsafe manner.
"""
fobj = conn.makefile(mode="rw")
fobj = _fileobject(conn, fobj, self.stderr)
getcurrent()._fileobj = fobj
getcurrent().switch_in()
try:
console = InteractiveConsole(self._create_interactive_locals())
console.interact(banner=self.banner)
except SystemExit: # raised by quit()
if hasattr(sys, 'exc_clear'): # py2
sys.exc_clear()
finally:
conn.close()
fobj.close()
|
Interact with one remote user.
.. versionchanged:: 1.1b2 Each connection gets its own
``locals`` dictionary. Previously they were shared in a
potentially unsafe manner.
|
handle
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/backdoor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/backdoor.py
|
MIT
|
def start(self):
"""Start accepting the connections.
If an address was provided in the constructor, then also create a socket,
bind it and put it into the listening mode.
"""
self.init_socket()
self._stop_event.clear()
try:
self.start_accepting()
except:
self.close()
raise
|
Start accepting the connections.
If an address was provided in the constructor, then also create a socket,
bind it and put it into the listening mode.
|
start
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/baseserver.py
|
MIT
|
def close(self):
"""Close the listener socket and stop accepting."""
self._stop_event.set()
try:
self.stop_accepting()
finally:
try:
self.socket.close()
except Exception:
pass
finally:
self.__dict__.pop('socket', None)
self.__dict__.pop('handle', None)
self.__dict__.pop('_handle', None)
self.__dict__.pop('_spawn', None)
self.__dict__.pop('full', None)
if self.pool is not None:
self.pool._semaphore.unlink(self._start_accepting_if_started)
|
Close the listener socket and stop accepting.
|
close
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/baseserver.py
|
MIT
|
def stop(self, timeout=None):
"""
Stop accepting the connections and close the listening socket.
If the server uses a pool to spawn the requests, then
:meth:`stop` also waits for all the handlers to exit. If there
are still handlers executing after *timeout* has expired
(default 1 second, :attr:`stop_timeout`), then the currently
running handlers in the pool are killed.
If the server does not use a pool, then this merely stops accepting connections;
any spawned greenlets that are handling requests continue running until
they naturally complete.
"""
self.close()
if timeout is None:
timeout = self.stop_timeout
if self.pool:
self.pool.join(timeout=timeout)
self.pool.kill(block=True, timeout=1)
|
Stop accepting the connections and close the listening socket.
If the server uses a pool to spawn the requests, then
:meth:`stop` also waits for all the handlers to exit. If there
are still handlers executing after *timeout* has expired
(default 1 second, :attr:`stop_timeout`), then the currently
running handlers in the pool are killed.
If the server does not use a pool, then this merely stops accepting connections;
any spawned greenlets that are handling requests continue running until
they naturally complete.
|
stop
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/baseserver.py
|
MIT
|
def serve_forever(self, stop_timeout=None):
"""Start the server if it hasn't been already started and wait until it's stopped."""
# add test that serve_forever exists on stop()
if not self.started:
self.start()
try:
self._stop_event.wait()
finally:
Greenlet.spawn(self.stop, timeout=stop_timeout).join()
|
Start the server if it hasn't been already started and wait until it's stopped.
|
serve_forever
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/baseserver.py
|
MIT
|
def __import__(*args, **kwargs):
"""
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> object
Normally python protects imports against concurrency by doing some locking
at the C level (at least, it does that in CPython). This function just
wraps the normal __import__ functionality in a recursive lock, ensuring that
we're protected against greenlet import concurrency as well.
"""
if len(args) > 0 and not issubclass(type(args[0]), _allowed_module_name_types):
# if a builtin has been acquired as a bound instance method,
# python knows not to pass 'self' when the method is called.
# No such protection exists for monkey-patched builtins,
# however, so this is necessary.
args = args[1:]
if not __lock_imports:
return _import(*args, **kwargs)
module_lock = __module_lock(args[0]) # Get a lock for the module name
imp.acquire_lock()
try:
module_lock.acquire()
try:
result = _import(*args, **kwargs)
finally:
module_lock.release()
finally:
imp.release_lock()
return result
|
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> object
Normally python protects imports against concurrency by doing some locking
at the C level (at least, it does that in CPython). This function just
wraps the normal __import__ functionality in a recursive lock, ensuring that
we're protected against greenlet import concurrency as well.
|
__import__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/builtins.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/builtins.py
|
MIT
|
def _python_callback(handle, revents):
"""
Returns an integer having one of three values:
- -1
An exception occurred during the callback and you must call
:func:`_python_handle_error` to deal with it. The Python watcher
object will have the exception tuple saved in ``_exc_info``.
- 0
Everything went according to plan. You should check to see if the libev
watcher is still active, and call :func:`_python_stop` if so. This will
clean up the memory.
- 1
Everything went according to plan, but the watcher has already
been stopped. Its memory may no longer be valid.
"""
try:
# Even dereferencing the handle needs to be inside the try/except;
# if we don't return normally (e.g., a signal) then we wind up going
# to the 'onerror' handler, which
# is not what we want; that can permanently wedge the loop depending
# on which callback was executing
watcher = ffi.from_handle(handle)
args = watcher.args
if args is None:
# Legacy behaviour from corecext: convert None into ()
# See test__core_watcher.py
args = _NOARGS
if len(args) > 0 and args[0] == GEVENT_CORE_EVENTS:
args = (revents, ) + args[1:]
watcher.callback(*args)
except:
watcher._exc_info = sys.exc_info()
# Depending on when the exception happened, the watcher
# may or may not have been stopped. We need to make sure its
# memory stays valid so we can stop it at the ev level if needed.
watcher.loop._keepaliveset.add(watcher)
return -1
else:
if watcher in watcher.loop._keepaliveset:
# It didn't stop itself
return 0
return 1 # It stopped itself
|
Returns an integer having one of three values:
- -1
An exception occurred during the callback and you must call
:func:`_python_handle_error` to deal with it. The Python watcher
object will have the exception tuple saved in ``_exc_info``.
- 0
Everything went according to plan. You should check to see if the libev
watcher is still active, and call :func:`_python_stop` if so. This will
clean up the memory.
- 1
Everything went according to plan, but the watcher has already
been stopped. Its memory may no longer be valid.
|
_python_callback
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/corecffi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/corecffi.py
|
MIT
|
def rawlink(self, callback):
"""
Register a callback to call when this object is ready.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
"""
if not callable(callback):
raise TypeError('Expected callable: %r' % (callback, ))
self._links.add(callback)
self._check_and_notify()
|
Register a callback to call when this object is ready.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
|
rawlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/event.py
|
MIT
|
def unlink(self, callback):
"""Remove the callback set by :meth:`rawlink`"""
try:
self._links.remove(callback)
except KeyError:
pass
|
Remove the callback set by :meth:`rawlink`
|
unlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/event.py
|
MIT
|
def exc_info(self):
"""
The three-tuple of exception information if :meth:`set_exception` was called.
"""
if self._exc_info:
return (self._exc_info[0], self._exc_info[1], load_traceback(self._exc_info[2]))
return ()
|
The three-tuple of exception information if :meth:`set_exception` was called.
|
exc_info
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/event.py
|
MIT
|
def set_exception(self, exception, exc_info=None):
"""Store the exception and wake up any waiters.
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
:keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback`
as returned by :func:`sys.exc_info`. This will be used when the exception
is re-raised to propagate the correct traceback.
"""
if exc_info:
self._exc_info = (exc_info[0], exc_info[1], dump_traceback(exc_info[2]))
else:
self._exc_info = (type(exception), exception, dump_traceback(None))
self._check_and_notify()
|
Store the exception and wake up any waiters.
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
:keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback`
as returned by :func:`sys.exc_info`. This will be used when the exception
is re-raised to propagate the correct traceback.
|
set_exception
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/event.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Return the stored value or raise the exception.
If this instance already holds a value or an exception, return or raise it immediatelly.
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
be raised.
:keyword bool block: If set to ``False`` and this instance is not ready,
immediately raise a :class:`Timeout` exception.
"""
if self._value is not _NONE:
return self._value
if self._exc_info:
return self._raise_exception()
if not block:
# Not ready and not blocking, so immediately timeout
raise Timeout()
# Wait, raising a timeout that elapses
self._wait_core(timeout, ())
# by definition we are now ready
return self.get(block=False)
|
Return the stored value or raise the exception.
If this instance already holds a value or an exception, return or raise it immediatelly.
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
be raised.
:keyword bool block: If set to ``False`` and this instance is not ready,
immediately raise a :class:`Timeout` exception.
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/event.py
|
MIT
|
def __init__(self, fobj, *args, **kwargs):
"""
:param fobj: The underlying file-like object to wrap, or an integer fileno
that will be pass to :func:`os.fdopen` along with everything in *args*.
:keyword bool lock: If True (the default) then all operations will
be performed one-by-one. Note that this does not guarantee that, if using
this file object from multiple threads/greenlets, operations will be performed
in any particular order, only that no two operations will be attempted at the
same time. You can also pass your own :class:`gevent.lock.Semaphore` to synchronize
file operations with an external resource.
:keyword bool close: If True (the default) then when this object is closed,
the underlying object is closed as well.
"""
self._close = kwargs.pop('close', True)
self.threadpool = kwargs.pop('threadpool', None)
self.lock = kwargs.pop('lock', True)
if kwargs:
raise TypeError('Unexpected arguments: %r' % kwargs.keys())
if self.lock is True:
self.lock = Semaphore()
elif not self.lock:
self.lock = DummySemaphore()
if not hasattr(self.lock, '__enter__'):
raise TypeError('Expected a Semaphore or boolean, got %r' % type(self.lock))
if isinstance(fobj, integer_types):
if not self._close:
# we cannot do this, since fdopen object will close the descriptor
raise TypeError('FileObjectThread does not support close=False')
fobj = os.fdopen(fobj, *args)
self.io = fobj
if self.threadpool is None:
self.threadpool = get_hub().threadpool
|
:param fobj: The underlying file-like object to wrap, or an integer fileno
that will be pass to :func:`os.fdopen` along with everything in *args*.
:keyword bool lock: If True (the default) then all operations will
be performed one-by-one. Note that this does not guarantee that, if using
this file object from multiple threads/greenlets, operations will be performed
in any particular order, only that no two operations will be attempted at the
same time. You can also pass your own :class:`gevent.lock.Semaphore` to synchronize
file operations with an external resource.
:keyword bool close: If True (the default) then when this object is closed,
the underlying object is closed as well.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/fileobject.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/fileobject.py
|
MIT
|
def close(self):
"""
.. versionchanged:: 1.1b1
The file object is closed using the threadpool. Note that whether or
not this action is synchronous or asynchronous is not documented.
"""
fobj = self.io
if fobj is None:
return
self.io = None
try:
self.flush(_fobj=fobj)
finally:
if self._close:
# Note that we're not using self._apply; older code
# did fobj.close() without going through the threadpool at all,
# so acquiring the lock could potentially introduce deadlocks
# that weren't present before. Avoiding the lock doesn't make
# the existing race condition any worse.
# We wrap the close in an exception handler and re-raise directly
# to avoid the (common, expected) IOError from being logged
def close():
try:
fobj.close()
except:
return sys.exc_info()
exc_info = self.threadpool.apply(close)
if exc_info:
reraise(*exc_info)
|
.. versionchanged:: 1.1b1
The file object is closed using the threadpool. Note that whether or
not this action is synchronous or asynchronous is not documented.
|
close
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/fileobject.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/fileobject.py
|
MIT
|
def __init__(self, run=None, *args, **kwargs):
"""
Greenlet constructor.
:param args: The arguments passed to the ``run`` function.
:param kwargs: The keyword arguments passed to the ``run`` function.
:keyword run: The callable object to run. If not given, this object's
`_run` method will be invoked (typically defined by subclasses).
.. versionchanged:: 1.1b1
The ``run`` argument to the constructor is now verified to be a callable
object. Previously, passing a non-callable object would fail after the greenlet
was spawned.
"""
# greenlet.greenlet(run=None, parent=None)
# Calling it with both positional arguments instead of a keyword
# argument (parent=get_hub()) speeds up creation of this object ~30%:
# python -m timeit -s 'import gevent' 'gevent.Greenlet()'
# Python 3.5: 2.70usec with keywords vs 1.94usec with positional
# Python 3.4: 2.32usec with keywords vs 1.74usec with positional
# Python 3.3: 2.55usec with keywords vs 1.92usec with positional
# Python 2.7: 1.73usec with keywords vs 1.40usec with positional
greenlet.__init__(self, None, get_hub())
if run is not None:
self._run = run
# If they didn't pass a callable at all, then they must
# already have one. Note that subclassing to override the run() method
# itself has never been documented or supported.
if not callable(self._run):
raise TypeError("The run argument or self._run must be callable")
if args:
self.args = args
if kwargs:
self._kwargs = kwargs
|
Greenlet constructor.
:param args: The arguments passed to the ``run`` function.
:param kwargs: The keyword arguments passed to the ``run`` function.
:keyword run: The callable object to run. If not given, this object's
`_run` method will be invoked (typically defined by subclasses).
.. versionchanged:: 1.1b1
The ``run`` argument to the constructor is now verified to be a callable
object. Previously, passing a non-callable object would fail after the greenlet
was spawned.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def exc_info(self):
"""Holds the exc_info three-tuple raised by the function if the greenlet finished with an error.
Otherwise a false value."""
e = self._exc_info
if e:
return (e[0], e[1], load_traceback(e[2]))
|
Holds the exc_info three-tuple raised by the function if the greenlet finished with an error.
Otherwise a false value.
|
exc_info
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def throw(self, *args):
"""Immediatelly switch into the greenlet and raise an exception in it.
Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever.
To raise an exception in a safe manner from any greenlet, use :meth:`kill`.
If a greenlet was started but never switched to yet, then also
a) cancel the event that will start it
b) fire the notifications as if an exception was raised in a greenlet
"""
self.__cancel_start()
try:
if not self.dead:
# Prevent switching into a greenlet *at all* if we had never
# started it. Usually this is the same thing that happens by throwing,
# but if this is done from the hub with nothing else running, prevents a
# LoopExit.
greenlet.throw(self, *args)
finally:
self.__handle_death_before_start(*args)
|
Immediatelly switch into the greenlet and raise an exception in it.
Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever.
To raise an exception in a safe manner from any greenlet, use :meth:`kill`.
If a greenlet was started but never switched to yet, then also
a) cancel the event that will start it
b) fire the notifications as if an exception was raised in a greenlet
|
throw
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def start(self):
"""Schedule the greenlet to run in this loop iteration"""
if self._start_event is None:
self._start_event = self.parent.loop.run_callback(self.switch)
|
Schedule the greenlet to run in this loop iteration
|
start
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def start_later(self, seconds):
"""Schedule the greenlet to run in the future loop iteration *seconds* later"""
if self._start_event is None:
self._start_event = self.parent.loop.timer(seconds)
self._start_event.start(self.switch)
|
Schedule the greenlet to run in the future loop iteration *seconds* later
|
start_later
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def spawn(cls, *args, **kwargs):
"""
Create a new :class:`Greenlet` object and schedule it to run ``function(*args, **kwargs)``.
This can be used as ``gevent.spawn`` or ``Greenlet.spawn``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
"""
g = cls(*args, **kwargs)
g.start()
return g
|
Create a new :class:`Greenlet` object and schedule it to run ``function(*args, **kwargs)``.
This can be used as ``gevent.spawn`` or ``Greenlet.spawn``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
|
spawn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def spawn_later(cls, seconds, *args, **kwargs):
"""
Create and return a new Greenlet object scheduled to run ``function(*args, **kwargs)``
in the future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later``
or ``gevent.spawn_later``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If an argument that's meant to be a function (the first argument in *args*, or the ``run`` keyword )
is given to this classmethod (and not a classmethod of a subclass),
it is verified to be callable. Previously, the spawned greenlet would have failed
when it started running.
"""
if cls is Greenlet and not args and 'run' not in kwargs:
raise TypeError("")
g = cls(*args, **kwargs)
g.start_later(seconds)
return g
|
Create and return a new Greenlet object scheduled to run ``function(*args, **kwargs)``
in the future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later``
or ``gevent.spawn_later``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If an argument that's meant to be a function (the first argument in *args*, or the ``run`` keyword )
is given to this classmethod (and not a classmethod of a subclass),
it is verified to be callable. Previously, the spawned greenlet would have failed
when it started running.
|
spawn_later
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def kill(self, exception=GreenletExit, block=True, timeout=None):
"""
Raise the ``exception`` in the greenlet.
If ``block`` is ``True`` (the default), wait until the greenlet dies or the optional timeout expires.
If block is ``False``, the current greenlet is not unscheduled.
The function always returns ``None`` and never raises an error.
.. note::
Depending on what this greenlet is executing and the state
of the event loop, the exception may or may not be raised
immediately when this greenlet resumes execution. It may
be raised on a subsequent green call, or, if this greenlet
exits before making such a call, it may not be raised at
all. As of 1.1, an example where the exception is raised
later is if this greenlet had called :func:`sleep(0)
<gevent.sleep>`; an example where the exception is raised
immediately is if this greenlet had called
:func:`sleep(0.1) <gevent.sleep>`.
See also :func:`gevent.kill`.
:keyword type exception: The type of exception to raise in the greenlet. The default
is :class:`GreenletExit`, which indicates a :meth:`successful` completion
of the greenlet.
.. versionchanged:: 0.13.0
*block* is now ``True`` by default.
.. versionchanged:: 1.1a2
If this greenlet had never been switched to, killing it will prevent it from ever being switched to.
"""
self.__cancel_start()
if self.dead:
self.__handle_death_before_start(exception)
else:
waiter = Waiter() if block else None
self.parent.loop.run_callback(_kill, self, exception, waiter)
if block:
waiter.get()
self.join(timeout)
# it should be OK to use kill() in finally or kill a greenlet from more than one place;
# thus it should not raise when the greenlet is already killed (= not started)
|
Raise the ``exception`` in the greenlet.
If ``block`` is ``True`` (the default), wait until the greenlet dies or the optional timeout expires.
If block is ``False``, the current greenlet is not unscheduled.
The function always returns ``None`` and never raises an error.
.. note::
Depending on what this greenlet is executing and the state
of the event loop, the exception may or may not be raised
immediately when this greenlet resumes execution. It may
be raised on a subsequent green call, or, if this greenlet
exits before making such a call, it may not be raised at
all. As of 1.1, an example where the exception is raised
later is if this greenlet had called :func:`sleep(0)
<gevent.sleep>`; an example where the exception is raised
immediately is if this greenlet had called
:func:`sleep(0.1) <gevent.sleep>`.
See also :func:`gevent.kill`.
:keyword type exception: The type of exception to raise in the greenlet. The default
is :class:`GreenletExit`, which indicates a :meth:`successful` completion
of the greenlet.
.. versionchanged:: 0.13.0
*block* is now ``True`` by default.
.. versionchanged:: 1.1a2
If this greenlet had never been switched to, killing it will prevent it from ever being switched to.
|
kill
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Return the result the greenlet has returned or re-raise the exception it has raised.
If block is ``False``, raise :class:`gevent.Timeout` if the greenlet is still alive.
If block is ``True``, unschedule the current greenlet until the result is available
or the timeout expires. In the latter case, :class:`gevent.Timeout` is raised.
"""
if self.ready():
if self.successful():
return self.value
self._raise_exception()
if not block:
raise Timeout()
switch = getcurrent().switch
self.rawlink(switch)
try:
t = Timeout._start_new_or_dummy(timeout)
try:
result = self.parent.switch()
if result is not self:
raise InvalidSwitchError('Invalid switch into Greenlet.get(): %r' % (result, ))
finally:
t.cancel()
except:
# unlinking in 'except' instead of finally is an optimization:
# if switch occurred normally then link was already removed in _notify_links
# and there's no need to touch the links set.
# Note, however, that if "Invalid switch" assert was removed and invalid switch
# did happen, the link would remain, causing another invalid switch later in this greenlet.
self.unlink(switch)
raise
if self.ready():
if self.successful():
return self.value
self._raise_exception()
|
Return the result the greenlet has returned or re-raise the exception it has raised.
If block is ``False``, raise :class:`gevent.Timeout` if the greenlet is still alive.
If block is ``True``, unschedule the current greenlet until the result is available
or the timeout expires. In the latter case, :class:`gevent.Timeout` is raised.
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/greenlet.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.