Python Crypto.Util.number.long_to_bytes() Examples

The following are 30 code examples of Crypto.Util.number.long_to_bytes(). 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: DSA.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: connection.py    From pyrdp with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: crypto.py    From pyrdp with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: encrypt.py    From h4cker with MIT License 6 votes vote down vote up
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 #5
Source File: cryptutils.py    From edl with MIT License 6 votes vote down vote up
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 #6
Source File: test_modexp.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: PemToXml.py    From PemToXml with GNU General Public License v2.0 6 votes vote down vote up
def pubKeyXML(pemPublicKeyFile):
   with open (pemPublicKeyFile, 'rb') as pkFile:
      pemPublicKey = pkFile.read()
   publicKey = RSA.importKey(pemPublicKey)
   xml  = '<RSAKeyValue>'
   xml += '<Modulus>'
   xml += standard_b64encode(number.long_to_bytes(publicKey.n))
   xml += '</Modulus>'
   xml += '<Exponent>'
   xml += standard_b64encode(number.long_to_bytes(publicKey.e))
   xml += '</Exponent>'
   xml += '</RSAKeyValue>'
   fileName = basename(pemPublicKeyFile)
   with open (fileName+'.xml', 'w') as pkFile:
      pkFile.write(xml)
   return
#
# CreateXMLPrivKey
# 
Example #8
Source File: _mode_gcm.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def _compute_mac(self):
        """Compute MAC without any FSM checks."""

        if self._tag:
            return self._tag

        # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
        self._pad_cache_and_update()
        self._update(long_to_bytes(8 * self._auth_len, 8))
        self._update(long_to_bytes(8 * self._msg_len, 8))
        s_tag = self._signer.digest()

        # Step 6 - Compute T
        self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]

        return self._tag 
Example #9
Source File: ChaCha20_Poly1305.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def _compute_mac(self):
        """Finalize the cipher (if not done already) and return the MAC."""

        if self._mac_tag:
            assert(self._status == _CipherStatus.PROCESSING_DONE)
            return self._mac_tag

        assert(self._status != _CipherStatus.PROCESSING_DONE)

        if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
            self._pad_aad()

        if self._len_ct & 0x0F:
            self._authenticator.update(b'\x00' * (16 - (self._len_ct & 0x0F)))

        self._status = _CipherStatus.PROCESSING_DONE

        self._authenticator.update(long_to_bytes(self._len_aad, 8)[::-1])
        self._authenticator.update(long_to_bytes(self._len_ct, 8)[::-1])
        self._mac_tag = self._authenticator.digest()
        return self._mac_tag 
Example #10
Source File: asn1.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def pack(data):
    ret = ''
    for part in data:
        if type(part) in (type(()), type([])):
            partData = pack(part)
            partType = SEQUENCE|0x20
        elif type(part) in (type(1), type(1L)):
            partData = number.long_to_bytes(part)
            if ord(partData[0])&(0x80):
                partData = '\x00' + partData
            partType = INTEGER
        else:
            raise 'unknown type %s' % type(part)

        ret += chr(partType)
        if len(partData) > 127:
            l = number.long_to_bytes(len(partData))
            ret += chr(len(l)|0x80) + l
        else:
            ret += chr(len(partData))
        ret += partData
    return ret 
Example #11
Source File: _DSA.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 #12
Source File: randpool.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _noise(self):
        # Adds a bit of noise to the random pool, by adding in the
        # current time and CPU usage of this process.
        # The difference from the previous call to _noise() is taken
        # in an effort to estimate the entropy.
        t=time.time()
        delta = (t - self._lastcounter)/self._ticksize*1e6
        self._lastcounter = t
        self._addBytes(long_to_bytes(long(1000*time.time())))
        self._addBytes(long_to_bytes(long(1000*time.clock())))
        self._addBytes(long_to_bytes(long(1000*time.time())))
        self._addBytes(long_to_bytes(long(delta)))

        # Reduce delta to a maximum of 8 bits so we don't add too much
        # entropy as a result of this call.
        delta=delta % 0xff
        return int(delta) 
Example #13
Source File: randpool.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _noise(self):
        # Adds a bit of noise to the random pool, by adding in the
        # current time and CPU usage of this process.
        # The difference from the previous call to _noise() is taken
        # in an effort to estimate the entropy.
        t=time.time()
        delta = (t - self._lastcounter)/self._ticksize*1e6
        self._lastcounter = t
        self._addBytes(long_to_bytes(int(1000*time.time())))
        self._addBytes(long_to_bytes(int(1000*time.clock())))
        self._addBytes(long_to_bytes(int(1000*time.time())))
        self._addBytes(long_to_bytes(int(delta)))

        # Reduce delta to a maximum of 8 bits so we don't add too much
        # entropy as a result of this call.
        delta=delta % 0xff
        return int(delta) 
Example #14
Source File: common.py    From arkc-client with GNU General Public License v2.0 6 votes vote down vote up
def generate_RSA(pridir, pubdir):
    key = RSA.generate(2048)
    with open(pridir, 'wb') as content_file:
        content_file.write(key.exportKey('PEM'))
    print("Private key written to home directory " + pridir)
    with open(pubdir, 'wb') as content_file:
        # Ugly hack to introduce pycrypto v2.7a1
        # Original: .exportKey('OpenSSH')
        eb = long_to_bytes(key.e)
        nb = long_to_bytes(key.n)
        if bord(eb[0]) & 0x80:
            eb = bchr(0x00) + eb
        if bord(nb[0]) & 0x80:
            nb = bchr(0x00) + nb
        keyparts = [b('ssh-rsa'), eb, nb]
        keystring = b('').join(
            [struct.pack(">I", len(kp)) + kp for kp in keyparts])
        content_file.write(b('ssh-rsa ') + binascii.b2a_base64(keystring)[:-1])
    print("Public key written to home directory " + pubdir)
    return sha1(key.exportKey('PEM')).hexdigest() 
Example #15
Source File: DSA.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: _DSA.py    From earthengine with MIT License 6 votes vote down vote up
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 #17
Source File: algorithms.py    From wincrypto with MIT License 6 votes vote down vote up
def export_privatekeyblob(self):
        key = self.key.key
        n = key.n
        e = key.e
        d = key.d
        p = key.p
        q = key.q

        n_bytes = long_to_bytes(n)[::-1]
        key_len = len(n_bytes) * 8
        result = PUBLICKEYSTRUC_s.pack(bType_PRIVATEKEYBLOB, CUR_BLOB_VERSION, CALG_RSA_KEYX)
        result += RSAPUBKEY_s.pack(PRIVATEKEYBLOB_MAGIC, key_len, e)
        result += n_bytes
        result += long_to_bytes(p, key_len / 16)[::-1]
        result += long_to_bytes(q, key_len / 16)[::-1]
        result += long_to_bytes(d % (p - 1), key_len / 16)[::-1]
        result += long_to_bytes(d % (q - 1), key_len / 16)[::-1]
        result += long_to_bytes(inverse(q, p), key_len / 16)[::-1]
        result += long_to_bytes(d, key_len / 8)[::-1]
        return result 
Example #18
Source File: randpool.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _noise(self):
        # Adds a bit of noise to the random pool, by adding in the
        # current time and CPU usage of this process.
        # The difference from the previous call to _noise() is taken
        # in an effort to estimate the entropy.
        t=time.time()
        delta = (t - self._lastcounter)/self._ticksize*1e6
        self._lastcounter = t
        self._addBytes(long_to_bytes(long(1000*time.time())))
        self._addBytes(long_to_bytes(long(1000*time.clock())))
        self._addBytes(long_to_bytes(long(1000*time.time())))
        self._addBytes(long_to_bytes(long(delta)))

        # Reduce delta to a maximum of 8 bits so we don't add too much
        # entropy as a result of this call.
        delta=delta % 0xff
        return int(delta) 
Example #19
Source File: Mozilla.py    From BrainDamage with Apache License 2.0 5 votes vote down vote up
def extractSecretKey(self, globalSalt, masterPassword, entrySalt):

        (globalSalt, masterPassword, entrySalt) = self.is_masterpassword_correct(masterPassword)

        if unhexlify('f8000000000000000000000000000001') not in self.key3:
            return None
        privKeyEntry = self.key3[unhexlify('f8000000000000000000000000000001')]
        saltLen = ord(privKeyEntry[1])
        nameLen = ord(privKeyEntry[2])
        privKeyEntryASN1 = decoder.decode(privKeyEntry[3 + saltLen + nameLen:])
        data = privKeyEntry[3 + saltLen + nameLen:]
        self.printASN1(data, len(data), 0)

        # see https://github.com/philsmd/pswRecovery4Moz/blob/master/pswRecovery4Moz.txt
        entrySalt = privKeyEntryASN1[0][0][1][0].asOctets()
        privKeyData = privKeyEntryASN1[0][1].asOctets()
        privKey = self.decrypt3DES(globalSalt, masterPassword, entrySalt, privKeyData)
        self.printASN1(privKey, len(privKey), 0)

        privKeyASN1 = decoder.decode(privKey)
        prKey = privKeyASN1[0][2].asOctets()
        self.printASN1(prKey, len(prKey), 0)
        prKeyASN1 = decoder.decode(prKey)
        id = prKeyASN1[0][1]
        key = long_to_bytes(prKeyASN1[0][3])

        return key

    # --------------------------------------------

    # Get the path list of the firefox profiles 
Example #20
Source File: key.py    From little-boxes with ISC License 5 votes vote down vote up
def to_magic_key(self) -> str:
        mod = base64.urlsafe_b64encode(
            number.long_to_bytes(self.privkey.n)  # type: ignore
        ).decode("utf-8")
        pubexp = base64.urlsafe_b64encode(
            number.long_to_bytes(self.privkey.e)  # type: ignore
        ).decode("utf-8")
        return f"data:application/magic-public-key,RSA.{mod}.{pubexp}" 
Example #21
Source File: ECC.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def init_p256():
    p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
    b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
    order = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
    Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
    Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5

    p256_modulus = long_to_bytes(p, 32)
    p256_b = long_to_bytes(b, 32)
    p256_order = long_to_bytes(order, 32)

    ec_p256_context = VoidPointer()
    result = _ec_lib.ec_ws_new_context(ec_p256_context.address_of(),
                                       c_uint8_ptr(p256_modulus),
                                       c_uint8_ptr(p256_b),
                                       c_uint8_ptr(p256_order),
                                       c_size_t(len(p256_modulus)),
                                       c_ulonglong(getrandbits(64))
                                       )
    if result:
        raise ImportError("Error %d initializing P-256 context" % result)

    context = SmartPointer(ec_p256_context.get(), _ec_lib.ec_free_context)
    p256 = _Curve(Integer(p),
                  Integer(b),
                  Integer(order),
                  Integer(Gx),
                  Integer(Gy),
                  None,
                  256,
                  "1.2.840.10045.3.1.7",    # ANSI X9.62
                  context,
                  "NIST P-256",
                  "ecdsa-sha2-nistp256")
    global p256_names
    _curves.update(dict.fromkeys(p256_names, p256)) 
Example #22
Source File: _IntegerNative.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def to_bytes(self, block_size=0):
        if self._value < 0:
            raise ValueError("Conversion only valid for non-negative numbers")
        result = long_to_bytes(self._value, block_size)
        if len(result) > block_size > 0:
            raise ValueError("Value too large to encode")
        return result 
Example #23
Source File: ECC.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def __imul__(self, scalar):
        """Multiply this point by a scalar"""

        if scalar < 0:
            raise ValueError("Scalar multiplication is only defined for non-negative integers")
        sb = long_to_bytes(scalar)
        result = _ec_lib.ec_ws_scalar(self._point.get(),
                                      c_uint8_ptr(sb),
                                      c_size_t(len(sb)),
                                      c_ulonglong(getrandbits(64)))
        if result:
            raise ValueError("Error %d during scalar multiplication" % result)
        return self 
Example #24
Source File: algorithms.py    From wincrypto with MIT License 5 votes vote down vote up
def export_publickeyblob(self):
        n = self.key.key.n
        e = self.key.key.e
        n_bytes = long_to_bytes(n)[::-1]
        result = PUBLICKEYSTRUC_s.pack(bType_PUBLICKEYBLOB, CUR_BLOB_VERSION, CALG_RSA_KEYX)
        result += RSAPUBKEY_s.pack(RSAPUBKEY_MAGIC, len(n_bytes) * 8, e)
        result += n_bytes
        return result 
Example #25
Source File: asn1.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def _definite_form(length):
                """Build length octets according to BER/DER
                definite form.
                """
                if length > 127:
                        encoding = long_to_bytes(length)
                        return bchr(len(encoding) + 128) + encoding
                return bchr(length) 
Example #26
Source File: KDF.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
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 #27
Source File: SecretSharing.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def encode(self):
        """Return the field element, encoded as a 16 byte string."""

        return long_to_bytes(self._value, 16) 
Example #28
Source File: CMAC.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
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 #29
Source File: cert.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def pkcs_i2osp(x,xLen):
    """
    Converts a long (the first parameter) to the associated byte string
    representation of length l (second parameter). Basically, the length
    parameters allow the function to perform the associated padding.

    Input : x        nonnegative integer to be converted
            xLen     intended length of the resulting octet string

    Output: x        corresponding nonnegative integer

    Reverse function is pkcs_os2ip().
    """
    z = number.long_to_bytes(x)
    padlen = max(0, xLen-len(z))
    return '\x00'*padlen + z

# for every hash function a tuple is provided, giving access to 
# - hash output length in byte
# - associated hash function that take data to be hashed as parameter
#   XXX I do not provide update() at the moment.
# - DER encoding of the leading bits of digestInfo (the hash value
#   will be concatenated to create the complete digestInfo).
# 
# Notes:
# - MD4 asn.1 value should be verified. Also, as stated in 
#   PKCS#1 v2.1, MD4 should not be used.
# - hashlib is available from http://code.krypto.org/python/hashlib/
# - 'tls' one is the concatenation of both md5 and sha1 hashes used
#   by SSL/TLS when signing/verifying things 
Example #30
Source File: randpool.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def add_event(self, s=''):
        """add_event(s:string)
        Add an event to the random pool.  The current time is stored
        between calls and used to estimate the entropy.  The optional
        's' parameter is a string that will also be XORed into the pool.
        Returns the estimated number of additional bits of entropy gain.
        """
        event = time.time()*1000
        delta = self._noise()
        s = (s + long_to_bytes(event) +
             4*chr(0xaa) + long_to_bytes(delta) )
        self._addBytes(s)
        if event==self._event1 and event==self._event2:
            # If events are coming too closely together, assume there's
            # no effective entropy being added.
            bits=0
        else:
            # Count the number of bits in delta, and assume that's the entropy.
            bits=0
            while delta:
                delta, bits = delta>>1, bits+1
            if bits>8: bits=8

        self._event1, self._event2 = event, self._event1

        self._updateEntropyEstimate(bits)
        return bits

    # Private functions