Python Crypto.Util.number.bytes_to_long() Examples
The following are 30
code examples of Crypto.Util.number.bytes_to_long().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.Util.number
, or try the search function
.
Example #1
Source File: cryptutils.py From edl with MIT License | 6 votes |
def change_key(self, master_key): if master_key >= (1 << 128): raise InvalidInputException('Master key should be 128-bit') self.__master_key = long_to_bytes(master_key, 16) self.__aes_ecb = AES.new(self.__master_key, AES.MODE_ECB) self.__auth_key = bytes_to_long(self.__aes_ecb.encrypt(b'\x00' * 16)) # precompute the table for multiplication in finite field table = [] # for 8-bit for i in range(16): row = [] for j in range(256): row.append(self.gf_2_128_mul(self.__auth_key, j << (8 * i))) table.append(tuple(row)) self.__pre_table = tuple(table) self.prev_init_value = None # reset
Example #2
Source File: test_modexp.py From FODI with GNU General Public License v3.0 | 6 votes |
def monty_pow(base, exp, modulus): max_len = len(long_to_bytes(max(base, exp, modulus))) base_b, exp_b, modulus_b = [ long_to_bytes(x, max_len) for x in (base, exp, modulus) ] out = create_string_buffer(max_len) error = _raw_montgomery.monty_pow( out, base_b, exp_b, modulus_b, c_size_t(max_len), c_ulonglong(32) ) if error == 17: raise ExceptionModulus() if error: raise ValueError("monty_pow failed with error: %d" % error) result = bytes_to_long(get_raw_buffer(out)) return result
Example #3
Source File: asn1.py From earthengine with MIT License | 6 votes |
def decode(self, derEle, noLeftOvers=0): """Decode a complete INTEGER DER element, and re-initializes this object with it. @param derEle A complete INTEGER DER element. It must start with a DER INTEGER tag. @param noLeftOvers Indicate whether it is acceptable to complete the parsing of the DER element and find that not all bytes in derEle have been used. @return Index of the first unused byte in the given DER element. Raises a ValueError exception if the DER element is not a valid non-negative INTEGER. Raises an IndexError exception if the DER element is too short. """ tlvLength = DerObject.decode(self, derEle, noLeftOvers) if self.typeTag!=self.typeTags['INTEGER']: raise ValueError ("Not a DER INTEGER.") if bord(self.payload[0])>127: raise ValueError ("Negative INTEGER.") self.value = bytes_to_long(self.payload) return tlvLength
Example #4
Source File: test_DSA.py From FODI with GNU General Public License v3.0 | 6 votes |
def _check_public_key(self, dsaObj): k = bytes_to_long(a2b_hex(self.k)) m_hash = bytes_to_long(a2b_hex(self.m_hash)) # Check capabilities self.assertEqual(0, dsaObj.has_private()) self.assertEqual(1, dsaObj.can_sign()) self.assertEqual(0, dsaObj.can_encrypt()) # Check that private parameters are all missing self.assertEqual(0, hasattr(dsaObj, 'x')) # Sanity check key data self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1 # Public-only key objects should raise an error when .sign() is called self.assertRaises(TypeError, dsaObj._sign, m_hash, k) # Check __eq__ and __ne__ self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_ self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf
Example #5
Source File: asn1.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def decode(self, derEle, noLeftOvers=0): """Decode a complete INTEGER DER element, and re-initializes this object with it. @param derEle A complete INTEGER DER element. It must start with a DER INTEGER tag. @param noLeftOvers Indicate whether it is acceptable to complete the parsing of the DER element and find that not all bytes in derEle have been used. @return Index of the first unused byte in the given DER element. Raises a ValueError exception if the DER element is not a valid non-negative INTEGER. Raises an IndexError exception if the DER element is too short. """ tlvLength = DerObject.decode(self, derEle, noLeftOvers) if self.typeTag!=self.typeTags['INTEGER']: raise ValueError ("Not a DER INTEGER.") if bord(self.payload[0])>127: raise ValueError ("Negative INTEGER.") self.value = bytes_to_long(self.payload) return tlvLength
Example #6
Source File: asn1.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
def parse(data): things = [] while data: t = ord(data[0]) assert (t & 0xc0) == 0, 'not a universal value: 0x%02x' % t #assert t & 0x20, 'not a constructed value: 0x%02x' % t l = ord(data[1]) assert data != 0x80, "shouldn't be an indefinite length" if l & 0x80: # long form ll = l & 0x7f l = number.bytes_to_long(data[2:2+ll]) s = 2 + ll else: s = 2 body, data = data[s:s+l], data[s+l:] t = t&(~0x20) assert t in (SEQUENCE, INTEGER), 'bad type: 0x%02x' % t if t == SEQUENCE: things.append(parse(body)) elif t == INTEGER: #assert (ord(body[0])&0x80) == 0, "shouldn't have negative number" things.append(number.bytes_to_long(body)) if len(things) == 1: return things[0] return things
Example #7
Source File: _DSA.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=bord(hash1[i])^bord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise RuntimeError('Bad q value generated')
Example #8
Source File: DSA.py From python-for-android with Apache License 2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise error, 'Bad q value generated'
Example #9
Source File: DSA.py From python-for-android with Apache License 2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise error, 'Bad q value generated'
Example #10
Source File: DSA.py From python-for-android with Apache License 2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159) < q < pow(2,160): return S, q raise error('Bad q value generated')
Example #11
Source File: encrypt.py From h4cker with MIT License | 6 votes |
def derive_key(password): start = bytes_to_long(password) #Making sure I am safe from offline bruteforce attack for i in range(NB_ITERATIONS): start = start ** e start %= N #We are never too cautious let's make it harder key = 1 for i in range(NB_ITERATIONS): key = key ** e key %= N key *= start key %= N return sha256(long_to_bytes(key)).digest()
Example #12
Source File: connection.py From pyrdp with GNU General Public License v3.0 | 6 votes |
def writePublicKey(self, publicKey: RSA.RsaKey) -> bytes: modulus = publicKey.n publicExponent = publicKey.e # Modulus must be reversed because bytes_to_long expects it to be in big endian format modulusBytes = long_to_bytes(modulus)[:: -1] stream = BytesIO() stream.write(b"RSA1") Uint32LE.pack(len(modulusBytes) + 8, stream) Uint32LE.pack(2048, stream) Uint32LE.pack(255, stream) Uint32LE.pack(publicExponent, stream) stream.write(modulusBytes) stream.write(b"\x00" * 8) return stream.getvalue()
Example #13
Source File: crypto.py From pyrdp with GNU General Public License v3.0 | 6 votes |
def decrypt(self, ciphertext: bytes) -> bytes: c = bytes_to_long(ciphertext) # compute c**d (mod n) if (hasattr(self.key, 'p') and hasattr(self.key, 'q') and hasattr(self.key, 'u')): m1 = pow(c, self.key.d % (self.key.p - 1), self.key.p) m2 = pow(c, self.key.d % (self.key.q - 1), self.key.q) h = m2 - m1 if (h < 0): h = h + self.key.q h = h * self.key.u % self.key.q plaintext = h * self.key.p + m1 else: plaintext = pow(c, self.key.d, self.key.n) return long_to_bytes(plaintext)
Example #14
Source File: cryptutils.py From edl with MIT License | 6 votes |
def __ghash(self, aad, txt): len_aad = len(aad) len_txt = len(txt) # padding if 0 == len_aad % 16: data = aad else: data = aad + b'\x00' * (16 - len_aad % 16) if 0 == len_txt % 16: data += txt else: data += txt + b'\x00' * (16 - len_txt % 16) tag = 0 assert len(data) % 16 == 0 for i in range(len(data) // 16): tag ^= bytes_to_long(data[i * 16: (i + 1) * 16]) tag = self.__times_auth_key(tag) # print 'X\t', hex(tag) tag ^= ((8 * len_aad) << 64) | (8 * len_txt) tag = self.__times_auth_key(tag) return tag
Example #15
Source File: SecretSharing.py From FODI with GNU General Public License v3.0 | 5 votes |
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 is_native_int(encoded_value): 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")
Example #16
Source File: CMAC.py From FODI with GNU General Public License v3.0 | 5 votes |
def _shift_bytes(bs, xor_lsb=0): num = (bytes_to_long(bs) << 1) ^ xor_lsb return long_to_bytes(num, len(bs))[-len(bs):]
Example #17
Source File: cert.py From POC-EXP with GNU General Public License v3.0 | 5 votes |
def pkcs_os2ip(x): """ Accepts a byte string as input parameter and return the associated long value: Input : x octet string to be converted Output: x corresponding nonnegative integer Reverse function is pkcs_i2osp() """ return number.bytes_to_long(x) # IP2OS function defined in RFC 3447 for octet string to integer conversion
Example #18
Source File: KDF.py From FODI with GNU General Public License v3.0 | 5 votes |
def _double(self, bs): doubled = bytes_to_long(bs)<<1 if bord(bs[0]) & 0x80: doubled ^= 0x87 return long_to_bytes(doubled, len(bs))[-len(bs):]
Example #19
Source File: cert.py From dash-hack with MIT License | 5 votes |
def pkcs_os2ip(x): """ Accepts a byte string as input parameter and return the associated long value: Input : x octet string to be converted Output: x corresponding nonnegative integer Reverse function is pkcs_i2osp() """ return number.bytes_to_long(x) # IP2OS function defined in RFC 3447 for octet string to integer conversion
Example #20
Source File: cert.py From dash-hack with MIT License | 5 votes |
def pkcs_os2ip(x): """ Accepts a byte string as input parameter and return the associated long value: Input : x octet string to be converted Output: x corresponding nonnegative integer Reverse function is pkcs_i2osp() """ return number.bytes_to_long(x) # IP2OS function defined in RFC 3447 for octet string to integer conversion
Example #21
Source File: pkcs1_15.py From FODI with GNU General Public License v3.0 | 5 votes |
def sign(self, msg_hash): """Create the PKCS#1 v1.5 signature of a message. This function is also called ``RSASSA-PKCS1-V1_5-SIGN`` and it is specified in `section 8.2.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#page-36>`_. :parameter msg_hash: This is an object from the :mod:`Crypto.Hash` package. It has been used to digest the message to sign. :type msg_hash: hash object :return: the signature encoded as a *byte string*. :raise ValueError: if the RSA key is not long enough for the given hash algorithm. :raise TypeError: if the RSA key has no private half. """ # See 8.2.1 in RFC3447 modBits = Crypto.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k) # Step 2a (OS2IP) em_int = bytes_to_long(em) # Step 2b (RSASP1) m_int = self._key._decrypt(em_int) # Step 2c (I2OSP) signature = long_to_bytes(m_int, k) return signature
Example #22
Source File: cert.py From dash-hack with MIT License | 5 votes |
def pkcs_os2ip(x): """ Accepts a byte string as input parameter and return the associated long value: Input : x octet string to be converted Output: x corresponding nonnegative integer Reverse function is pkcs_i2osp() """ return number.bytes_to_long(x) # IP2OS function defined in RFC 3447 for octet string to integer conversion
Example #23
Source File: test_DSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_bad_key5(self): (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)] tup = (y, g, p, q, x+1) self.assertRaises(ValueError, self.dsa.construct, tup) tup = (y, g, p, q, q+10) self.assertRaises(ValueError, self.dsa.construct, tup)
Example #24
Source File: connection.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def parsePublicKey(self, data: bytes) -> RSA.RsaKey: stream = BytesIO(data) _magic = stream.read(4) keyLength = Uint32LE.unpack(stream) _bitLength = Uint32LE.unpack(stream) _dataLength = Uint32LE.unpack(stream) publicExponent = Uint32LE.unpack(stream) modulus = stream.read(keyLength - 8) _padding = stream.read(8) # Modulus must be reversed because bytes_to_long expects it to be in big endian format modulus = bytes_to_long(modulus[:: -1]) publicExponent = int(publicExponent) publicKey = RSA.construct((modulus, publicExponent)) return publicKey
Example #25
Source File: crypto.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def encrypt(self, plaintext: bytes) -> bytes: m = bytes_to_long(plaintext) ciphertext = pow(m, self.key.e, self.key.n) return long_to_bytes(ciphertext)
Example #26
Source File: CMAC.py From earthengine with MIT License | 5 votes |
def _shift_bytes(bs, xor_lsb=0): num = (bytes_to_long(bs)<<1) ^ xor_lsb return long_to_bytes(num, len(bs))[-len(bs):]
Example #27
Source File: cryptutils.py From edl with MIT License | 5 votes |
def encrypt(self, init_value, plaintext, auth_data=b''): if init_value >= (1 << 96): raise InvalidInputException('IV should be 96-bit') # a naive checking for IV reuse if init_value == self.prev_init_value: raise InvalidInputException('IV must not be reused!') self.prev_init_value = init_value len_plaintext = len(plaintext) # len_auth_data = len(auth_data) if len_plaintext > 0: counter = Counter.new( nbits=32, prefix=long_to_bytes(init_value, 12), initial_value=2, # notice this allow_wraparound=False) aes_ctr = AES.new(self.__master_key, AES.MODE_CTR, counter=counter) if 0 != len_plaintext % 16: padded_plaintext = plaintext + \ b'\x00' * (16 - len_plaintext % 16) else: padded_plaintext = plaintext ciphertext = aes_ctr.encrypt(padded_plaintext)[:len_plaintext] else: ciphertext = b'' auth_tag = self.__ghash(auth_data, ciphertext) # print 'GHASH\t', hex(auth_tag) auth_tag ^= bytes_to_long(self.__aes_ecb.encrypt( long_to_bytes((init_value << 32) | 1, 16))) # assert len(ciphertext) == len(plaintext) assert auth_tag < (1 << 128) return ciphertext, auth_tag
Example #28
Source File: test_DSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def _test_verification(self, dsaObj): m_hash = bytes_to_long(a2b_hex(self.m_hash)) r = bytes_to_long(a2b_hex(self.r)) s = bytes_to_long(a2b_hex(self.s)) self.failUnless(dsaObj._verify(m_hash, (r, s))) self.failIf(dsaObj._verify(m_hash + 1, (r, s)))
Example #29
Source File: test_DSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_repr(self): (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)] dsaObj = self.dsa.construct((y, g, p, q)) repr(dsaObj)
Example #30
Source File: PemToXml.py From PemToXml with GNU General Public License v2.0 | 5 votes |
def GetLong(nodelist): rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) string = ''.join(rc) return number.bytes_to_long(b64decode(string)) # # CreatePEMPubKey #