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 copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = MD2Hash()
result = _raw_md2_lib.md2_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying MD2" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/MD2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/MD2.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_md4_lib.md4_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating MD4"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/MD4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/MD4.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that
has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_md4_lib.md4_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating MD4"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that
has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/MD4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/MD4.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = MD4Hash()
result = _raw_md4_lib.md4_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying MD4" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/MD4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/MD4.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_ripemd160_lib.ripemd160_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating ripemd160"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that
has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_ripemd160_lib.ripemd160_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating ripemd160"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that
has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = RIPEMD160Hash()
result = _raw_ripemd160_lib.ripemd160_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying ripemd160" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/RIPEMD160.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha224_lib.SHA224_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha224_lib.SHA224_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA224Hash()
result = _raw_sha224_lib.SHA224_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA224" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA224.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha256_lib.SHA256_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA256"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha256_lib.SHA256_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA256"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA256Hash()
result = _raw_sha256_lib.SHA256_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA256" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA256.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha384_lib.SHA384_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA384"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha384_lib.SHA384_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA384"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA384Hash()
result = _raw_sha384_lib.SHA384_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA384" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA384.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._digest_done and not self._update_after_digest:
raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHA-3/224"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
self._digest_done = True
bfr = create_string_buffer(self.digest_size)
result = _raw_keccak_lib.keccak_digest(self._state.get(),
bfr,
c_size_t(self.digest_size))
if result:
raise ValueError("Error %d while instantiating SHA-3/224"
% result)
self._digest_value = get_raw_buffer(bfr)
return self._digest_value
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
MIT
|
def new(*args, **kwargs):
"""Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_224_Hash` object
"""
data = kwargs.pop("data", None)
update_after_digest = kwargs.pop("update_after_digest", False)
if len(args) == 1:
if data:
raise ValueError("Initial data for hash specified twice")
data = args[0]
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
return SHA3_224_Hash(data, update_after_digest)
|
Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_224_Hash` object
|
new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_224.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._digest_done and not self._update_after_digest:
raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHA-3/256"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
self._digest_done = True
bfr = create_string_buffer(self.digest_size)
result = _raw_keccak_lib.keccak_digest(self._state.get(),
bfr,
c_size_t(self.digest_size))
if result:
raise ValueError("Error %d while instantiating SHA-3/256"
% result)
self._digest_value = get_raw_buffer(bfr)
return self._digest_value
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
MIT
|
def new(*args, **kwargs):
"""Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_256_Hash` object
"""
data = kwargs.pop("data", None)
update_after_digest = kwargs.pop("update_after_digest", False)
if len(args) == 1:
if data:
raise ValueError("Initial data for hash specified twice")
data = args[0]
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
return SHA3_256_Hash(data, update_after_digest)
|
Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_256_Hash` object
|
new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_256.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._digest_done and not self._update_after_digest:
raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHA-3/384"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
self._digest_done = True
bfr = create_string_buffer(self.digest_size)
result = _raw_keccak_lib.keccak_digest(self._state.get(),
bfr,
c_size_t(self.digest_size))
if result:
raise ValueError("Error %d while instantiating SHA-3/384"
% result)
self._digest_value = get_raw_buffer(bfr)
return self._digest_value
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
MIT
|
def new(*args, **kwargs):
"""Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_384_Hash` object
"""
data = kwargs.pop("data", None)
update_after_digest = kwargs.pop("update_after_digest", False)
if len(args) == 1:
if data:
raise ValueError("Initial data for hash specified twice")
data = args[0]
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
return SHA3_384_Hash(data, update_after_digest)
|
Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_384_Hash` object
|
new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_384.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._digest_done and not self._update_after_digest:
raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHA-3/512"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
self._digest_done = True
bfr = create_string_buffer(self.digest_size)
result = _raw_keccak_lib.keccak_digest(self._state.get(),
bfr,
c_size_t(self.digest_size))
if result:
raise ValueError("Error %d while instantiating SHA-3/512"
% result)
self._digest_value = get_raw_buffer(bfr)
return self._digest_value
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
You cannot update the hash anymore after the first call to ``digest``
(or ``hexdigest``).
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
MIT
|
def new(*args, **kwargs):
"""Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_512_Hash` object
"""
data = kwargs.pop("data", None)
update_after_digest = kwargs.pop("update_after_digest", False)
if len(args) == 1:
if data:
raise ValueError("Initial data for hash specified twice")
data = args[0]
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
return SHA3_512_Hash(data, update_after_digest)
|
Return a fresh instance of the hash object.
:Keywords:
data : byte string
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to ``update()``.
update_after_digest : boolean
Optional. By default, a hash object cannot be updated anymore after
the digest is computed. When this flag is ``True``, such check
is no longer enforced.
:Return: A `SHA3_512_Hash` object
|
new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA3_512.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha512_lib.SHA512_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA512"
% result)
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
MIT
|
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha512_lib.SHA512_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA512"
% result)
return get_raw_buffer(bfr)
|
Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
|
digest
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
MIT
|
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA512Hash()
result = _raw_sha512_lib.SHA512_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA512" % result)
return clone
|
Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
|
copy
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHA512.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
You cannot use ``update`` anymore after the first call to ``read``.
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._is_squeezing:
raise TypeError("You cannot call 'update' after the first 'read'")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHAKE128 state"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
You cannot use ``update`` anymore after the first call to ``read``.
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHAKE128.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHAKE128.py
|
MIT
|
def read(self, length):
"""Return the next ``length`` bytes of **binary** (non-printable)
digest for the message.
You cannot use ``update`` anymore after the first call to ``read``.
:Return: A byte string of `length` bytes.
"""
self._is_squeezing = True
bfr = create_string_buffer(length)
result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
bfr,
c_size_t(length))
if result:
raise ValueError("Error %d while extracting from SHAKE128"
% result)
return get_raw_buffer(bfr)
|
Return the next ``length`` bytes of **binary** (non-printable)
digest for the message.
You cannot use ``update`` anymore after the first call to ``read``.
:Return: A byte string of `length` bytes.
|
read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHAKE128.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHAKE128.py
|
MIT
|
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
You cannot use ``update`` anymore after the first call to ``read``.
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
if self._is_squeezing:
raise TypeError("You cannot call 'update' after the first 'read'")
expect_byte_string(data)
result = _raw_keccak_lib.keccak_absorb(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while updating SHAKE256 state"
% result)
return self
|
Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
You cannot use ``update`` anymore after the first call to ``read``.
:Parameters:
data : byte string
The next chunk of the message being hashed.
|
update
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHAKE256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHAKE256.py
|
MIT
|
def read(self, length):
"""Return the next ``length`` bytes of **binary** (non-printable)
digest for the message.
You cannot use ``update`` anymore after the first call to ``read``.
:Return: A byte string of `length` bytes.
"""
self._is_squeezing = True
bfr = create_string_buffer(length)
result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
bfr,
c_size_t(length))
if result:
raise ValueError("Error %d while extracting from SHAKE256"
% result)
return get_raw_buffer(bfr)
|
Return the next ``length`` bytes of **binary** (non-printable)
digest for the message.
You cannot use ``update`` anymore after the first call to ``read``.
:Return: A byte string of `length` bytes.
|
read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Hash/SHAKE256.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Hash/SHAKE256.py
|
MIT
|
def encode(data, marker, passphrase=None, randfunc=None):
"""Encode a piece of binary data into PEM format.
:Parameters:
data : byte string
The piece of binary data to encode.
marker : string
The marker for the PEM block (e.g. "PUBLIC KEY").
Note that there is no official master list for all allowed markers.
Still, you can refer to the OpenSSL_ source code.
passphrase : byte string
If given, the PEM block will be encrypted. The key is derived from
the passphrase.
randfunc : callable
Random number generation function; it accepts an integer N and returns
a byte string of random data, N bytes long. If not given, a new one is
instantiated.
:Returns:
The PEM block, as a string.
.. _OpenSSL: http://cvs.openssl.org/fileview?f=openssl/crypto/pem/pem.h&v=1.66.2.1.4.2
"""
if randfunc is None:
randfunc = get_random_bytes
out = "-----BEGIN %s-----\n" % marker
if passphrase:
# We only support 3DES for encryption
salt = randfunc(8)
key = PBKDF1(passphrase, salt, 16, 1, MD5)
key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
objenc = DES3.new(key, DES3.MODE_CBC, salt)
out += "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n" %\
tostr(hexlify(salt).upper())
# Encrypt with PKCS#7 padding
data = objenc.encrypt(pad(data, objenc.block_size))
elif passphrase is not None:
raise ValueError("Empty password")
# Each BASE64 line can take up to 64 characters (=48 bytes of data)
# b2a_base64 adds a new line character!
chunks = [tostr(b2a_base64(data[i:i + 48]))
for i in range(0, len(data), 48)]
out += "".join(chunks)
out += "-----END %s-----" % marker
return out
|
Encode a piece of binary data into PEM format.
:Parameters:
data : byte string
The piece of binary data to encode.
marker : string
The marker for the PEM block (e.g. "PUBLIC KEY").
Note that there is no official master list for all allowed markers.
Still, you can refer to the OpenSSL_ source code.
passphrase : byte string
If given, the PEM block will be encrypted. The key is derived from
the passphrase.
randfunc : callable
Random number generation function; it accepts an integer N and returns
a byte string of random data, N bytes long. If not given, a new one is
instantiated.
:Returns:
The PEM block, as a string.
.. _OpenSSL: http://cvs.openssl.org/fileview?f=openssl/crypto/pem/pem.h&v=1.66.2.1.4.2
|
encode
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/PEM.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/PEM.py
|
MIT
|
def decode(pem_data, passphrase=None):
"""Decode a PEM block into binary.
:Parameters:
pem_data : string
The PEM block.
passphrase : byte string
If given and the PEM block is encrypted,
the key will be derived from the passphrase.
:Returns:
A tuple with the binary data, the marker string, and a boolean to
indicate if decryption was performed.
:Raises ValueError:
If decoding fails, if the PEM file is encrypted and no passphrase has
been provided or if the passphrase is incorrect.
"""
# Verify Pre-Encapsulation Boundary
r = re.compile("\s*-----BEGIN (.*)-----\s+")
m = r.match(pem_data)
if not m:
raise ValueError("Not a valid PEM pre boundary")
marker = m.group(1)
# Verify Post-Encapsulation Boundary
r = re.compile("-----END (.*)-----\s*$")
m = r.search(pem_data)
if not m or m.group(1) != marker:
raise ValueError("Not a valid PEM post boundary")
# Removes spaces and slit on lines
lines = pem_data.replace(" ", '').split()
# Decrypts, if necessary
if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
if not passphrase:
raise ValueError("PEM is encrypted, but no passphrase available")
DEK = lines[2].split(':')
if len(DEK) != 2 or DEK[0] != 'DEK-Info':
raise ValueError("PEM encryption format not supported.")
algo, salt = DEK[1].split(',')
salt = unhexlify(tobytes(salt))
if algo == "DES-CBC":
# This is EVP_BytesToKey in OpenSSL
key = PBKDF1(passphrase, salt, 8, 1, MD5)
objdec = DES.new(key, DES.MODE_CBC, salt)
elif algo == "DES-EDE3-CBC":
# Note that EVP_BytesToKey is note exactly the same as PBKDF1
key = PBKDF1(passphrase, salt, 16, 1, MD5)
key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
objdec = DES3.new(key, DES3.MODE_CBC, salt)
elif algo == "AES-128-CBC":
key = PBKDF1(passphrase, salt[:8], 16, 1, MD5)
objdec = AES.new(key, AES.MODE_CBC, salt)
else:
raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
lines = lines[2:]
else:
objdec = None
# Decode body
data = a2b_base64(b(''.join(lines[1:-1])))
enc_flag = False
if objdec:
data = unpad(objdec.decrypt(data), objdec.block_size)
enc_flag = True
return (data, marker, enc_flag)
|
Decode a PEM block into binary.
:Parameters:
pem_data : string
The PEM block.
passphrase : byte string
If given and the PEM block is encrypted,
the key will be derived from the passphrase.
:Returns:
A tuple with the binary data, the marker string, and a boolean to
indicate if decryption was performed.
:Raises ValueError:
If decoding fails, if the PEM file is encrypted and no passphrase has
been provided or if the passphrase is incorrect.
|
decode
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/PEM.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/PEM.py
|
MIT
|
def wrap(private_key, key_oid, passphrase=None, protection=None,
prot_params=None, key_params=None, randfunc=None):
"""Wrap a private key into a PKCS#8 blob (clear or encrypted).
:Parameters:
private_key : byte string
The private key encoded in binary form. The actual encoding is
algorithm specific. In most cases, it is DER.
key_oid : string
The object identifier (OID) of the private key to wrap.
It is a dotted string, like "``1.2.840.113549.1.1.1``" (for RSA keys).
passphrase : (binary) string
The secret passphrase from which the wrapping key is derived.
Set it only if encryption is required.
protection : string
The identifier of the algorithm to use for securely wrapping the key.
The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
prot_params : dictionary
Parameters for the protection algorithm.
+------------------+-----------------------------------------------+
| Key | Description |
+==================+===============================================+
| iteration_count | The KDF algorithm is repeated several times to|
| | slow down brute force attacks on passwords |
| | (called *N* or CPU/memory cost in scrypt). |
| | |
| | The default value for PBKDF2 is 1 000. |
| | The default value for scrypt is 16 384. |
+------------------+-----------------------------------------------+
| salt_size | Salt is used to thwart dictionary and rainbow |
| | attacks on passwords. The default value is 8 |
| | bytes. |
+------------------+-----------------------------------------------+
| block_size | *(scrypt only)* Memory-cost (r). The default |
| | value is 8. |
+------------------+-----------------------------------------------+
| parallelization | *(scrypt only)* CPU-cost (p). The default |
| | value is 1. |
+------------------+-----------------------------------------------+
key_params : DER object
The algorithm parameters associated to the private key.
It is required for algorithms like DSA, but not for others like RSA.
randfunc : callable
Random number generation function; it should accept a single integer
N and return a string of random data, N bytes long.
If not specified, a new RNG will be instantiated
from ``Cryptodome.Random``.
:Return:
The PKCS#8-wrapped private key (possibly encrypted),
as a binary string.
"""
if key_params is None:
key_params = DerNull()
#
# PrivateKeyInfo ::= SEQUENCE {
# version Version,
# privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
# privateKey PrivateKey,
# attributes [0] IMPLICIT Attributes OPTIONAL
# }
#
pk_info = DerSequence([
0,
DerSequence([
DerObjectId(key_oid),
key_params
]),
DerOctetString(private_key)
])
pk_info_der = pk_info.encode()
if passphrase is None:
return pk_info_der
if not passphrase:
raise ValueError("Empty passphrase")
# Encryption with PBES2
passphrase = tobytes(passphrase)
if protection is None:
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
return PBES2.encrypt(pk_info_der, passphrase,
protection, prot_params, randfunc)
|
Wrap a private key into a PKCS#8 blob (clear or encrypted).
:Parameters:
private_key : byte string
The private key encoded in binary form. The actual encoding is
algorithm specific. In most cases, it is DER.
key_oid : string
The object identifier (OID) of the private key to wrap.
It is a dotted string, like "``1.2.840.113549.1.1.1``" (for RSA keys).
passphrase : (binary) string
The secret passphrase from which the wrapping key is derived.
Set it only if encryption is required.
protection : string
The identifier of the algorithm to use for securely wrapping the key.
The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
prot_params : dictionary
Parameters for the protection algorithm.
+------------------+-----------------------------------------------+
| Key | Description |
+==================+===============================================+
| iteration_count | The KDF algorithm is repeated several times to|
| | slow down brute force attacks on passwords |
| | (called *N* or CPU/memory cost in scrypt). |
| | |
| | The default value for PBKDF2 is 1 000. |
| | The default value for scrypt is 16 384. |
+------------------+-----------------------------------------------+
| salt_size | Salt is used to thwart dictionary and rainbow |
| | attacks on passwords. The default value is 8 |
| | bytes. |
+------------------+-----------------------------------------------+
| block_size | *(scrypt only)* Memory-cost (r). The default |
| | value is 8. |
+------------------+-----------------------------------------------+
| parallelization | *(scrypt only)* CPU-cost (p). The default |
| | value is 1. |
+------------------+-----------------------------------------------+
key_params : DER object
The algorithm parameters associated to the private key.
It is required for algorithms like DSA, but not for others like RSA.
randfunc : callable
Random number generation function; it should accept a single integer
N and return a string of random data, N bytes long.
If not specified, a new RNG will be instantiated
from ``Cryptodome.Random``.
:Return:
The PKCS#8-wrapped private key (possibly encrypted),
as a binary string.
|
wrap
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/PKCS8.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/PKCS8.py
|
MIT
|
def unwrap(p8_private_key, passphrase=None):
"""Unwrap a private key from a PKCS#8 blob (clear or encrypted).
:Parameters:
p8_private_key : byte string
The private key wrapped into a PKCS#8 blob, DER encoded.
passphrase : (byte) string
The passphrase to use to decrypt the blob (if it is encrypted).
:Return:
A tuple containing:
#. the algorithm identifier of the wrapped key (OID, dotted string)
#. the private key (byte string, DER encoded)
#. the associated parameters (byte string, DER encoded) or ``None``
:Raises ValueError:
If decoding fails
"""
if passphrase:
passphrase = tobytes(passphrase)
found = False
try:
p8_private_key = PBES1.decrypt(p8_private_key, passphrase)
found = True
except PbesError, e:
error_str = "PBES1[%s]" % str(e)
except ValueError:
error_str = "PBES1[Invalid]"
if not found:
try:
p8_private_key = PBES2.decrypt(p8_private_key, passphrase)
found = True
except PbesError, e:
error_str += ",PBES2[%s]" % str(e)
except ValueError:
error_str += ",PBES2[Invalid]"
if not found:
raise ValueError("Error decoding PKCS#8 (%s)" % error_str)
pk_info = DerSequence().decode(p8_private_key, nr_elements=(2, 3, 4))
if len(pk_info) == 2 and not passphrase:
raise ValueError("Not a valid clear PKCS#8 structure "
"(maybe it is encrypted?)")
#
# PrivateKeyInfo ::= SEQUENCE {
# version Version,
# privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
# privateKey PrivateKey,
# attributes [0] IMPLICIT Attributes OPTIONAL
# }
# Version ::= INTEGER
if pk_info[0] != 0:
raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
# PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
#
# EncryptedPrivateKeyInfo ::= SEQUENCE {
# encryptionAlgorithm EncryptionAlgorithmIdentifier,
# encryptedData EncryptedData
# }
# EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
# AlgorithmIdentifier ::= SEQUENCE {
# algorithm OBJECT IDENTIFIER,
# parameters ANY DEFINED BY algorithm OPTIONAL
# }
algo = DerSequence().decode(pk_info[1], nr_elements=(1, 2))
algo_oid = DerObjectId().decode(algo[0]).value
if len(algo) == 1:
algo_params = None
else:
try:
DerNull().decode(algo[1])
algo_params = None
except:
algo_params = algo[1]
# EncryptedData ::= OCTET STRING
private_key = DerOctetString().decode(pk_info[2]).payload
return (algo_oid, private_key, algo_params)
|
Unwrap a private key from a PKCS#8 blob (clear or encrypted).
:Parameters:
p8_private_key : byte string
The private key wrapped into a PKCS#8 blob, DER encoded.
passphrase : (byte) string
The passphrase to use to decrypt the blob (if it is encrypted).
:Return:
A tuple containing:
#. the algorithm identifier of the wrapped key (OID, dotted string)
#. the private key (byte string, DER encoded)
#. the associated parameters (byte string, DER encoded) or ``None``
:Raises ValueError:
If decoding fails
|
unwrap
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/PKCS8.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/PKCS8.py
|
MIT
|
def decrypt(data, passphrase):
"""Decrypt a piece of data using a passphrase and *PBES1*.
The algorithm to use is automatically detected.
:Parameters:
data : byte string
The piece of data to decrypt.
passphrase : byte string
The passphrase to use for decrypting the data.
:Returns:
The decrypted data, as a binary string.
"""
enc_private_key_info = DerSequence().decode(data)
encrypted_algorithm = DerSequence().decode(enc_private_key_info[0])
encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
pbe_oid = DerObjectId().decode(encrypted_algorithm[0]).value
cipher_params = {}
if pbe_oid == "1.2.840.113549.1.5.3":
# PBE_MD5_DES_CBC
hashmod = MD5
ciphermod = DES
elif pbe_oid == "1.2.840.113549.1.5.6":
# PBE_MD5_RC2_CBC
hashmod = MD5
ciphermod = ARC2
cipher_params['effective_keylen'] = 64
elif pbe_oid == "1.2.840.113549.1.5.10":
# PBE_SHA1_DES_CBC
hashmod = SHA1
ciphermod = DES
elif pbe_oid == "1.2.840.113549.1.5.11":
# PBE_SHA1_RC2_CBC
hashmod = SHA1
ciphermod = ARC2
cipher_params['effective_keylen'] = 64
else:
raise PbesError("Unknown OID for PBES1")
pbe_params = DerSequence().decode(encrypted_algorithm[1], nr_elements=2)
salt = DerOctetString().decode(pbe_params[0]).payload
iterations = pbe_params[1]
key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod)
key, iv = key_iv[:8], key_iv[8:]
cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params)
pt = cipher.decrypt(encrypted_data)
return unpad(pt, cipher.block_size)
|
Decrypt a piece of data using a passphrase and *PBES1*.
The algorithm to use is automatically detected.
:Parameters:
data : byte string
The piece of data to decrypt.
passphrase : byte string
The passphrase to use for decrypting the data.
:Returns:
The decrypted data, as a binary string.
|
decrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/_PBES.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/_PBES.py
|
MIT
|
def encrypt(data, passphrase, protection, prot_params=None, randfunc=None):
"""Encrypt a piece of data using a passphrase and *PBES2*.
:Parameters:
data : byte string
The piece of data to encrypt.
passphrase : byte string
The passphrase to use for encrypting the data.
protection : string
The identifier of the encryption algorithm to use.
The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
prot_params : dictionary
Parameters of the protection algorithm.
+------------------+-----------------------------------------------+
| Key | Description |
+==================+===============================================+
| iteration_count | The KDF algorithm is repeated several times to|
| | slow down brute force attacks on passwords |
| | (called *N* or CPU/memory cost in scrypt). |
| | |
| | The default value for PBKDF2 is 1 000. |
| | The default value for scrypt is 16 384. |
+------------------+-----------------------------------------------+
| salt_size | Salt is used to thwart dictionary and rainbow |
| | attacks on passwords. The default value is 8 |
| | bytes. |
+------------------+-----------------------------------------------+
| block_size | *(scrypt only)* Memory-cost (r). The default |
| | value is 8. |
+------------------+-----------------------------------------------+
| parallelization | *(scrypt only)* CPU-cost (p). The default |
| | value is 1. |
+------------------+-----------------------------------------------+
randfunc : callable
Random number generation function; it should accept
a single integer N and return a string of random data,
N bytes long. If not specified, a new RNG will be
instantiated from ``Cryptodome.Random``.
:Returns:
The encrypted data, as a binary string.
"""
if prot_params is None:
prot_params = {}
if randfunc is None:
randfunc = Random.new().read
if protection == 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC':
key_size = 24
module = DES3
cipher_mode = DES3.MODE_CBC
enc_oid = "1.2.840.113549.3.7"
elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC',
'scryptAndAES128-CBC'):
key_size = 16
module = AES
cipher_mode = AES.MODE_CBC
enc_oid = "2.16.840.1.101.3.4.1.2"
elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC',
'scryptAndAES192-CBC'):
key_size = 24
module = AES
cipher_mode = AES.MODE_CBC
enc_oid = "2.16.840.1.101.3.4.1.22"
elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC',
'scryptAndAES256-CBC'):
key_size = 32
module = AES
cipher_mode = AES.MODE_CBC
enc_oid = "2.16.840.1.101.3.4.1.42"
else:
raise ValueError("Unknown PBES2 mode")
# Get random data
iv = randfunc(module.block_size)
salt = randfunc(prot_params.get("salt_size", 8))
# Derive key from password
if protection.startswith('PBKDF2'):
count = prot_params.get("iteration_count", 1000)
key = PBKDF2(passphrase, salt, key_size, count)
kdf_info = DerSequence([
DerObjectId("1.2.840.113549.1.5.12"), # PBKDF2
DerSequence([
DerOctetString(salt),
DerInteger(count)
])
])
else:
# It must be scrypt
count = prot_params.get("iteration_count", 16384)
scrypt_r = prot_params.get('block_size', 8)
scrypt_p = prot_params.get('parallelization', 1)
key = scrypt(passphrase, salt, key_size,
count, scrypt_r, scrypt_p)
kdf_info = DerSequence([
DerObjectId("1.3.6.1.4.1.11591.4.11"), # scrypt
DerSequence([
DerOctetString(salt),
DerInteger(count),
DerInteger(scrypt_r),
DerInteger(scrypt_p)
])
])
# Create cipher and use it
cipher = module.new(key, cipher_mode, iv)
encrypted_data = cipher.encrypt(pad(data, cipher.block_size))
enc_info = DerSequence([
DerObjectId(enc_oid),
DerOctetString(iv)
])
# Result
enc_private_key_info = DerSequence([
# encryptionAlgorithm
DerSequence([
DerObjectId("1.2.840.113549.1.5.13"), # PBES2
DerSequence([
kdf_info,
enc_info
]),
]),
DerOctetString(encrypted_data)
])
return enc_private_key_info.encode()
|
Encrypt a piece of data using a passphrase and *PBES2*.
:Parameters:
data : byte string
The piece of data to encrypt.
passphrase : byte string
The passphrase to use for encrypting the data.
protection : string
The identifier of the encryption algorithm to use.
The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
prot_params : dictionary
Parameters of the protection algorithm.
+------------------+-----------------------------------------------+
| Key | Description |
+==================+===============================================+
| iteration_count | The KDF algorithm is repeated several times to|
| | slow down brute force attacks on passwords |
| | (called *N* or CPU/memory cost in scrypt). |
| | |
| | The default value for PBKDF2 is 1 000. |
| | The default value for scrypt is 16 384. |
+------------------+-----------------------------------------------+
| salt_size | Salt is used to thwart dictionary and rainbow |
| | attacks on passwords. The default value is 8 |
| | bytes. |
+------------------+-----------------------------------------------+
| block_size | *(scrypt only)* Memory-cost (r). The default |
| | value is 8. |
+------------------+-----------------------------------------------+
| parallelization | *(scrypt only)* CPU-cost (p). The default |
| | value is 1. |
+------------------+-----------------------------------------------+
randfunc : callable
Random number generation function; it should accept
a single integer N and return a string of random data,
N bytes long. If not specified, a new RNG will be
instantiated from ``Cryptodome.Random``.
:Returns:
The encrypted data, as a binary string.
|
encrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/_PBES.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/_PBES.py
|
MIT
|
def decrypt(data, passphrase):
"""Decrypt a piece of data using a passphrase and *PBES2*.
The algorithm to use is automatically detected.
:Parameters:
data : byte string
The piece of data to decrypt.
passphrase : byte string
The passphrase to use for decrypting the data.
:Returns:
The decrypted data, as a binary string.
"""
enc_private_key_info = DerSequence().decode(data, nr_elements=2)
enc_algo = DerSequence().decode(enc_private_key_info[0])
encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
pbe_oid = DerObjectId().decode(enc_algo[0]).value
if pbe_oid != "1.2.840.113549.1.5.13":
raise PbesError("Not a PBES2 object")
pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2)
### Key Derivation Function selection
kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2)
kdf_oid = DerObjectId().decode(kdf_info[0]).value
# We only support PBKDF2 or scrypt
if kdf_oid == "1.2.840.113549.1.5.12":
pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4))
salt = DerOctetString().decode(pbkdf2_params[0]).payload
iteration_count = pbkdf2_params[1]
if len(pbkdf2_params) > 2:
kdf_key_length = pbkdf2_params[2]
else:
kdf_key_length = None
if len(pbkdf2_params) > 3:
raise PbesError("Unsupported PRF for PBKDF2")
elif kdf_oid == "1.3.6.1.4.1.11591.4.11":
scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5))
salt = DerOctetString().decode(scrypt_params[0]).payload
iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
for x in (1, 2, 3)]
if len(scrypt_params) > 4:
kdf_key_length = scrypt_params[4]
else:
kdf_key_length = None
else:
raise PbesError("Unsupported PBES2 KDF")
### Cipher selection
enc_info = DerSequence().decode(pbes2_params[1])
enc_oid = DerObjectId().decode(enc_info[0]).value
if enc_oid == "1.2.840.113549.3.7":
# DES_EDE3_CBC
ciphermod = DES3
key_size = 24
elif enc_oid == "2.16.840.1.101.3.4.1.2":
# AES128_CBC
ciphermod = AES
key_size = 16
elif enc_oid == "2.16.840.1.101.3.4.1.22":
# AES192_CBC
ciphermod = AES
key_size = 24
elif enc_oid == "2.16.840.1.101.3.4.1.42":
# AES256_CBC
ciphermod = AES
key_size = 32
else:
raise PbesError("Unsupported PBES2 cipher")
if kdf_key_length and kdf_key_length != key_size:
raise PbesError("Mismatch between PBES2 KDF parameters"
" and selected cipher")
IV = DerOctetString().decode(enc_info[1]).payload
# Create cipher
if kdf_oid == "1.2.840.113549.1.5.12": # PBKDF2
key = PBKDF2(passphrase, salt, key_size, iteration_count)
else:
key = scrypt(passphrase, salt, key_size, iteration_count,
scrypt_r, scrypt_p)
cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV)
# Decrypt data
pt = cipher.decrypt(encrypted_data)
return unpad(pt, cipher.block_size)
|
Decrypt a piece of data using a passphrase and *PBES2*.
The algorithm to use is automatically detected.
:Parameters:
data : byte string
The piece of data to decrypt.
passphrase : byte string
The passphrase to use for decrypting the data.
:Returns:
The decrypted data, as a binary string.
|
decrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/IO/_PBES.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/IO/_PBES.py
|
MIT
|
def _random(**kwargs):
"""Generate a random natural integer of a certain size.
:Keywords:
exact_bits : positive integer
The length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >= 2^(bits - 1)
max_bits : positive integer
The maximum length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >=0
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Return: a Integer object
"""
exact_bits = kwargs.pop("exact_bits", None)
max_bits = kwargs.pop("max_bits", None)
randfunc = kwargs.pop("randfunc", None)
if randfunc is None:
randfunc = Random.new().read
if exact_bits is None and max_bits is None:
raise ValueError("Either 'exact_bits' or 'max_bits' must be specified")
if exact_bits is not None and max_bits is not None:
raise ValueError("'exact_bits' and 'max_bits' are mutually exclusive")
bits = exact_bits or max_bits
bytes_needed = ((bits - 1) // 8) + 1
significant_bits_msb = 8 - (bytes_needed * 8 - bits)
msb = bord(randfunc(1)[0])
if exact_bits is not None:
msb |= 1 << (significant_bits_msb - 1)
msb &= (1 << significant_bits_msb) - 1
return Integer.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
|
Generate a random natural integer of a certain size.
:Keywords:
exact_bits : positive integer
The length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >= 2^(bits - 1)
max_bits : positive integer
The maximum length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >=0
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Return: a Integer object
|
_random
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Numbers.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Numbers.py
|
MIT
|
def _random_range(**kwargs):
"""Generate a random integer within a given internal.
:Keywords:
min_inclusive : integer
The lower end of the interval (inclusive).
max_inclusive : integer
The higher end of the interval (inclusive).
max_exclusive : integer
The higher end of the interval (exclusive).
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Returns:
An Integer randomly taken in the given interval.
"""
min_inclusive = kwargs.pop("min_inclusive", None)
max_inclusive = kwargs.pop("max_inclusive", None)
max_exclusive = kwargs.pop("max_exclusive", None)
randfunc = kwargs.pop("randfunc", None)
if kwargs:
raise ValueError("Unknown keywords: " + str(kwargs.keys))
if None not in (max_inclusive, max_exclusive):
raise ValueError("max_inclusive and max_exclusive cannot be both"
" specified")
if max_exclusive is not None:
max_inclusive = max_exclusive - 1
if None in (min_inclusive, max_inclusive):
raise ValueError("Missing keyword to identify the interval")
if randfunc is None:
randfunc = Random.new().read
norm_maximum = max_inclusive - min_inclusive
bits_needed = Integer(norm_maximum).size_in_bits()
norm_candidate = -1
while not 0 <= norm_candidate <= norm_maximum:
norm_candidate = _random(
max_bits=bits_needed,
randfunc=randfunc
)
return norm_candidate + min_inclusive
|
Generate a random integer within a given internal.
:Keywords:
min_inclusive : integer
The lower end of the interval (inclusive).
max_inclusive : integer
The higher end of the interval (inclusive).
max_exclusive : integer
The higher end of the interval (exclusive).
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Returns:
An Integer randomly taken in the given interval.
|
_random_range
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Numbers.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Numbers.py
|
MIT
|
def miller_rabin_test(candidate, iterations, randfunc=None):
"""Perform a Miller-Rabin primality test on an integer.
The test is specified in Section C.3.1 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
iterations : integer
The maximum number of iterations to perform before
declaring a candidate a probable prime.
randfunc : callable
An RNG function where bases are taken from.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
if candidate.is_even():
return COMPOSITE
one = Integer(1)
minus_one = Integer(candidate - 1)
if randfunc is None:
randfunc = Random.new().read
# Step 1 and 2
m = Integer(minus_one)
a = 0
while m.is_even():
m >>= 1
a += 1
# Skip step 3
# Step 4
for i in xrange(iterations):
# Step 4.1-2
base = 1
while base in (one, minus_one):
base = Integer.random_range(min_inclusive=2,
max_inclusive=candidate - 2)
assert(2 <= base <= candidate - 2)
# Step 4.3-4.4
z = pow(base, m, candidate)
if z in (one, minus_one):
continue
# Step 4.5
for j in xrange(1, a):
z = pow(z, 2, candidate)
if z == minus_one:
break
if z == one:
return COMPOSITE
else:
return COMPOSITE
# Step 5
return PROBABLY_PRIME
|
Perform a Miller-Rabin primality test on an integer.
The test is specified in Section C.3.1 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
iterations : integer
The maximum number of iterations to perform before
declaring a candidate a probable prime.
randfunc : callable
An RNG function where bases are taken from.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
miller_rabin_test
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Primality.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Primality.py
|
MIT
|
def lucas_test(candidate):
"""Perform a Lucas primality test on an integer.
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# Step 1
if candidate.is_even() or candidate.is_perfect_square():
return COMPOSITE
# Step 2
def alternate():
sgn = 1
value = 5
for x in xrange(10):
yield sgn * value
sgn, value = -sgn, value + 2
for D in alternate():
js = Integer.jacobi_symbol(D, candidate)
if js == 0:
return COMPOSITE
if js == -1:
break
else:
return COMPOSITE
# Found D. P=1 and Q=(1-D)/4 (note that Q is guaranteed to be an integer)
# Step 3
# This is \delta(n) = n - jacobi(D/n)
K = candidate + 1
# Step 4
r = K.size_in_bits() - 1
# Step 5
# U_1=1 and V_1=P
U_i = Integer(1)
V_i = Integer(1)
U_temp = Integer(0)
V_temp = Integer(0)
# Step 6
for i in xrange(r - 1, -1, -1):
# Square
# U_temp = U_i * V_i % candidate
U_temp.set(U_i)
U_temp *= V_i
U_temp %= candidate
# V_temp = (((V_i ** 2 + (U_i ** 2 * D)) * K) >> 1) % candidate
V_temp.set(U_i)
V_temp *= U_i
V_temp *= D
V_temp.multiply_accumulate(V_i, V_i)
if V_temp.is_odd():
V_temp += candidate
V_temp >>= 1
V_temp %= candidate
# Multiply
if K.get_bit(i):
# U_i = (((U_temp + V_temp) * K) >> 1) % candidate
U_i.set(U_temp)
U_i += V_temp
if U_i.is_odd():
U_i += candidate
U_i >>= 1
U_i %= candidate
# V_i = (((V_temp + U_temp * D) * K) >> 1) % candidate
V_i.set(V_temp)
V_i.multiply_accumulate(U_temp, D)
if V_i.is_odd():
V_i += candidate
V_i >>= 1
V_i %= candidate
else:
U_i.set(U_temp)
V_i.set(V_temp)
# Step 7
if U_i == 0:
return PROBABLY_PRIME
return COMPOSITE
|
Perform a Lucas primality test on an integer.
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
lucas_test
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Primality.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Primality.py
|
MIT
|
def test_probable_prime(candidate, randfunc=None):
"""Test if a number is prime.
A number is qualified as prime if it passes a certain
number of Miller-Rabin tests (dependent on the size
of the number, but such that probability of a false
positive is less than 10^-30) and a single Lucas test.
For instance, a 1024-bit candidate will need to pass
4 Miller-Rabin tests.
:Parameters:
candidate : integer
The number to test for primality.
randfunc : callable
The routine to draw random bytes from to select Miller-Rabin bases.
:Returns:
``PROBABLE_PRIME`` if the number if prime with very high probability.
``COMPOSITE`` if the number is a composite.
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
"""
if randfunc is None:
randfunc = Random.new().read
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# First, check trial division by the smallest primes
try:
map(candidate.fail_if_divisible_by, _sieve_base)
except ValueError:
return False
# These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
# with p(k, t) being the probability that a randomly chosen k-bit number
# is composite but still survives t MR iterations.
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
(620, 7), (740, 6), (890, 5), (1200, 4),
(1700, 3), (3700, 2))
bit_size = candidate.size_in_bits()
try:
mr_iterations = list(filter(lambda x: bit_size < x[0],
mr_ranges))[0][1]
except IndexError:
mr_iterations = 1
if miller_rabin_test(candidate, mr_iterations,
randfunc=randfunc) == COMPOSITE:
return COMPOSITE
if lucas_test(candidate) == COMPOSITE:
return COMPOSITE
return PROBABLY_PRIME
|
Test if a number is prime.
A number is qualified as prime if it passes a certain
number of Miller-Rabin tests (dependent on the size
of the number, but such that probability of a false
positive is less than 10^-30) and a single Lucas test.
For instance, a 1024-bit candidate will need to pass
4 Miller-Rabin tests.
:Parameters:
candidate : integer
The number to test for primality.
randfunc : callable
The routine to draw random bytes from to select Miller-Rabin bases.
:Returns:
``PROBABLE_PRIME`` if the number if prime with very high probability.
``COMPOSITE`` if the number is a composite.
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
|
test_probable_prime
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Primality.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Primality.py
|
MIT
|
def generate_probable_prime(**kwargs):
"""Generate a random probable prime.
The prime will not have any specific properties
(e.g. it will not be a *strong* prime).
Random numbers are evaluated for primality until one
passes all tests, consisting of a certain number of
Miller-Rabin tests with random bases followed by
a single Lucas test.
The number of Miller-Rabin iterations is chosen such that
the probability that the output number is a non-prime is
less than 1E-30 (roughly 2^{-100}).
This approach is compliant to `FIPS PUB 186-4`__.
:Keywords:
exact_bits : integer
The desired size in bits of the probable prime.
It must be at least 160.
randfunc : callable
An RNG function where candidate primes are taken from.
prime_filter : callable
A function that takes an Integer as parameter and returns
True if the number can be passed to further primality tests,
False if it should be immediately discarded.
:Return:
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
prime_filter = kwargs.pop("prime_filter", lambda x: True)
if kwargs:
print "Unknown parameters:", kwargs.keys()
if exact_bits is None:
raise ValueError("Missing exact_bits parameter")
if exact_bits < 160:
raise ValueError("Prime number is not big enough.")
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
candidate = Integer.random(exact_bits=exact_bits,
randfunc=randfunc) | 1
if not prime_filter(candidate):
continue
result = test_probable_prime(candidate, randfunc)
return candidate
|
Generate a random probable prime.
The prime will not have any specific properties
(e.g. it will not be a *strong* prime).
Random numbers are evaluated for primality until one
passes all tests, consisting of a certain number of
Miller-Rabin tests with random bases followed by
a single Lucas test.
The number of Miller-Rabin iterations is chosen such that
the probability that the output number is a non-prime is
less than 1E-30 (roughly 2^{-100}).
This approach is compliant to `FIPS PUB 186-4`__.
:Keywords:
exact_bits : integer
The desired size in bits of the probable prime.
It must be at least 160.
randfunc : callable
An RNG function where candidate primes are taken from.
prime_filter : callable
A function that takes an Integer as parameter and returns
True if the number can be passed to further primality tests,
False if it should be immediately discarded.
:Return:
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
generate_probable_prime
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Primality.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Primality.py
|
MIT
|
def generate_probable_safe_prime(**kwargs):
"""Generate a random, probable safe prime.
Note this operation is much slower than generating a simple prime.
:Keywords:
exact_bits : integer
The desired size in bits of the probable safe prime.
randfunc : callable
An RNG function where candidate primes are taken from.
:Return:
A probable safe prime in the range
2^exact_bits > p > 2^(exact_bits-1).
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
if kwargs:
print "Unknown parameters:", kwargs.keys()
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc)
candidate = q * 2 + 1
if candidate.size_in_bits() != exact_bits:
continue
result = test_probable_prime(candidate, randfunc=randfunc)
return candidate
|
Generate a random, probable safe prime.
Note this operation is much slower than generating a simple prime.
:Keywords:
exact_bits : integer
The desired size in bits of the probable safe prime.
randfunc : callable
An RNG function where candidate primes are taken from.
:Return:
A probable safe prime in the range
2^exact_bits > p > 2^(exact_bits-1).
|
generate_probable_safe_prime
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/Primality.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/Primality.py
|
MIT
|
def __init__(self, value):
"""Initialize the integer to the given value."""
self._mpz_p = new_mpz()
self._initialized = False
if isinstance(value, float):
raise ValueError("A floating point type is not a natural number")
self._initialized = True
if isinstance(value, (int, long)):
_gmp.mpz_init(self._mpz_p)
result = _gmp.gmp_sscanf(tobytes(str(value)), b("%Zd"), self._mpz_p)
if result != 1:
raise ValueError("Error converting '%d'" % value)
else:
_gmp.mpz_init_set(self._mpz_p, value._mpz_p)
|
Initialize the integer to the given value.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def to_bytes(self, block_size=0):
"""Convert the number into a byte string.
This method encodes the number in network order and prepends
as many zero bytes as required. It only works for non-negative
values.
:Parameters:
block_size : integer
The exact size the output byte string must have.
If zero, the string has the minimal length.
:Returns:
A byte string.
:Raise ValueError:
If the value is negative or if ``block_size`` is
provided and the length of the byte string would exceed it.
"""
if self < 0:
raise ValueError("Conversion only valid for non-negative numbers")
buf_len = (_gmp.mpz_sizeinbase(self._mpz_p, 2) + 7) // 8
if buf_len > block_size > 0:
raise ValueError("Number is too big to convert to byte string"
"of prescribed length")
buf = create_string_buffer(buf_len)
_gmp.mpz_export(
buf,
null_pointer, # Ignore countp
1, # Big endian
c_size_t(1), # Each word is 1 byte long
0, # Endianess within a word - not relevant
c_size_t(0), # No nails
self._mpz_p)
return bchr(0) * max(0, block_size - buf_len) + get_raw_buffer(buf)
|
Convert the number into a byte string.
This method encodes the number in network order and prepends
as many zero bytes as required. It only works for non-negative
values.
:Parameters:
block_size : integer
The exact size the output byte string must have.
If zero, the string has the minimal length.
:Returns:
A byte string.
:Raise ValueError:
If the value is negative or if ``block_size`` is
provided and the length of the byte string would exceed it.
|
to_bytes
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def from_bytes(byte_string):
"""Convert a byte string into a number.
:Parameters:
byte_string : byte string
The input number, encoded in network order.
It can only be non-negative.
:Return:
The ``Integer`` object carrying the same value as the input.
"""
result = Integer(0)
_gmp.mpz_import(
result._mpz_p,
c_size_t(len(byte_string)), # Amount of words to read
1, # Big endian
c_size_t(1), # Each word is 1 byte long
0, # Endianess within a word - not relevant
c_size_t(0), # No nails
byte_string)
return result
|
Convert a byte string into a number.
:Parameters:
byte_string : byte string
The input number, encoded in network order.
It can only be non-negative.
:Return:
The ``Integer`` object carrying the same value as the input.
|
from_bytes
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def sqrt(self):
"""Return the largest Integer that does not
exceed the square root"""
if self < 0:
raise ValueError("Square root of negative value")
result = Integer(0)
_gmp.mpz_sqrt(result._mpz_p,
self._mpz_p)
return result
|
Return the largest Integer that does not
exceed the square root
|
sqrt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def get_bit(self, n):
"""Return True if the n-th bit is set to 1.
Bit 0 is the least significant."""
if not 0 <= n < 65536:
raise ValueError("Incorrect bit position")
return bool(_gmp.mpz_tstbit(self._mpz_p,
c_ulong(int(n))))
|
Return True if the n-th bit is set to 1.
Bit 0 is the least significant.
|
get_bit
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def size_in_bits(self):
"""Return the minimum number of bits that can encode the number."""
if self < 0:
raise ValueError("Conversion only valid for non-negative numbers")
return _gmp.mpz_sizeinbase(self._mpz_p, 2)
|
Return the minimum number of bits that can encode the number.
|
size_in_bits
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def fail_if_divisible_by(self, small_prime):
"""Raise an exception if the small prime is a divisor."""
if isinstance(small_prime, (int, long)):
if 0 < small_prime < 65536:
if _gmp.mpz_divisible_ui_p(self._mpz_p,
c_ulong(small_prime)):
raise ValueError("The value is composite")
return
small_prime = Integer(small_prime)
if _gmp.mpz_divisible_p(self._mpz_p,
small_prime._mpz_p):
raise ValueError("The value is composite")
|
Raise an exception if the small prime is a divisor.
|
fail_if_divisible_by
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def multiply_accumulate(self, a, b):
"""Increment the number by the product of a and b."""
if not isinstance(a, Integer):
a = Integer(a)
if isinstance(b, (int, long)):
if 0 < b < 65536:
_gmp.mpz_addmul_ui(self._mpz_p,
a._mpz_p,
c_ulong(b))
return self
if -65535 < b < 0:
_gmp.mpz_submul_ui(self._mpz_p,
a._mpz_p,
c_ulong(-b))
return self
b = Integer(b)
_gmp.mpz_addmul(self._mpz_p,
a._mpz_p,
b._mpz_p)
return self
|
Increment the number by the product of a and b.
|
multiply_accumulate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def set(self, source):
"""Set the Integer to have the given value"""
if not isinstance(source, Integer):
source = Integer(source)
_gmp.mpz_set(self._mpz_p,
source._mpz_p)
return self
|
Set the Integer to have the given value
|
set
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def inplace_inverse(self, modulus):
"""Compute the inverse of this number in the ring of
modulo integers.
Raise an exception if no inverse exists.
"""
if not isinstance(modulus, Integer):
modulus = Integer(modulus)
comp = _gmp.mpz_cmp(modulus._mpz_p,
self._zero_mpz_p)
if comp == 0:
raise ZeroDivisionError("Modulus cannot be zero")
if comp < 0:
raise ValueError("Modulus must be positive")
result = _gmp.mpz_invert(self._mpz_p,
self._mpz_p,
modulus._mpz_p)
if not result:
raise ValueError("No inverse value can be computed")
return self
|
Compute the inverse of this number in the ring of
modulo integers.
Raise an exception if no inverse exists.
|
inplace_inverse
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def gcd(self, term):
"""Compute the greatest common denominator between this
number and another term."""
result = Integer(0)
if isinstance(term, (int, long)):
if 0 < term < 65535:
_gmp.mpz_gcd_ui(result._mpz_p,
self._mpz_p,
c_ulong(term))
return result
term = Integer(term)
_gmp.mpz_gcd(result._mpz_p, self._mpz_p, term._mpz_p)
return result
|
Compute the greatest common denominator between this
number and another term.
|
gcd
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def lcm(self, term):
"""Compute the least common multiplier between this
number and another term."""
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_lcm(result._mpz_p, self._mpz_p, term._mpz_p)
return result
|
Compute the least common multiplier between this
number and another term.
|
lcm
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Math/_Numbers_gmp.py
|
MIT
|
def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
"""Derive one key from a password (or passphrase).
This function performs key derivation according an old version of
the PKCS#5 standard (v1.5).
This algorithm is called ``PBKDF1``. Even though it is still described
in the latest version of the PKCS#5 standard (version 2, or RFC2898),
newer applications should use the more secure and versatile `PBKDF2` instead.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : byte string
An 8 byte string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation.
dkLen : integer
The length of the desired key. Default is 16 bytes, suitable for instance for `Cryptodome.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
hashAlgo : module
The hash algorithm to use, as a module or an object from the `Cryptodome.Hash` package.
The digest length must be no shorter than ``dkLen``.
The default algorithm is `SHA1`.
:Return: A byte string of length `dkLen` that can be used as key.
"""
if not hashAlgo:
hashAlgo = SHA1
password = tobytes(password)
pHash = hashAlgo.new(password+salt)
digest = pHash.digest_size
if dkLen>digest:
raise TypeError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
if len(salt) != 8:
raise ValueError("Salt is not 8 bytes long (%d bytes instead)." % len(salt))
for i in xrange(count-1):
pHash = pHash.new(pHash.digest())
return pHash.digest()[:dkLen]
|
Derive one key from a password (or passphrase).
This function performs key derivation according an old version of
the PKCS#5 standard (v1.5).
This algorithm is called ``PBKDF1``. Even though it is still described
in the latest version of the PKCS#5 standard (version 2, or RFC2898),
newer applications should use the more secure and versatile `PBKDF2` instead.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : byte string
An 8 byte string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation.
dkLen : integer
The length of the desired key. Default is 16 bytes, suitable for instance for `Cryptodome.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
hashAlgo : module
The hash algorithm to use, as a module or an object from the `Cryptodome.Hash` package.
The digest length must be no shorter than ``dkLen``.
The default algorithm is `SHA1`.
:Return: A byte string of length `dkLen` that can be used as key.
|
PBKDF1
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def PBKDF2(password, salt, dkLen=16, count=1000, prf=None):
"""Derive one or more keys from a password (or passphrase).
This function performs key derivation according to
the PKCS#5 standard (v2.0), by means of the ``PBKDF2`` algorithm.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : string
A string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation. It is recommended to be at least 8 bytes long.
dkLen : integer
The cumulative length of the desired keys. Default is 16 bytes, suitable for instance for `Cryptodome.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
prf : callable
A pseudorandom function. It must be a function that returns a pseudorandom string
from two parameters: a secret and a salt. If not specified, HMAC-SHA1 is used.
:Return: A byte string of length `dkLen` that can be used as key material.
If you wanted multiple keys, just break up this string into segments of the desired length.
"""
password = tobytes(password)
if prf is None:
prf = lambda p,s: HMAC.new(p,s,SHA1).digest()
def link(s):
s[0], s[1] = s[1], prf(password, s[1])
return s[0]
key = b('')
i = 1
while len(key)<dkLen:
s = [ prf(password, salt + struct.pack(">I", i)) ] * 2
key += reduce(strxor, (link(s) for j in range(count)) )
i += 1
return key[:dkLen]
|
Derive one or more keys from a password (or passphrase).
This function performs key derivation according to
the PKCS#5 standard (v2.0), by means of the ``PBKDF2`` algorithm.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : string
A string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation. It is recommended to be at least 8 bytes long.
dkLen : integer
The cumulative length of the desired keys. Default is 16 bytes, suitable for instance for `Cryptodome.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
prf : callable
A pseudorandom function. It must be a function that returns a pseudorandom string
from two parameters: a secret and a salt. If not specified, HMAC-SHA1 is used.
:Return: A byte string of length `dkLen` that can be used as key material.
If you wanted multiple keys, just break up this string into segments of the desired length.
|
PBKDF2
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def __init__(self, key, ciphermod, cipher_params=None):
"""Initialize the S2V PRF.
:Parameters:
key : byte string
A secret that can be used as key for CMACs
based on ciphers from ``ciphermod``.
ciphermod : module
A block cipher module from `Cryptodome.Cipher`.
cipher_params : dictionary
A set of extra parameters to use to create a cipher instance.
"""
self._key = key
self._ciphermod = ciphermod
self._last_string = self._cache = bchr(0)*ciphermod.block_size
self._n_updates = ciphermod.block_size*8-1
if cipher_params is None:
self._cipher_params = {}
else:
self._cipher_params = dict(cipher_params)
|
Initialize the S2V PRF.
:Parameters:
key : byte string
A secret that can be used as key for CMACs
based on ciphers from ``ciphermod``.
ciphermod : module
A block cipher module from `Cryptodome.Cipher`.
cipher_params : dictionary
A set of extra parameters to use to create a cipher instance.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def derive(self):
""""Derive a secret from the vector of components.
:Return: a byte string, as long as the block length of the cipher.
"""
if len(self._last_string)>=16:
final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
else:
padded = (self._last_string + bchr(0x80)+ bchr(0)*15)[:16]
final = strxor(padded, self._double(self._cache))
mac = CMAC.new(self._key,
msg=final,
ciphermod=self._ciphermod,
cipher_params=self._cipher_params)
return mac.digest()
|
"Derive a secret from the vector of components.
:Return: a byte string, as long as the block length of the cipher.
|
derive
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def HKDF(master, key_len, salt, hashmod, num_keys=1, context=None):
"""Derive one or more keys from a master secret using
the HMAC-based KDF defined in RFC5869_.
This KDF is not suitable for deriving keys from a password or for key
stretching. Use `PBKDF2` instead.
HKDF is a key derivation method approved by NIST in `SP 800 56C`__.
:Parameters:
master : byte string
The unguessable value used by the KDF to generate the other keys.
It must be a high-entropy secret, though not necessarily uniform.
It must not be a password.
salt : byte string
A non-secret, reusable value that strengthens the randomness
extraction step.
Ideally, it is as long as the digest size of the chosen hash.
If empty, a string of zeroes in used.
key_len : integer
The length in bytes of every derived key.
hashmod : module
A cryptographic hash algorithm from `Cryptodome.Hash`.
`Cryptodome.Hash.SHA512` is a good choice.
num_keys : integer
The number of keys to derive. Every key is ``key_len`` bytes long.
The maximum cumulative length of all keys is
255 times the digest size.
context : byte string
Optional identifier describing what the keys are used for.
:Return: A byte string or a tuple of byte strings.
.. _RFC5869: http://tools.ietf.org/html/rfc5869
.. __: http://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf
"""
output_len = key_len * num_keys
if output_len > (255 * hashmod.digest_size):
raise ValueError("Too much secret data to derive")
if not salt:
salt = bchr(0) * hashmod.digest_size
if context is None:
context = b("")
# Step 1: extract
hmac = HMAC.new(salt, master, digestmod=hashmod)
prk = hmac.digest()
# Step 2: expand
t = [b("")]
n = 1
tlen = 0
while tlen < output_len:
hmac = HMAC.new(prk, t[-1] + context + bchr(n), digestmod=hashmod)
t.append(hmac.digest())
tlen += hashmod.digest_size
n += 1
derived_output = b("").join(t)
if num_keys == 1:
return derived_output[:key_len]
kol = [derived_output[idx:idx + key_len]
for idx in xrange(0, output_len, key_len)]
return list(kol[:num_keys])
|
Derive one or more keys from a master secret using
the HMAC-based KDF defined in RFC5869_.
This KDF is not suitable for deriving keys from a password or for key
stretching. Use `PBKDF2` instead.
HKDF is a key derivation method approved by NIST in `SP 800 56C`__.
:Parameters:
master : byte string
The unguessable value used by the KDF to generate the other keys.
It must be a high-entropy secret, though not necessarily uniform.
It must not be a password.
salt : byte string
A non-secret, reusable value that strengthens the randomness
extraction step.
Ideally, it is as long as the digest size of the chosen hash.
If empty, a string of zeroes in used.
key_len : integer
The length in bytes of every derived key.
hashmod : module
A cryptographic hash algorithm from `Cryptodome.Hash`.
`Cryptodome.Hash.SHA512` is a good choice.
num_keys : integer
The number of keys to derive. Every key is ``key_len`` bytes long.
The maximum cumulative length of all keys is
255 times the digest size.
context : byte string
Optional identifier describing what the keys are used for.
:Return: A byte string or a tuple of byte strings.
.. _RFC5869: http://tools.ietf.org/html/rfc5869
.. __: http://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf
|
HKDF
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def _scryptROMix(blocks, n):
"""Sequential memory-hard function for scrypt."""
x = [blocks[i:i + 64] for i in xrange(0, len(blocks), 64)]
len_x = len(x)
v = [None]*n
load_le_uint32 = _raw_salsa20_lib.load_le_uint32
for i in xrange(n):
v[i] = x
x = _scryptBlockMix(x, len_x)
for i in xrange(n):
j = load_le_uint32(x[-1]) & (n - 1)
t = [strxor(x[idx], v[j][idx]) for idx in xrange(len_x)]
x = _scryptBlockMix(t, len_x)
return b("").join([get_raw_buffer(y) for y in x])
|
Sequential memory-hard function for scrypt.
|
_scryptROMix
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def scrypt(password, salt, key_len, N, r, p, num_keys=1):
"""Derive one or more keys from a passphrase.
This function performs key derivation according to
the `scrypt`_ algorithm, introduced in Percival's paper
`"Stronger key derivation via sequential memory-hard functions"`__.
This implementation is based on the `RFC draft`__.
:Parameters:
password : string
The secret pass phrase to generate the keys from.
salt : string
A string to use for better protection from dictionary attacks.
This value does not need to be kept secret,
but it should be randomly chosen for each derivation.
It is recommended to be at least 8 bytes long.
key_len : integer
The length in bytes of every derived key.
N : integer
CPU/Memory cost parameter. It must be a power of 2 and less
than ``2**32``.
r : integer
Block size parameter.
p : integer
Parallelization parameter.
It must be no greater than ``(2**32-1)/(4r)``.
num_keys : integer
The number of keys to derive. Every key is ``key_len`` bytes long.
By default, only 1 key is generated.
The maximum cumulative length of all keys is ``(2**32-1)*32``
(that is, 128TB).
A good choice of parameters *(N, r , p)* was suggested
by Colin Percival in his `presentation in 2009`__:
- *(16384, 8, 1)* for interactive logins (<=100ms)
- *(1048576, 8, 1)* for file encryption (<=5s)
:Return: A byte string or a tuple of byte strings.
.. _scrypt: http://www.tarsnap.com/scrypt.html
.. __: http://www.tarsnap.com/scrypt/scrypt.pdf
.. __: http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-03
.. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf
"""
if 2 ** (bit_size(N) - 1) != N:
raise ValueError("N must be a power of 2")
if N >= 2 ** 32:
raise ValueError("N is too big")
if p > ((2 ** 32 - 1) * 32) // (128 * r):
raise ValueError("p or r are too big")
prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest()
blocks = PBKDF2(password, salt, p * 128 * r, 1, prf=prf_hmac_sha256)
blocks = b("").join([_scryptROMix(blocks[x:x + 128 * r], N)
for x in xrange(0, len(blocks), 128 * r)])
dk = PBKDF2(password, blocks, key_len * num_keys, 1,
prf=prf_hmac_sha256)
if num_keys == 1:
return dk
kol = [dk[idx:idx + key_len]
for idx in xrange(0, key_len * num_keys, key_len)]
return kol
|
Derive one or more keys from a passphrase.
This function performs key derivation according to
the `scrypt`_ algorithm, introduced in Percival's paper
`"Stronger key derivation via sequential memory-hard functions"`__.
This implementation is based on the `RFC draft`__.
:Parameters:
password : string
The secret pass phrase to generate the keys from.
salt : string
A string to use for better protection from dictionary attacks.
This value does not need to be kept secret,
but it should be randomly chosen for each derivation.
It is recommended to be at least 8 bytes long.
key_len : integer
The length in bytes of every derived key.
N : integer
CPU/Memory cost parameter. It must be a power of 2 and less
than ``2**32``.
r : integer
Block size parameter.
p : integer
Parallelization parameter.
It must be no greater than ``(2**32-1)/(4r)``.
num_keys : integer
The number of keys to derive. Every key is ``key_len`` bytes long.
By default, only 1 key is generated.
The maximum cumulative length of all keys is ``(2**32-1)*32``
(that is, 128TB).
A good choice of parameters *(N, r , p)* was suggested
by Colin Percival in his `presentation in 2009`__:
- *(16384, 8, 1)* for interactive logins (<=100ms)
- *(1048576, 8, 1)* for file encryption (<=5s)
:Return: A byte string or a tuple of byte strings.
.. _scrypt: http://www.tarsnap.com/scrypt.html
.. __: http://www.tarsnap.com/scrypt/scrypt.pdf
.. __: http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-03
.. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf
|
scrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/KDF.py
|
MIT
|
def _div_gf2(a, b):
"""
Compute division of polynomials over GF(2).
Given a and b, it finds two polynomials q and r such that:
a = b*q + r with deg(r)<deg(b)
"""
if (a < b):
return 0, a
deg = number.size
q = 0
r = a
d = deg(b)
while deg(r) >= d:
s = 1 << (deg(r) - d)
q ^= s
r ^= _mult_gf2(b, s)
return (q, r)
|
Compute division of polynomials over GF(2).
Given a and b, it finds two polynomials q and r such that:
a = b*q + r with deg(r)<deg(b)
|
_div_gf2
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
MIT
|
def __init__(self, encoded_value):
"""Initialize the element to a certain value.
The value passed as parameter is internally encoded as
a 128-bit integer, where each bit represents a polynomial
coefficient. The LSB is the constant coefficient.
"""
if isinstance(encoded_value, (int, long)):
self._value = encoded_value
elif len(encoded_value) == 16:
self._value = bytes_to_long(encoded_value)
else:
raise ValueError("The encoded value must be an integer or a 16 byte string")
|
Initialize the element to a certain value.
The value passed as parameter is internally encoded as
a 128-bit integer, where each bit represents a polynomial
coefficient. The LSB is the constant coefficient.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
MIT
|
def inverse(self):
"""Return the inverse of this element in GF(2^128)."""
# We use the Extended GCD algorithm
# http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor
r0, r1 = self._value, self.irr_poly
s0, s1 = 1, 0
while r1 > 0:
q = _div_gf2(r0, r1)[0]
r0, r1 = r1, r0 ^ _mult_gf2(q, r1)
s0, s1 = s1, s0 ^ _mult_gf2(q, s1)
return _Element(s0)
|
Return the inverse of this element in GF(2^128).
|
inverse
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
MIT
|
def split(k, n, secret):
"""Split a secret into *n* shares.
The secret can be reconstructed later when *k* shares
out of the original *n* are recombined. Each share
must be kept confidential to the person it was
assigned to.
Each share is associated to an index (starting from 1),
which must be presented when the secret is recombined.
:Parameters:
k : integer
The number of shares that must be present in order to reconstruct
the secret.
n : integer
The total number of shares to create (>*k*).
secret : byte string
The 16 byte string (e.g. the AES128 key) to split.
:Return:
*n* tuples, each containing the unique index (an integer) and
the share (a byte string, 16 bytes long) meant for a
participant.
"""
#
# We create a polynomial with random coefficients in GF(2^128):
#
# p(x) = \sum_{i=0}^{k-1} c_i * x^i
#
# c_0 is the encoded secret
#
coeffs = [_Element(rng(16)) for i in xrange(k - 1)]
coeffs.insert(0, _Element(secret))
# Each share is y_i = p(x_i) where x_i is the public index
# associated to each of the n users.
def make_share(user, coeffs):
share, x, idx = [_Element(p) for p in (0, 1, user)]
for coeff in coeffs:
share += coeff * x
x *= idx
return share.encode()
return [(i, make_share(i, coeffs)) for i in xrange(1, n + 1)]
|
Split a secret into *n* shares.
The secret can be reconstructed later when *k* shares
out of the original *n* are recombined. Each share
must be kept confidential to the person it was
assigned to.
Each share is associated to an index (starting from 1),
which must be presented when the secret is recombined.
:Parameters:
k : integer
The number of shares that must be present in order to reconstruct
the secret.
n : integer
The total number of shares to create (>*k*).
secret : byte string
The 16 byte string (e.g. the AES128 key) to split.
:Return:
*n* tuples, each containing the unique index (an integer) and
the share (a byte string, 16 bytes long) meant for a
participant.
|
split
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
MIT
|
def combine(shares):
"""Recombine a secret, if enough shares are presented.
:Parameters:
shares : tuples
At least *k* tuples, each containin the index (an integer) and
the share (a byte string, 16 bytes long) that were assigned to
a participant.
:Return:
The original secret, as a byte string (16 bytes long).
"""
#
# Given k points (x,y), the interpolation polynomial of degree k-1 is:
#
# L(x) = \sum_{j=0}^{k-1} y_i * l_j(x)
#
# where:
#
# l_j(x) = \prod_{ \overset{0 \le m \le k-1}{m \ne j} }
# \frac{x - x_m}{x_j - x_m}
#
# However, in this case we are purely intersted in the constant
# coefficient of L(x).
#
shares = [[_Element(y) for y in x] for x in shares]
result = _Element(0)
k = len(shares)
for j in xrange(k):
x_j, y_j = shares[j]
coeff_0_l = _Element(0)
while not int(coeff_0_l):
coeff_0_l = _Element(rng(16))
inv = coeff_0_l.inverse()
for m in xrange(k):
x_m = shares[m][0]
if m != j:
t = x_m * (x_j + x_m).inverse()
coeff_0_l *= t
result += y_j * coeff_0_l * inv
return result.encode()
|
Recombine a secret, if enough shares are presented.
:Parameters:
shares : tuples
At least *k* tuples, each containin the index (an integer) and
the share (a byte string, 16 bytes long) that were assigned to
a participant.
:Return:
The original secret, as a byte string (16 bytes long).
|
combine
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Protocol/SecretSharing.py
|
MIT
|
def exportKey(self, format='PEM', pkcs8=None, passphrase=None,
protection=None, randfunc=None):
"""Export this DSA key.
:Parameters:
format : string
The format to use for wrapping the key:
- *'DER'*. Binary encoding.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/
`RFC1423`_ (default).
- *'OpenSSH'*. Textual encoding, one line of text, see `RFC4253`_.
Only suitable for public keys, not private keys.
passphrase : string
For private keys only. The pass phrase to use for deriving
the encryption key.
pkcs8 : boolean
For private keys only. If ``True`` (default), the key is arranged
according to `PKCS#8`_ and if `False`, according to the custom
OpenSSL/OpenSSH encoding.
protection : string
The encryption scheme to use for protecting the private key.
It is only meaningful when a pass phrase is present too.
If ``pkcs8`` takes value ``True``, ``protection`` is the PKCS#8
algorithm to use for deriving the secret and encrypting
the private DSA key.
For a complete list of algorithms, see `Cryptodome.IO.PKCS8`.
The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*.
If ``pkcs8`` is ``False``, the obsolete PEM encryption scheme is
used. It is based on MD5 for key derivation, and Triple DES for
encryption. Parameter ``protection`` is ignored.
The combination ``format='DER'`` and ``pkcs8=False`` is not allowed
if a passphrase is present.
randfunc : callable
A function that returns random bytes.
By default it is `Cryptodome.Random.get_random_bytes`.
:Return: A byte string with the encoded public or private half
of the key.
:Raise ValueError:
When the format is unknown or when you try to encrypt a private
key with *DER* format and OpenSSL/OpenSSH.
:attention:
If you don't provide a pass phrase, the private key will be
exported in the clear!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
"""
if passphrase is not None:
passphrase = tobytes(passphrase)
if randfunc is None:
randfunc = Random.get_random_bytes
if format == 'OpenSSH':
tup1 = [self._key[x].to_bytes() for x in 'p', 'q', 'g', 'y']
def func(x):
if (bord(x[0]) & 0x80):
return bchr(0) + x
else:
return x
tup2 = map(func, tup1)
keyparts = [b('ssh-dss')] + tup2
keystring = b('').join(
[struct.pack(">I", len(kp)) + kp for kp in keyparts]
)
return b('ssh-dss ') + binascii.b2a_base64(keystring)[:-1]
# DER format is always used, even in case of PEM, which simply
# encodes it into BASE64.
params = DerSequence([self.p, self.q, self.g])
if self.has_private():
if pkcs8 is None:
pkcs8 = True
if pkcs8:
if not protection:
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
private_key = DerInteger(self.x).encode()
binary_key = PKCS8.wrap(
private_key, oid, passphrase,
protection, key_params=params,
randfunc=randfunc
)
if passphrase:
key_type = 'ENCRYPTED PRIVATE'
else:
key_type = 'PRIVATE'
passphrase = None
else:
if format != 'PEM' and passphrase:
raise ValueError("DSA private key cannot be encrypted")
ints = [0, self.p, self.q, self.g, self.y, self.x]
binary_key = DerSequence(ints).encode()
key_type = "DSA PRIVATE"
else:
if pkcs8:
raise ValueError("PKCS#8 is only meaningful for private keys")
binary_key = _create_subject_public_key_info(oid,
DerInteger(self.y), params)
key_type = "DSA PUBLIC"
if format == 'DER':
return binary_key
if format == 'PEM':
pem_str = PEM.encode(
binary_key, key_type + " KEY",
passphrase, randfunc
)
return tobytes(pem_str)
raise ValueError("Unknown key format '%s'. Cannot export the DSA key." % format)
|
Export this DSA key.
:Parameters:
format : string
The format to use for wrapping the key:
- *'DER'*. Binary encoding.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/
`RFC1423`_ (default).
- *'OpenSSH'*. Textual encoding, one line of text, see `RFC4253`_.
Only suitable for public keys, not private keys.
passphrase : string
For private keys only. The pass phrase to use for deriving
the encryption key.
pkcs8 : boolean
For private keys only. If ``True`` (default), the key is arranged
according to `PKCS#8`_ and if `False`, according to the custom
OpenSSL/OpenSSH encoding.
protection : string
The encryption scheme to use for protecting the private key.
It is only meaningful when a pass phrase is present too.
If ``pkcs8`` takes value ``True``, ``protection`` is the PKCS#8
algorithm to use for deriving the secret and encrypting
the private DSA key.
For a complete list of algorithms, see `Cryptodome.IO.PKCS8`.
The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*.
If ``pkcs8`` is ``False``, the obsolete PEM encryption scheme is
used. It is based on MD5 for key derivation, and Triple DES for
encryption. Parameter ``protection`` is ignored.
The combination ``format='DER'`` and ``pkcs8=False`` is not allowed
if a passphrase is present.
randfunc : callable
A function that returns random bytes.
By default it is `Cryptodome.Random.get_random_bytes`.
:Return: A byte string with the encoded public or private half
of the key.
:Raise ValueError:
When the format is unknown or when you try to encrypt a private
key with *DER* format and OpenSSL/OpenSSH.
:attention:
If you don't provide a pass phrase, the private key will be
exported in the clear!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
exportKey
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def _generate_domain(L, randfunc):
"""Generate a new set of DSA domain parameters"""
N = { 1024:160, 2048:224, 3072:256 }.get(L)
if N is None:
raise ValueError("Invalid modulus length (%d)" % L)
outlen = SHA256.digest_size * 8
n = (L + outlen - 1) // outlen - 1 # ceil(L/outlen) -1
b_ = L - 1 - (n * outlen)
# Generate q (A.1.1.2)
q = Integer(4)
upper_bit = 1 << (N - 1)
while test_probable_prime(q, randfunc) != PROBABLY_PRIME:
seed = randfunc(64)
U = Integer.from_bytes(SHA256.new(seed).digest()) & (upper_bit - 1)
q = U | upper_bit | 1
assert(q.size_in_bits() == N)
# Generate p (A.1.1.2)
offset = 1
upper_bit = 1 << (L - 1)
while True:
V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest()
for j in xrange(n + 1) ]
V = [ Integer.from_bytes(v) for v in V ]
W = sum([V[i] * (1 << (i * outlen)) for i in xrange(n)],
(V[n] & (1 << b_ - 1)) * (1 << (n * outlen)))
X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L}
assert(X.size_in_bits() == L)
c = X % (q * 2)
p = X - (c - 1) # 2q divides (p-1)
if p.size_in_bits() == L and \
test_probable_prime(p, randfunc) == PROBABLY_PRIME:
break
offset += n + 1
# Generate g (A.2.3, index=1)
e = (p - 1) // q
for count in itertools.count(1):
U = seed + b("ggen") + bchr(1) + Integer(count).to_bytes()
W = Integer.from_bytes(SHA256.new(U).digest())
g = pow(W, e, p)
if g != 1:
break
return (p, q, g, seed)
|
Generate a new set of DSA domain parameters
|
_generate_domain
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def generate(bits, randfunc=None, domain=None):
"""Generate a new DSA key pair.
The algorithm follows Appendix A.1/A.2 and B.1 of `FIPS 186-4`_,
respectively for domain generation and key pair generation.
:Parameters:
bits : integer
Key length, or size (in bits) of the DSA modulus *p*.
It must be 1024, 2048 or 3072.
randfunc : callable
Random number generation function; it accepts a single integer N
and return a string of random data N bytes long.
If not specified, the default from ``Cryptodome.Random`` is used.
domain : list
The DSA domain parameters *p*, *q* and *g* as a list of 3
integers. Size of *p* and *q* must comply to `FIPS 186-4`_.
If not specified, the parameters are created anew.
:Return: A DSA key object (`DsaKey`).
:Raise ValueError:
When **bits** is too little, too big, or not a multiple of 64.
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if randfunc is None:
randfunc = Random.get_random_bytes
if domain:
p, q, g = map(Integer, domain)
## Perform consistency check on domain parameters
# P and Q must be prime
fmt_error = test_probable_prime(p) == COMPOSITE
fmt_error = test_probable_prime(q) == COMPOSITE
# Verify Lagrange's theorem for sub-group
fmt_error |= ((p - 1) % q) != 0
fmt_error |= g <= 1 or g >= p
fmt_error |= pow(g, q, p) != 1
if fmt_error:
raise ValueError("Invalid DSA domain parameters")
else:
p, q, g, _ = _generate_domain(bits, randfunc)
L = p.size_in_bits()
N = q.size_in_bits()
if L != bits:
raise ValueError("Mismatch between size of modulus (%d)"
" and 'bits' parameter (%d)" % (L, bits))
if (L, N) not in [(1024, 160), (2048, 224),
(2048, 256), (3072, 256)]:
raise ValueError("Lengths of p and q (%d, %d) are not compatible"
"to FIPS 186-3" % (L, N))
if not 1 < g < p:
raise ValueError("Incorrent DSA generator")
# B.1.1
c = Integer.random(exact_bits=N + 64)
x = c % (q - 1) + 1 # 1 <= x <= q-1
y = pow(g, x, p)
key_dict = { 'y':y, 'g':g, 'p':p, 'q':q, 'x':x }
return DsaKey(key_dict)
|
Generate a new DSA key pair.
The algorithm follows Appendix A.1/A.2 and B.1 of `FIPS 186-4`_,
respectively for domain generation and key pair generation.
:Parameters:
bits : integer
Key length, or size (in bits) of the DSA modulus *p*.
It must be 1024, 2048 or 3072.
randfunc : callable
Random number generation function; it accepts a single integer N
and return a string of random data N bytes long.
If not specified, the default from ``Cryptodome.Random`` is used.
domain : list
The DSA domain parameters *p*, *q* and *g* as a list of 3
integers. Size of *p* and *q* must comply to `FIPS 186-4`_.
If not specified, the parameters are created anew.
:Return: A DSA key object (`DsaKey`).
:Raise ValueError:
When **bits** is too little, too big, or not a multiple of 64.
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
generate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def construct(tup, consistency_check=True):
"""Construct a DSA key from a tuple of valid DSA components.
:Parameters:
tup : tuple
A tuple of long integers, with 4 or 5 items
in the following order:
1. Public key (*y*).
2. Sub-group generator (*g*).
3. Modulus, finite field order (*p*).
4. Sub-group order (*q*).
5. Private key (*x*). Optional.
consistency_check : boolean
If *True*, the library will verify that the provided components
fulfil the main DSA properties.
:Raise PublicKey.ValueError:
When the key being imported fails the most basic DSA validity checks.
:Return: A DSA key object (`DsaKey`).
"""
key_dict = dict(zip(('y', 'g', 'p', 'q', 'x'), map(Integer, tup)))
key = DsaKey(key_dict)
fmt_error = False
if consistency_check:
# P and Q must be prime
fmt_error = test_probable_prime(key.p) == COMPOSITE
fmt_error = test_probable_prime(key.q) == COMPOSITE
# Verify Lagrange's theorem for sub-group
fmt_error |= ((key.p - 1) % key.q) != 0
fmt_error |= key.g <= 1 or key.g >= key.p
fmt_error |= pow(key.g, key.q, key.p) != 1
# Public key
fmt_error |= key.y <= 0 or key.y >= key.p
if hasattr(key, 'x'):
fmt_error |= key.x <= 0 or key.x >= key.q
fmt_error |= pow(key.g, key.x, key.p) != key.y
if fmt_error:
raise ValueError("Invalid DSA key components")
return key
|
Construct a DSA key from a tuple of valid DSA components.
:Parameters:
tup : tuple
A tuple of long integers, with 4 or 5 items
in the following order:
1. Public key (*y*).
2. Sub-group generator (*g*).
3. Modulus, finite field order (*p*).
4. Sub-group order (*q*).
5. Private key (*x*). Optional.
consistency_check : boolean
If *True*, the library will verify that the provided components
fulfil the main DSA properties.
:Raise PublicKey.ValueError:
When the key being imported fails the most basic DSA validity checks.
:Return: A DSA key object (`DsaKey`).
|
construct
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def _import_key_der(key_data, passphrase, params):
"""Import a DSA key (public or private half), encoded in DER form."""
decodings = (_import_openssl_private,
_import_subjectPublicKeyInfo,
_import_x509_cert,
_import_pkcs8)
for decoding in decodings:
try:
return decoding(key_data, passphrase, params)
except ValueError:
pass
raise ValueError("DSA key format is not supported")
|
Import a DSA key (public or private half), encoded in DER form.
|
_import_key_der
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def import_key(extern_key, passphrase=None):
"""Import a DSA key (public or private).
:Parameters:
extern_key : (byte) string
The DSA key to import.
An DSA *public* key can be in any of the following formats:
- X.509 certificate (binary or PEM format)
- X.509 ``subjectPublicKeyInfo`` (binary or PEM)
- OpenSSH (one line of text, see `RFC4253`_)
A DSA *private* key can be in any of the following formats:
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
DER SEQUENCE (binary or PEM encoding)
- OpenSSL/OpenSSH (binary or PEM)
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
The private key may be encrypted by means of a certain pass phrase
either at the PEM level or at the PKCS#8 level.
passphrase : string
In case of an encrypted private key, this is the pass phrase
from which the decryption key is derived.
:Return: A DSA key object (`DsaKey`).
:Raise ValueError:
When the given key cannot be parsed (possibly because
the pass phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
.. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt
"""
extern_key = tobytes(extern_key)
if passphrase is not None:
passphrase = tobytes(passphrase)
if extern_key.startswith(b('-----')):
# This is probably a PEM encoded key
(der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
if enc_flag:
passphrase = None
return _import_key_der(der, passphrase, None)
if extern_key.startswith(b('ssh-dss ')):
# This is probably a public OpenSSH key
keystring = binascii.a2b_base64(extern_key.split(b(' '))[1])
keyparts = []
while len(keystring) > 4:
length = struct.unpack(">I", keystring[:4])[0]
keyparts.append(keystring[4:4 + length])
keystring = keystring[4 + length:]
if keyparts[0] == b("ssh-dss"):
tup = [Integer.from_bytes(keyparts[x]) for x in (4, 3, 1, 2)]
return construct(tup)
if bord(extern_key[0]) == 0x30:
# This is probably a DER encoded key
return _import_key_der(extern_key, passphrase, None)
raise ValueError("DSA key format is not supported")
|
Import a DSA key (public or private).
:Parameters:
extern_key : (byte) string
The DSA key to import.
An DSA *public* key can be in any of the following formats:
- X.509 certificate (binary or PEM format)
- X.509 ``subjectPublicKeyInfo`` (binary or PEM)
- OpenSSH (one line of text, see `RFC4253`_)
A DSA *private* key can be in any of the following formats:
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
DER SEQUENCE (binary or PEM encoding)
- OpenSSL/OpenSSH (binary or PEM)
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
The private key may be encrypted by means of a certain pass phrase
either at the PEM level or at the PKCS#8 level.
passphrase : string
In case of an encrypted private key, this is the pass phrase
from which the decryption key is derived.
:Return: A DSA key object (`DsaKey`).
:Raise ValueError:
When the given key cannot be parsed (possibly because
the pass phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
.. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt
|
import_key
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/DSA.py
|
MIT
|
def x(self):
"""The X-coordinate of the ECC point"""
if self.is_point_at_infinity():
raise ValueError("Point at infinity")
return self._x
|
The X-coordinate of the ECC point
|
x
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def y(self):
"""The Y-coordinate of the ECC point"""
if self.is_point_at_infinity():
raise ValueError("Point at infinity")
return self._y
|
The Y-coordinate of the ECC point
|
y
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def __iadd__(self, point):
"""Add a second point to this one"""
if self.is_point_at_infinity():
return self.set(point)
if point.is_point_at_infinity():
return self
if self == point:
return self.double()
if self._x == point._x:
return self.set(self.point_at_infinity())
common = self._common
tmp1 = self._tmp1
x3 = self._x3
y3 = self._y3
# common = (point._y - self._y) * (point._x - self._x).inverse(_curve.p) % _curve.p
common.set(point._y)
common -= self._y
tmp1.set(point._x)
tmp1 -= self._x
tmp1.inplace_inverse(_curve.p)
common *= tmp1
common %= _curve.p
# x3 = (pow(common, 2, _curve.p) - self._x - point._x) % _curve.p
x3.set(common)
x3.inplace_pow(2, _curve.p)
x3 -= self._x
x3 -= point._x
while x3.is_negative():
x3 += _curve.p
# y3 = ((self._x - x3) * common - self._y) % _curve.p
y3.set(self._x)
y3 -= x3
y3 *= common
y3 -= self._y
y3 %= _curve.p
self._x.set(x3)
self._y.set(y3)
return self
|
Add a second point to this one
|
__iadd__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def __add__(self, point):
"""Return a new point, the addition of this one and another"""
result = self.copy()
result += point
return result
|
Return a new point, the addition of this one and another
|
__add__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def __mul__(self, scalar):
"""Return a new point, the scalar product of this one"""
if scalar < 0:
raise ValueError("Scalar multiplication only defined for non-negative integers")
# Trivial results
if scalar == 0 or self.is_point_at_infinity():
return self.point_at_infinity()
elif scalar == 1:
return self.copy()
# Scalar randomization
scalar_blind = Integer.random(exact_bits=64) * _curve.order + scalar
# Montgomery key ladder
r = [self.point_at_infinity().copy(), self.copy()]
bit_size = int(scalar_blind.size_in_bits())
scalar_int = int(scalar_blind)
for i in range(bit_size, -1, -1):
di = scalar_int >> i & 1
r[di ^ 1] += r[di]
r[di].double()
return r[0]
|
Return a new point, the scalar product of this one
|
__mul__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def __init__(self, **kwargs):
"""Create a new ECC key
Do not instantiate this object directly.
Keywords:
curve : string
It must be *"P-256"*, *"prime256v1"* or *"secp256r1"*.
d : integer
Only for a private key. It must be in the range ``[1..order-1]``.
point : EccPoint
Mandatory for a public key. If provided for a private key,
the implementation will NOT check whether it matches ``d``.
"""
kwargs_ = dict(kwargs)
self.curve = kwargs_.pop("curve", None)
self._d = kwargs_.pop("d", None)
self._point = kwargs_.pop("point", None)
if kwargs_:
raise TypeError("Unknown parameters: " + str(kwargs_))
if self.curve not in _curve.names:
raise ValueError("Unsupported curve (%s)", self.curve)
if self._d is None:
if self._point is None:
raise ValueError("Either private or public ECC component must be specified")
else:
self._d = Integer(self._d)
if not 1 <= self._d < _curve.order:
raise ValueError("Invalid ECC private component")
|
Create a new ECC key
Do not instantiate this object directly.
Keywords:
curve : string
It must be *"P-256"*, *"prime256v1"* or *"secp256r1"*.
d : integer
Only for a private key. It must be in the range ``[1..order-1]``.
point : EccPoint
Mandatory for a public key. If provided for a private key,
the implementation will NOT check whether it matches ``d``.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def d(self):
"""An integer (scalar), representating the private component"""
if not self.has_private():
raise ValueError("This is not a private ECC key")
return self._d
|
An integer (scalar), representating the private component
|
d
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def pointQ(self):
"""An `EccPoint`, representating the public component"""
if self._point is None:
self._point = _curve.G * self._d
return self._point
|
An `EccPoint`, representating the public component
|
pointQ
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def export_key(self, **kwargs):
"""Export this ECC key.
:Keywords:
format : string
The format to use for wrapping the key:
- *'DER'*. The key will be encoded in an ASN.1 DER_ structure (binary).
- *'PEM'*. The key will be encoded in a PEM_ envelope (ASCII).
- *'OpenSSH'*. The key will be encoded in the OpenSSH_ format
(ASCII, public keys only).
passphrase : byte string or string
The passphrase to use for protecting the private key.
*If not provided, the private key will remain in clear form!*
use_pkcs8 : boolean
In case of a private key, whether the PKCS#8_ representation
should be (internally) used. By default it will.
Not using PKCS#8 when exporting a private key in
password-protected PEM_ form means that the much weaker and
unflexible `PEM encryption`_ mechanism will be used.
PKCS#8 is therefore always recommended.
protection : string
In case of a private key being exported with password-protection
and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be
present and be a valid algorithm supported by `Cryptodome.IO.PKCS8`.
It is recommended to use ``PBKDF2WithHMAC-SHA1AndAES128-CBC``.
:Note:
In case of a private key being exported with password-protection
and PKCS#8_ (both ``DER`` and ``PEM`` formats), all additional parameters
will be passed to `Cryptodome.IO.PKCS8`.
.. _DER: http://www.ietf.org/rfc/rfc5915.txt
.. _PEM: http://www.ietf.org/rfc/rfc1421.txt
.. _`PEM encryption`: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
.. _OpenSSH: http://www.openssh.com/txt/rfc5656.txt
:Return: A multi-line string (for PEM and OpenSSH) or bytes (for DER) with the encoded key.
"""
args = kwargs.copy()
ext_format = args.pop("format")
if ext_format not in ("PEM", "DER", "OpenSSH"):
raise ValueError("Unknown format '%s'" % ext_format)
if self.has_private():
passphrase = args.pop("passphrase", None)
if isinstance(passphrase, basestring):
passphrase = tobytes(passphrase)
if not passphrase:
raise ValueError("Empty passphrase")
use_pkcs8 = args.pop("use_pkcs8", True)
if ext_format == "PEM":
if use_pkcs8:
if passphrase:
return self._export_private_encrypted_pkcs8_in_clear_pem(passphrase, **args)
else:
return self._export_private_clear_pkcs8_in_clear_pem()
else:
return self._export_private_pem(passphrase, **args)
elif ext_format == "DER":
# DER
if passphrase and not use_pkcs8:
raise ValueError("Private keys can only be encrpyted with DER using PKCS#8")
if use_pkcs8:
return self._export_pkcs8(passphrase=passphrase, **args)
else:
return self._export_private_der()
else:
raise ValueError("Private keys cannot be exported in OpenSSH format")
else: # Public key
if args:
raise ValueError("Unexpected parameters: '%s'" % args)
if ext_format == "PEM":
return self._export_public_pem()
elif ext_format == "DER":
return self._export_subjectPublicKeyInfo()
else:
return self._export_openssh()
|
Export this ECC key.
:Keywords:
format : string
The format to use for wrapping the key:
- *'DER'*. The key will be encoded in an ASN.1 DER_ structure (binary).
- *'PEM'*. The key will be encoded in a PEM_ envelope (ASCII).
- *'OpenSSH'*. The key will be encoded in the OpenSSH_ format
(ASCII, public keys only).
passphrase : byte string or string
The passphrase to use for protecting the private key.
*If not provided, the private key will remain in clear form!*
use_pkcs8 : boolean
In case of a private key, whether the PKCS#8_ representation
should be (internally) used. By default it will.
Not using PKCS#8 when exporting a private key in
password-protected PEM_ form means that the much weaker and
unflexible `PEM encryption`_ mechanism will be used.
PKCS#8 is therefore always recommended.
protection : string
In case of a private key being exported with password-protection
and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be
present and be a valid algorithm supported by `Cryptodome.IO.PKCS8`.
It is recommended to use ``PBKDF2WithHMAC-SHA1AndAES128-CBC``.
:Note:
In case of a private key being exported with password-protection
and PKCS#8_ (both ``DER`` and ``PEM`` formats), all additional parameters
will be passed to `Cryptodome.IO.PKCS8`.
.. _DER: http://www.ietf.org/rfc/rfc5915.txt
.. _PEM: http://www.ietf.org/rfc/rfc1421.txt
.. _`PEM encryption`: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
.. _OpenSSH: http://www.openssh.com/txt/rfc5656.txt
:Return: A multi-line string (for PEM and OpenSSH) or bytes (for DER) with the encoded key.
|
export_key
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def generate(**kwargs):
"""Generate a new private key on the given curve.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
randfunc : callable
Optional. The RNG to read randomness from.
If ``None``, the system source is used.
"""
curve = kwargs.pop("curve")
randfunc = kwargs.pop("randfunc", get_random_bytes)
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
d = Integer.random_range(min_inclusive=1,
max_exclusive=_curve.order,
randfunc=randfunc)
return EccKey(curve=curve, d=d)
|
Generate a new private key on the given curve.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
randfunc : callable
Optional. The RNG to read randomness from.
If ``None``, the system source is used.
|
generate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def construct(**kwargs):
"""Build a new ECC key (private or public) starting
from some base components.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
d : integer
Only for a private key. It must be in the range ``[1..order-1]``.
point_x : integer
Mandatory for a public key. X coordinate (affine) of the ECC point.
point_y : integer
Mandatory for a public key. Y coordinate (affine) of the ECC point.
"""
point_x = kwargs.pop("point_x", None)
point_y = kwargs.pop("point_y", None)
if "point" in kwargs:
raise TypeError("Unknown keyword: point")
if None not in (point_x, point_y):
kwargs["point"] = EccPoint(point_x, point_y)
# Validate that the point is on the P-256 curve
eq1 = pow(Integer(point_y), 2, _curve.p)
x = Integer(point_x)
eq2 = pow(x, 3, _curve.p)
x *= -3
eq2 += x
eq2 += _curve.b
eq2 %= _curve.p
if eq1 != eq2:
raise ValueError("The point is not on the curve")
# Validate that the private key matches the public one
d = kwargs.get("d", None)
if d is not None and "point" in kwargs:
pub_key = _curve.G * d
if pub_key.x != point_x or pub_key.y != point_y:
raise ValueError("Private and public ECC keys do not match")
return EccKey(**kwargs)
|
Build a new ECC key (private or public) starting
from some base components.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
d : integer
Only for a private key. It must be in the range ``[1..order-1]``.
point_x : integer
Mandatory for a public key. X coordinate (affine) of the ECC point.
point_y : integer
Mandatory for a public key. Y coordinate (affine) of the ECC point.
|
construct
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def import_key(encoded, passphrase=None):
"""Import an ECC key (public or private).
:Parameters:
encoded : bytes or a (multi-line) string
The ECC key to import.
An ECC public key can be:
- An X.509 certificate, binary (DER) or ASCII (PEM)
- An X.509 ``subjectPublicKeyInfo``, binary (DER) or ASCII (PEM)
- An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
An ECC private key can be:
- In binary format (DER, see section 3 of `RFC5915`_ or `PKCS#8`_)
- In ASCII format (PEM or OpenSSH)
Private keys can be in the clear or password-protected.
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
:Keywords:
passphrase : byte string
The passphrase to use for decrypting a private key.
Encryption may be applied protected at the PEM level or at the PKCS#8 level.
This parameter is ignored if the key in input is not encrypted.
:Return: An ECC key object (`EccKey`)
:Raise ValueError:
When the given key cannot be parsed (possibly because
the pass phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC5915: http://www.ietf.org/rfc/rfc5915.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
"""
encoded = tobytes(encoded)
if passphrase is not None:
passphrase = tobytes(passphrase)
# PEM
if encoded.startswith(b('-----')):
der_encoded, marker, enc_flag = PEM.decode(tostr(encoded), passphrase)
if enc_flag:
passphrase = None
return _import_der(der_encoded, passphrase)
# OpenSSH
if encoded.startswith(b('ecdsa-sha2-')):
return _import_openssh(encoded)
# DER
if bord(encoded[0]) == 0x30:
return _import_der(encoded, passphrase)
raise ValueError("ECC key format is not supported")
|
Import an ECC key (public or private).
:Parameters:
encoded : bytes or a (multi-line) string
The ECC key to import.
An ECC public key can be:
- An X.509 certificate, binary (DER) or ASCII (PEM)
- An X.509 ``subjectPublicKeyInfo``, binary (DER) or ASCII (PEM)
- An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
An ECC private key can be:
- In binary format (DER, see section 3 of `RFC5915`_ or `PKCS#8`_)
- In ASCII format (PEM or OpenSSH)
Private keys can be in the clear or password-protected.
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
:Keywords:
passphrase : byte string
The passphrase to use for decrypting a private key.
Encryption may be applied protected at the PEM level or at the PKCS#8 level.
This parameter is ignored if the key in input is not encrypted.
:Return: An ECC key object (`EccKey`)
:Raise ValueError:
When the given key cannot be parsed (possibly because
the pass phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _RFC5915: http://www.ietf.org/rfc/rfc5915.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
import_key
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ECC.py
|
MIT
|
def generate(bits, randfunc):
"""Randomly generate a fresh, new ElGamal key.
The key will be safe for use for both encryption and signature
(although it should be used for **only one** purpose).
:Parameters:
bits : int
Key length, or size (in bits) of the modulus *p*.
Recommended value is 2048.
randfunc : callable
Random number generation function; it should accept
a single integer N and return a string of random data
N bytes long.
:attention: You should always use a cryptographically secure random number generator,
such as the one defined in the ``Cryptodome.Random`` module; **don't** just use the
current time and the ``random`` module.
:Return: An ElGamal key object (`ElGamalKey`).
"""
obj=ElGamalKey()
# Generate a safe prime p
# See Algorithm 4.86 in Handbook of Applied Cryptography
obj.p = generate_probable_safe_prime(exact_bits=bits, randfunc=randfunc)
q = (obj.p - 1) >> 1
# Generate generator g
# See Algorithm 4.80 in Handbook of Applied Cryptography
# Note that the order of the group is n=p-1=2q, where q is prime
while 1:
# We must avoid g=2 because of Bleichenbacher's attack described
# in "Generating ElGamal signatures without knowning the secret key",
# 1996
#
obj.g = Integer.random_range(min_inclusive=3,
max_exclusive=obj.p,
randfunc=randfunc)
safe = 1
if pow(obj.g, 2, obj.p)==1:
safe=0
if safe and pow(obj.g, q, obj.p)==1:
safe=0
# Discard g if it divides p-1 because of the attack described
# in Note 11.67 (iii) in HAC
if safe and (obj.p-1) % obj.g == 0:
safe=0
# g^{-1} must not divide p-1 because of Khadir's attack
# described in "Conditions of the generator for forging ElGamal
# signature", 2011
ginv = obj.g.inverse(obj.p)
if safe and (obj.p-1) % ginv == 0:
safe=0
if safe:
break
# Generate private key x
obj.x = Integer.random_range(min_inclusive=2,
max_exclusive=obj.p-1,
randfunc=randfunc)
# Generate public key y
obj.y = pow(obj.g, obj.x, obj.p)
return obj
|
Randomly generate a fresh, new ElGamal key.
The key will be safe for use for both encryption and signature
(although it should be used for **only one** purpose).
:Parameters:
bits : int
Key length, or size (in bits) of the modulus *p*.
Recommended value is 2048.
randfunc : callable
Random number generation function; it should accept
a single integer N and return a string of random data
N bytes long.
:attention: You should always use a cryptographically secure random number generator,
such as the one defined in the ``Cryptodome.Random`` module; **don't** just use the
current time and the ``random`` module.
:Return: An ElGamal key object (`ElGamalKey`).
|
generate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ElGamal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ElGamal.py
|
MIT
|
def construct(tup):
"""Construct an ElGamal key from a tuple of valid ElGamal components.
The modulus *p* must be a prime.
The following conditions must apply:
- 1 < g < p-1
- g^{p-1} = 1 mod p
- 1 < x < p-1
- g^x = y mod p
:Parameters:
tup : tuple
A tuple of long integers, with 3 or 4 items
in the following order:
1. Modulus (*p*).
2. Generator (*g*).
3. Public key (*y*).
4. Private key (*x*). Optional.
:Raise PublicKey.ValueError:
When the key being imported fails the most basic ElGamal validity checks.
:Return: An ElGamal key object (`ElGamalKey`).
"""
obj=ElGamalKey()
if len(tup) not in [3,4]:
raise ValueError('argument for construct() wrong length')
for i in range(len(tup)):
field = obj._keydata[i]
setattr(obj, field, Integer(tup[i]))
fmt_error = test_probable_prime(obj.p) == COMPOSITE
fmt_error |= obj.g<=1 or obj.g>=obj.p
fmt_error |= pow(obj.g, obj.p-1, obj.p)!=1
fmt_error |= obj.y<1 or obj.y>=obj.p
if len(tup)==4:
fmt_error |= obj.x<=1 or obj.x>=obj.p
fmt_error |= pow(obj.g, obj.x, obj.p)!=obj.y
if fmt_error:
raise ValueError("Invalid ElGamal key components")
return obj
|
Construct an ElGamal key from a tuple of valid ElGamal components.
The modulus *p* must be a prime.
The following conditions must apply:
- 1 < g < p-1
- g^{p-1} = 1 mod p
- 1 < x < p-1
- g^x = y mod p
:Parameters:
tup : tuple
A tuple of long integers, with 3 or 4 items
in the following order:
1. Modulus (*p*).
2. Generator (*g*).
3. Public key (*y*).
4. Private key (*x*). Optional.
:Raise PublicKey.ValueError:
When the key being imported fails the most basic ElGamal validity checks.
:Return: An ElGamal key object (`ElGamalKey`).
|
construct
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/ElGamal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/ElGamal.py
|
MIT
|
def __init__(self, **kwargs):
"""Build an RSA key.
:Keywords:
n : integer
The modulus.
e : integer
The public exponent.
d : integer
The private exponent. Only required for private keys.
p : integer
The first factor of the modulus. Only required for private keys.
q : integer
The second factor of the modulus. Only required for private keys.
u : integer
The CRT coefficient (inverse of p modulo q). Only required for
privta keys.
"""
input_set = set(kwargs.keys())
public_set = set(('n', 'e'))
private_set = public_set | set(('p', 'q', 'd', 'u'))
if input_set not in (private_set, public_set):
raise ValueError("Some RSA components are missing")
for component, value in kwargs.items():
setattr(self, "_" + component, value)
|
Build an RSA key.
:Keywords:
n : integer
The modulus.
e : integer
The public exponent.
d : integer
The private exponent. Only required for private keys.
p : integer
The first factor of the modulus. Only required for private keys.
q : integer
The second factor of the modulus. Only required for private keys.
u : integer
The CRT coefficient (inverse of p modulo q). Only required for
privta keys.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def u(self):
"""Chinese remainder component (inverse of *p* modulo *q*)"""
if not self.has_private():
raise AttributeError("No CRT component 'u' available for public keys")
return int(self._u)
|
Chinese remainder component (inverse of *p* modulo *q*)
|
u
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def exportKey(self, format='PEM', passphrase=None, pkcs=1,
protection=None, randfunc=None):
"""Export this RSA key.
:Parameters:
format : string
The format to use for wrapping the key:
- *'DER'*. Binary encoding.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
- *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
Only suitable for public keys (not private keys).
passphrase : string
For private keys only. The pass phrase used for deriving the encryption
key.
pkcs : integer
For *DER* and *PEM* format only.
The PKCS standard to follow for assembling the components of the key.
You have two choices:
- **1** (default): the public key is embedded into
an X.509 ``SubjectPublicKeyInfo`` DER SEQUENCE.
The private key is embedded into a `PKCS#1`_
``RSAPrivateKey`` DER SEQUENCE.
- **8**: the private key is embedded into a `PKCS#8`_
``PrivateKeyInfo`` DER SEQUENCE. This value cannot be used
for public keys.
protection : string
The encryption scheme to use for protecting the private key.
If ``None`` (default), the behavior depends on ``format``:
- For *DER*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
scheme is used. The following operations are performed:
1. A 16 byte Triple DES key is derived from the passphrase
using `Cryptodome.Protocol.KDF.PBKDF2` with 8 bytes salt,
and 1 000 iterations of `Cryptodome.Hash.HMAC`.
2. The private key is encrypted using CBC.
3. The encrypted key is encoded according to PKCS#8.
- For *PEM*, the obsolete PEM encryption scheme is used.
It is based on MD5 for key derivation, and Triple DES for encryption.
Specifying a value for ``protection`` is only meaningful for PKCS#8
(that is, ``pkcs=8``) and only if a pass phrase is present too.
The supported schemes for PKCS#8 are listed in the
`Cryptodome.IO.PKCS8` module (see ``wrap_algo`` parameter).
randfunc : callable
A function that provides random bytes. Only used for PEM encoding.
The default is `Cryptodome.Random.get_random_bytes`.
:Return: A byte string with the encoded public or private half
of the key.
:Raise ValueError:
When the format is unknown or when you try to encrypt a private
key with *DER* format and PKCS#1.
:attention:
If you don't provide a pass phrase, the private key will be
exported in the clear!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
"""
if passphrase is not None:
passphrase = tobytes(passphrase)
if randfunc is None:
randfunc = Random.get_random_bytes
if format == 'OpenSSH':
e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)]
if bord(e_bytes[0]) & 0x80:
e_bytes = bchr(0) + e_bytes
if bord(n_bytes[0]) & 0x80:
n_bytes = bchr(0) + n_bytes
keyparts = [b('ssh-rsa'), e_bytes, n_bytes]
keystring = b('').join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
return b('ssh-rsa ') + binascii.b2a_base64(keystring)[:-1]
# DER format is always used, even in case of PEM, which simply
# encodes it into BASE64.
if self.has_private():
binary_key = DerSequence([0,
self.n,
self.e,
self.d,
self.p,
self.q,
self.d % (self.p-1),
self.d % (self.q-1),
Integer(self.q).inverse(self.p)
]).encode()
if pkcs == 1:
key_type = 'RSA PRIVATE KEY'
if format == 'DER' and passphrase:
raise ValueError("PKCS#1 private key cannot be encrypted")
else: # PKCS#8
if format == 'PEM' and protection is None:
key_type = 'PRIVATE KEY'
binary_key = PKCS8.wrap(binary_key, oid, None)
else:
key_type = 'ENCRYPTED PRIVATE KEY'
if not protection:
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
binary_key = PKCS8.wrap(binary_key, oid,
passphrase, protection)
passphrase = None
else:
key_type = "RSA PUBLIC KEY"
binary_key = _create_subject_public_key_info(oid,
DerSequence([self.n,
self.e])
)
if format == 'DER':
return binary_key
if format == 'PEM':
pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc)
return tobytes(pem_str)
raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
|
Export this RSA key.
:Parameters:
format : string
The format to use for wrapping the key:
- *'DER'*. Binary encoding.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
- *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
Only suitable for public keys (not private keys).
passphrase : string
For private keys only. The pass phrase used for deriving the encryption
key.
pkcs : integer
For *DER* and *PEM* format only.
The PKCS standard to follow for assembling the components of the key.
You have two choices:
- **1** (default): the public key is embedded into
an X.509 ``SubjectPublicKeyInfo`` DER SEQUENCE.
The private key is embedded into a `PKCS#1`_
``RSAPrivateKey`` DER SEQUENCE.
- **8**: the private key is embedded into a `PKCS#8`_
``PrivateKeyInfo`` DER SEQUENCE. This value cannot be used
for public keys.
protection : string
The encryption scheme to use for protecting the private key.
If ``None`` (default), the behavior depends on ``format``:
- For *DER*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
scheme is used. The following operations are performed:
1. A 16 byte Triple DES key is derived from the passphrase
using `Cryptodome.Protocol.KDF.PBKDF2` with 8 bytes salt,
and 1 000 iterations of `Cryptodome.Hash.HMAC`.
2. The private key is encrypted using CBC.
3. The encrypted key is encoded according to PKCS#8.
- For *PEM*, the obsolete PEM encryption scheme is used.
It is based on MD5 for key derivation, and Triple DES for encryption.
Specifying a value for ``protection`` is only meaningful for PKCS#8
(that is, ``pkcs=8``) and only if a pass phrase is present too.
The supported schemes for PKCS#8 are listed in the
`Cryptodome.IO.PKCS8` module (see ``wrap_algo`` parameter).
randfunc : callable
A function that provides random bytes. Only used for PEM encoding.
The default is `Cryptodome.Random.get_random_bytes`.
:Return: A byte string with the encoded public or private half
of the key.
:Raise ValueError:
When the format is unknown or when you try to encrypt a private
key with *DER* format and PKCS#1.
:attention:
If you don't provide a pass phrase, the private key will be
exported in the clear!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
exportKey
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def generate(bits, randfunc=None, e=65537):
"""Create a new RSA key.
The algorithm closely follows NIST `FIPS 186-4`_ in its
sections B.3.1 and B.3.3. The modulus is the product of
two non-strong probable primes.
Each prime passes a suitable number of Miller-Rabin tests
with random bases and a single Lucas test.
:Parameters:
bits : integer
Key length, or size (in bits) of the RSA modulus.
It must be at least 1024.
The FIPS standard only defines 1024, 2048 and 3072.
randfunc : callable
Function that returns random bytes.
The default is `Cryptodome.Random.get_random_bytes`.
e : integer
Public RSA exponent. It must be an odd positive integer.
It is typically a small number with very few ones in its
binary representation.
The FIPS standard requires the public exponent to be
at least 65537 (the default).
:Return: An RSA key object (`RsaKey`).
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if bits < 1024:
raise ValueError("RSA modulus length must be >= 1024")
if e % 2 == 0 or e < 3:
raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
if randfunc is None:
randfunc = Random.get_random_bytes
d = n = Integer(1)
e = Integer(e)
while n.size_in_bits() != bits and d < (1 << (bits // 2)):
# Generate the prime factors of n: p and q.
# By construciton, their product is always
# 2^{bits-1} < p*q < 2^bits.
size_q = bits // 2
size_p = bits - size_q
min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt()
if size_q != size_p:
min_p = (Integer(1) << (2 * size_p - 1)).sqrt()
def filter_p(candidate):
return candidate > min_p and (candidate - 1).gcd(e) == 1
p = generate_probable_prime(exact_bits=size_p,
randfunc=randfunc,
prime_filter=filter_p)
min_distance = Integer(1) << (bits // 2 - 100)
def filter_q(candidate):
return (candidate > min_q and
(candidate - 1).gcd(e) == 1 and
abs(candidate - p) > min_distance)
q = generate_probable_prime(exact_bits=size_q,
randfunc=randfunc,
prime_filter=filter_q)
n = p * q
lcm = (p - 1).lcm(q - 1)
d = e.inverse(lcm)
if p > q:
p, q = q, p
u = p.inverse(q)
return RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
|
Create a new RSA key.
The algorithm closely follows NIST `FIPS 186-4`_ in its
sections B.3.1 and B.3.3. The modulus is the product of
two non-strong probable primes.
Each prime passes a suitable number of Miller-Rabin tests
with random bases and a single Lucas test.
:Parameters:
bits : integer
Key length, or size (in bits) of the RSA modulus.
It must be at least 1024.
The FIPS standard only defines 1024, 2048 and 3072.
randfunc : callable
Function that returns random bytes.
The default is `Cryptodome.Random.get_random_bytes`.
e : integer
Public RSA exponent. It must be an odd positive integer.
It is typically a small number with very few ones in its
binary representation.
The FIPS standard requires the public exponent to be
at least 65537 (the default).
:Return: An RSA key object (`RsaKey`).
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
generate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def construct(rsa_components, consistency_check=True):
"""Construct an RSA key from a tuple of valid RSA components.
The modulus **n** must be the product of two primes.
The public exponent **e** must be odd and larger than 1.
In case of a private key, the following equations must apply:
- e != 1
- p*q = n
- e*d = 1 mod lcm[(p-1)(q-1)]
- p*u = 1 mod q
:Parameters:
rsa_components : tuple
A tuple of long integers, with at least 2 and no
more than 6 items. The items come in the following order:
1. RSA modulus (*n*).
2. Public exponent (*e*).
3. Private exponent (*d*).
Only required if the key is private.
4. First factor of *n* (*p*).
Optional, but factor q must also be present.
5. Second factor of *n* (*q*). Optional.
6. CRT coefficient, *(1/p) mod q* (*u*). Optional.
consistency_check : boolean
If *True*, the library will verify that the provided components
fulfil the main RSA properties.
:Raise ValueError:
When the key being imported fails the most basic RSA validity checks.
:Return: An RSA key object (`RsaKey`).
"""
class InputComps(object):
pass
input_comps = InputComps()
for (comp, value) in zip(('n', 'e', 'd', 'p', 'q', 'u'), rsa_components):
setattr(input_comps, comp, Integer(value))
n = input_comps.n
e = input_comps.e
if not hasattr(input_comps, 'd'):
key = RsaKey(n=n, e=e)
else:
d = input_comps.d
if hasattr(input_comps, 'q'):
p = input_comps.p
q = input_comps.q
else:
# Compute factors p and q from the private exponent d.
# We assume that n has no more than two factors.
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t //= 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = Integer(2)
while not spotted and a < 100:
k = Integer(t)
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = Integer(n).gcd(cand + 1)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
assert ((n % p) == 0)
q = n // p
if hasattr(input_comps, 'u'):
u = input_comps.u
else:
u = p.inverse(q)
# Build key object
key = RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
# Very consistency of the key
fmt_error = False
if consistency_check:
# Modulus and public exponent must be coprime
fmt_error = e <= 1 or e >= n
fmt_error |= Integer(n).gcd(e) != 1
# For RSA, modulus must be odd
fmt_error |= not n & 1
if not fmt_error and key.has_private():
# Modulus and private exponent must be coprime
fmt_error = d <= 1 or d >= n
fmt_error |= Integer(n).gcd(d) != 1
# Modulus must be product of 2 primes
fmt_error |= (p * q != n)
fmt_error |= test_probable_prime(p) == COMPOSITE
fmt_error |= test_probable_prime(q) == COMPOSITE
# See Carmichael theorem
phi = (p - 1) * (q - 1)
lcm = phi // (p - 1).gcd(q - 1)
fmt_error |= (e * d % int(lcm)) != 1
if hasattr(key, 'u'):
# CRT coefficient
fmt_error |= u <= 1 or u >= q
fmt_error |= (p * u % q) != 1
else:
fmt_error = True
if fmt_error:
raise ValueError("Invalid RSA key components")
return key
|
Construct an RSA key from a tuple of valid RSA components.
The modulus **n** must be the product of two primes.
The public exponent **e** must be odd and larger than 1.
In case of a private key, the following equations must apply:
- e != 1
- p*q = n
- e*d = 1 mod lcm[(p-1)(q-1)]
- p*u = 1 mod q
:Parameters:
rsa_components : tuple
A tuple of long integers, with at least 2 and no
more than 6 items. The items come in the following order:
1. RSA modulus (*n*).
2. Public exponent (*e*).
3. Private exponent (*d*).
Only required if the key is private.
4. First factor of *n* (*p*).
Optional, but factor q must also be present.
5. Second factor of *n* (*q*). Optional.
6. CRT coefficient, *(1/p) mod q* (*u*). Optional.
consistency_check : boolean
If *True*, the library will verify that the provided components
fulfil the main RSA properties.
:Raise ValueError:
When the key being imported fails the most basic RSA validity checks.
:Return: An RSA key object (`RsaKey`).
|
construct
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def _import_keyDER(extern_key, passphrase):
"""Import an RSA key (public or private half), encoded in DER form."""
decodings = (_import_pkcs1_private,
_import_pkcs1_public,
_import_subjectPublicKeyInfo,
_import_x509_cert,
_import_pkcs8)
for decoding in decodings:
try:
return decoding(extern_key, passphrase)
except ValueError:
pass
raise ValueError("RSA key format is not supported")
|
Import an RSA key (public or private half), encoded in DER form.
|
_import_keyDER
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
def import_key(extern_key, passphrase=None):
"""Import an RSA key (public or private half), encoded in standard
form.
:Parameter extern_key:
The RSA key to import, encoded as a byte string.
An RSA public key can be in any of the following formats:
- X.509 certificate (binary or PEM format)
- X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
encoding)
- `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
- OpenSSH (textual public key only)
An RSA private key can be in any of the following formats:
- PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
DER SEQUENCE (binary or PEM encoding)
- OpenSSH (textual public key only)
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
The private key may be encrypted by means of a certain pass phrase
either at the PEM level or at the PKCS#8 level.
:Type extern_key: string
:Parameter passphrase:
In case of an encrypted private key, this is the pass phrase from
which the decryption key is derived.
:Type passphrase: string
:Return: An RSA key object (`RsaKey`).
:Raise ValueError/IndexError/TypeError:
When the given key cannot be parsed (possibly because the pass
phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
"""
extern_key = tobytes(extern_key)
if passphrase is not None:
passphrase = tobytes(passphrase)
if extern_key.startswith(b('-----')):
# This is probably a PEM encoded key.
(der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
if enc_flag:
passphrase = None
return _import_keyDER(der, passphrase)
if extern_key.startswith(b('ssh-rsa ')):
# This is probably an OpenSSH key
keystring = binascii.a2b_base64(extern_key.split(b(' '))[1])
keyparts = []
while len(keystring) > 4:
l = struct.unpack(">I", keystring[:4])[0]
keyparts.append(keystring[4:4 + l])
keystring = keystring[4 + l:]
e = Integer.from_bytes(keyparts[1])
n = Integer.from_bytes(keyparts[2])
return construct([n, e])
if bord(extern_key[0]) == 0x30:
# This is probably a DER encoded key
return _import_keyDER(extern_key, passphrase)
raise ValueError("RSA key format is not supported")
|
Import an RSA key (public or private half), encoded in standard
form.
:Parameter extern_key:
The RSA key to import, encoded as a byte string.
An RSA public key can be in any of the following formats:
- X.509 certificate (binary or PEM format)
- X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
encoding)
- `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
- OpenSSH (textual public key only)
An RSA private key can be in any of the following formats:
- PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
DER SEQUENCE (binary or PEM encoding)
- OpenSSH (textual public key only)
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
The private key may be encrypted by means of a certain pass phrase
either at the PEM level or at the PKCS#8 level.
:Type extern_key: string
:Parameter passphrase:
In case of an encrypted private key, this is the pass phrase from
which the decryption key is derived.
:Type passphrase: string
:Return: An RSA key object (`RsaKey`).
:Raise ValueError/IndexError/TypeError:
When the given key cannot be parsed (possibly because the pass
phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
import_key
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/PublicKey/RSA.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.