示例#1
0
def password_derive_bytes(pstring, salt, iterations, keylen):
    lasthash = pstring + salt
    for i in range(iterations - 1):
        lasthash = SHA1.new(lasthash).digest()
    bytes = SHA1.new(lasthash).digest()
    ctrl = 1
    while len(bytes) < keylen:
        bytes += SHA1.new(str(ctrl).encode() + lasthash).digest()
        ctrl += 1
    return bytes[:keylen]
示例#2
0
    def verify(self, msg: bytes, signature: bytes):

        _hash = SHA1.new(msg)
        public_key = RSA.importKey(self.public_key)
        verifier = pss.new(public_key)
        res = verifier.verify(_hash, signature)
        print(f"verify result is --> {res}")
示例#3
0
def _sign_message(token: str, body: str) -> t.Tuple[str, str]:
    key = RSA.generate(1024, e=int("10001", 16))
    signer = PKCS1_v1_5.new(key)
    digest = SHA1.new()
    digest.update(f"X-AuthToken:{token}{body}".encode("utf-8"))
    signature = signer.sign(digest)
    return signature.hex(), f"{key.n:x}"
    def verify_signature(self, signature_algorithm, signature, cert, data):
        """
        Verifies the signature
        """
        sig = SnowflakeOCSPPyasn1.bit_string_to_bytearray(signature)
        if PY2:
            sig = str(sig)
        else:
            sig = sig.decode('latin-1').encode('latin-1')

        pubkey = SnowflakeOCSPPyasn1.bit_string_to_bytearray(
            cert.getComponentByName(
                'tbsCertificate').getComponentByName(
                'subjectPublicKeyInfo').getComponentByName('subjectPublicKey'))
        if PY2:
            pubkey = str(pubkey)
        else:
            pubkey = pubkey.decode('latin-1').encode('latin-1')

        rsakey = RSA.importKey(pubkey)
        signer = PKCS1_v1_5.new(rsakey)

        algorithm = signature_algorithm[0]
        if algorithm in SnowflakeOCSPPyasn1.SIGNATURE_HASH_ALGO_TO_DIGEST_CLASS:
            digest = SnowflakeOCSPPyasn1.SIGNATURE_HASH_ALGO_TO_DIGEST_CLASS[
                algorithm].new()
        else:
            digest = SHA1.new()

        data = der_encoder.encode(data)
        digest.update(data)
        if not signer.verify(digest, sig):
            raise RevocationCheckError(
                msg="Failed to verify the signature",
                errno=ER_INVALID_OCSP_RESPONSE)
示例#5
0
    def parse(self, data: (bytes, bytearray)) -> (bytes, bytearray):
        global REQUEST_PRV_KEY

        self.enc_output = data

        iv = data[:16]

        cipher = AES.new(REQUEST_SECRET, AES.MODE_CBC, iv)
        enc_data = data[16:]  # array + signature
        dec_data = unpad(cipher.decrypt(enc_data), AES.block_size)

        body = dec_data[:
                        -REQUEST_PRV_KEY.size_in_bytes()]  # UNIQUE_MAGIC + DNA
        self.signature = dec_data[-REQUEST_PRV_KEY.size_in_bytes():]

        # verify file magic
        assert body[:4] == REQUEST_MAGIC, "Invalid update request magic"

        # verify signature
        verifier = PKCS1_v1_5.new(REQUEST_PRV_KEY)
        assert verifier.verify(SHA1.new(body),
                               self.signature), "Invalid signature"

        (magic, self.dna, self.sys_fw_ver, self.ver_code,
         self.pcba_rev) = unpack("<4s 16s 3I", body)
        self.serial = hexlify(self.dna)
示例#6
0
def rsa_verify(sign, message, pub_Key):
    pub = RSA.importKey(pub_Key)
    cipher = SHA1.new(message)
    t = Signature_pkcs1_v1_5.new(pub).verify(cipher, base64.b64decode(sign))
    if t:
        return True
    return False
示例#7
0
    def extract_files(self, directory: str = OUTPUT_DIR) -> None:
        global DEBUG

        for single in self.update_files:
            self.stream.seek(single.offset)
            cipher = AES.new(single.key, AES.MODE_CBC, single.iv)
            hasher = SHA1.new()
            bz2 = BZ2Decompressor()
            read = 0
            with open(join(directory, single.name), "wb") as f:
                while read < single.size_pad:
                    # calculate the exact size of the read
                    amt = (single.size_pad -
                           read) if (single.size_pad -
                                     read) < BLOCK_SIZE else BLOCK_SIZE
                    enc_buff = self.stream.read(amt)
                    # decrypt the buffer
                    dec_buff = cipher.decrypt(enc_buff)
                    # remove padding
                    if len(dec_buff) < BLOCK_SIZE:
                        if single.size_nopad < single.size_pad:
                            diff = single.size_pad - single.size_nopad
                            dec_buff = dec_buff[:-diff]
                    # update the hasher
                    hasher.update(dec_buff)
                    # decompress if bz2
                    if single.name.endswith(".bz2"):
                        dec_buff = bz2.decompress(dec_buff)
                    # output to file
                    f.write(dec_buff)
                    read += len(enc_buff)
                assert self.verifier.verify(
                    hasher, single.signature), "Invalid signature"
            # rename the .bz2 files because they're already decompressed
            if single.name.endswith(".bz2"):  # .tar.bz2 files
                if DEBUG:
                    print("> Unpacking %s..." % (single.name))
                orig_path = join(directory, single.name)
                new_path = join(directory, single.name.replace(".bz2", ".tar"))
                if isfile(new_path):
                    remove(new_path)
                rename(orig_path, new_path)
                if DEBUG:
                    print("> Renamed %s to %s" %
                          (basename(orig_path), basename(new_path)))
                with TarFile(new_path) as tar_f:
                    if DEBUG:
                        for member in tar_f.getmembers():
                            print("+ %s @ %s, %s" %
                                  (member.name, hex(member.offset),
                                   convert_size(member.size)))
                    tar_f.extractall(directory)
                remove(new_path)
                if DEBUG:
                    print("- Deleted %s" % (single.name))
            elif single.name.endswith(".img"):  # rk30 images
                if DEBUG:
                    print("> Unpacking %s..." % (single.name))
                RKFW(join(directory, single.name))
示例#8
0
 def sign(self, message):
     if not self.keyObject:
         raise ValueError('key object is not exist')
     h = SHA1.new(message)
     signature_bytes = pkcs1_15.new(self.keyObject).sign(h)
     signature_int = number.bytes_to_long(signature_bytes)
     signature = str(signature_int)
     return signature
示例#9
0
def rsa_verify_string_sha1(publickeystr, msg, sig):
    key = RSA.importKey(publickeystr)
    h = SHA1.new(msg)
    try:
        pkcs1_15.new(key).verify(h, sig)
        return True
    except ValueError:
        # Raises ValueError if the signature is wrong
        return False
示例#10
0
def sha1(inp, hexdigest=False, return_object=False):
    if not strng.is_bin(inp):
        raise ValueError('input must by byte string')
    h = SHA1.new(inp)
    if return_object:
        return h
    if hexdigest:
        return strng.to_bin(h.hexdigest())
    return h.digest()
示例#11
0
 def verify(self, signature, message):
     h = SHA1.new(message)
     try:
         signature_int = long(signature)
         signature_bytes = number.long_to_bytes(signature_int)
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (ValueError, TypeError):
         result = False
     return result
示例#12
0
    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Cryptodome.Hash import SHA1

        self.description = "Unapproved hash (SHA-1) test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
示例#13
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        # For Protected users
        tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)
        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
        key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'), SHA1).digest()[:20]

        return key1, key2, key3
    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Cryptodome.Hash import SHA1

        self.description = "Unapproved hash (SHA-1) test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
示例#15
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(
            SHA1.new(password.encode('utf-16le')).digest(),
            (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(
            MD4.new(password.encode('utf-16le')).digest(),
            (sid + '\0').encode('utf-16le'), SHA1).digest()

        return key1, key2
示例#16
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        # For Protected users
        tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)
        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
        key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'), SHA1).digest()[:20]

        return key1, key2, key3
示例#17
0
    def decrypt(self, key, entropy=None):
        keyHash = SHA1.new(key).digest()
        sessionKey = HMAC.new(keyHash, self['Salt'],
                              ALGORITHMS_DATA[self['HashAlgo']][1])
        if entropy is not None:
            sessionKey.update(entropy)

        sessionKey = sessionKey.digest()

        # Derive the key
        derivedKey = self.deriveKey(sessionKey)

        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(
            derivedKey[:ALGORITHMS_DATA[self['CryptAlgo']][0]],
            mode=ALGORITHMS_DATA[self['CryptAlgo']][2],
            iv=b'\x00' * ALGORITHMS_DATA[self['CryptAlgo']][3])
        cleartext = unpad(cipher.decrypt(self['Data']),
                          ALGORITHMS_DATA[self['CryptAlgo']][1].block_size)

        # Now check the signature

        # ToDo Fix this, it's just ugly, more testing so we can remove one
        toSign = (self.rawData[20:][:len(self.rawData) - 20 -
                                    len(self['Sign']) - 4])

        # Calculate the different HMACKeys
        keyHash2 = keyHash + b"\x00" * ALGORITHMS_DATA[
            self['HashAlgo']][1].block_size
        ipad = bytearray([i ^ 0x36 for i in bytearray(keyHash2)
                          ][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
        opad = bytearray([i ^ 0x5c for i in bytearray(keyHash2)
                          ][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
        a = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad)
        a.update(self['HMac'])

        hmacCalculated1 = ALGORITHMS_DATA[self['HashAlgo']][1].new(opad)
        hmacCalculated1.update(a.digest())

        if entropy is not None:
            hmacCalculated1.update(entropy)

        hmacCalculated1.update(toSign)

        hmacCalculated3 = HMAC.new(keyHash, self['HMac'],
                                   ALGORITHMS_DATA[self['HashAlgo']][1])
        if entropy is not None:
            hmacCalculated3.update(entropy)

        hmacCalculated3.update(toSign)

        if hmacCalculated1.digest() == self['Sign'] or hmacCalculated3.digest(
        ) == self['Sign']:
            return cleartext
        else:
            return None
示例#18
0
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
    def runTest(self):
        key = RSA.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
示例#21
0
    def runTest(self):
        key = RSA.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
示例#22
0
def dsa_sign(x: int, msg: bytes):
    k = random.randint(1, q - 1)  # sig. priv. key
    r = pow(g, k, p) % q  # sig. pub.  key, reduced mod q
    if r == 0:  # start again
        return dsa_sign(x, msg)
    h = int.from_bytes(SHA1.new(msg).digest(), 'big')
    s = (pow(k, -1, q) * (h + x * r)) % q
    if s == 0:  # start again
        return dsa_sign(x, msg)
    # r = (g^k mod p) mod q
    # s = (h+xr)/k    mod q
    return (r, s)
def _verify_signature(signature_algorithm, signature, cert, data):
    rsakey = RSA.importKey(cert.public_key.unwrap().dump())
    signer = PKCS1_v1_5.new(rsakey)
    if signature_algorithm in SIGNATURE_ALGORITHM_TO_DIGEST_CLASS:
        digest = SIGNATURE_ALGORITHM_TO_DIGEST_CLASS[signature_algorithm].new()
    else:
        # the last resort. should not happen.
        digest = SHA1.new()
    digest.update(data.dump())
    if not signer.verify(digest, signature):
        raise OperationalError(msg="Failed to verify the signature",
                               errno=ER_INVALID_OCSP_RESPONSE)
示例#24
0
 def attack1(self):
     print('Eve:   attack 1, g = 1')
     self.outB.put((self.p, 1))  # g_B := 1
     ack = self.inB.get()
     assert ack == 'ACK'
     self.outA.put(ack)
     KA = self.inA.get()
     self.outB.put(1)  # KA_B := 1
     KB = self.inB.get()
     assert KB == 1
     self.outA.put(KB)
     self.key = SHA1.new(bytes([1])).digest()[:BS]  # s = 1
示例#25
0
 def attack2(self):
     print('Eve:   attack 2, g = p')
     self.outB.put((self.p, self.p))  # g_B := p (= 0)
     ack = self.inB.get()
     assert ack == 'ACK'
     self.outA.put(ack)
     KA = self.inA.get()
     self.outB.put(0)  # KA_B := 0
     KB = self.inB.get()
     assert KB == 0
     self.outA.put(KB)
     self.key = SHA1.new(b'').digest()[:BS]  # s = 0
示例#26
0
 def verify(self, signature, message):
     h = SHA1.new(strng.to_bin(message))
     try:
         signature_int = int(signature)
         signature_bytes = number.long_to_bytes(signature_int)
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (ValueError, TypeError):
         from logs import lg
         lg.exc()
         result = False
     return result
示例#27
0
def pycrypto():
    import Crypto
    from Crypto.Hash import MD2
    from Crypto.Hash import MD4
    from Crypto.Hash import MD5
    from Crypto.Hash import SHA1
    from Crypto.Hash import SHA224
    from Crypto.Hash import SHA256
    from Crypto.Hash import SHA384
    from Crypto.Hash import SHA512
    from Crypto.Hash import HMAC

    Crypto.Hash.MD2.new()  # Noncompliant
    MD2.new()  # Noncompliant
    MD4.new()  # Noncompliant
    MD5.new()  # Noncompliant
    SHA1.new()  # Noncompliant
    SHA224.new()  # Noncompliant
    SHA256.new()  # OK
    SHA384.new()  # OK
    SHA512.new()  # OK
    HMAC.new(b"\x00")  # OK
示例#28
0
 def run(self):
     assert self.outbox is not None
     self.outbox.put((self.p, self.g, self.KA))
     KB = self.inbox.get()
     s = pow(KB, self.Ka, self.p)
     key = SHA1.new(int_to_bytes(s)).digest()[:BS]
     iv = get_random_bytes(BS)
     msg = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
     ciph = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(msg, BS))
     self.outbox.put((ciph, iv))
     ciph, iv = self.inbox.get()
     msgB = unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(ciph), BS)
     assert msg == msgB
     print('Alice: msg ok, done')
示例#29
0
def dsa_verify(y: int, msg: bytes, sig) -> bool:
    r, s = sig
    if not (0 < r < q and 0 < s < q):
        return False
    w = pow(s, -1, q)  # w = k/(h+xr) mod q
    h = int.from_bytes(SHA1.new(msg).digest(), 'big')
    u1 = (h * w) % q  # u1 = hk/(h+xr)
    u2 = (r * w) % q  # u2 = rk/(h+xr)
    v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
    # v0 = g^(hk/(h+xr)) * (g^x)^(rk/(h+xr)) mod p
    #    = g^(k(h+xr)/(h+xr))                mod p
    #    = g^k                               mod p
    # v = v0 mod q = r
    return v == r
示例#30
0
 def run(self):
     assert self.outbox is not None
     p, g, KA = self.inbox.get()
     Kb, KB = dhlib.gen_key(p, g)
     self.outbox.put(KB)
     s = pow(KA, Kb, p)
     key = SHA1.new(int_to_bytes(s)).digest()[:BS]
     ciph, iv = self.inbox.get()
     msg = unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(ciph), BS)
     print('Bob:  ', msg)
     iv = get_random_bytes(BS)
     ciph = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(msg, BS))
     self.outbox.put((ciph, iv))
     print('Bob:   done')
示例#31
0
 def attack3_active(self, ciphA, ivA):
     sA = self.p - self.s
     keyA = SHA1.new(int_to_bytes(sA)).digest()[:BS]
     print("Eve:   Alice's key", keyA.hex())
     msg = unpad(AES.new(keyA, AES.MODE_CBC, ivA).decrypt(ciphA), BS)
     print('Eve:  ', msg)
     ciph = AES.new(self.key, AES.MODE_CBC, ivA).encrypt(pad(msg, BS))
     self.outB.put((ciph, ivA))
     ciph, iv = self.inB.get()
     msg = unpad(AES.new(self.key, AES.MODE_CBC, iv).decrypt(ciph), BS)
     print('Eve:  ', msg)
     ciphA = AES.new(keyA, AES.MODE_CBC, iv).encrypt(pad(msg, BS))
     self.outA.put((ciphA, iv))
     print('Eve:   done')
    def test_asn1_encoding(self):
        """Verify ASN.1 encoding"""

        self.description = "ASN.1 encoding test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3', 'der')
        signature = signer.sign(hash_obj)

        # Verify that output looks like a SEQUENCE
        self.assertEqual(bord(signature[0]), 48)
        signer.verify(hash_obj, signature)

        # Verify that ASN.1 parsing fails as expected
        signature = bchr(7) + signature[1:]
        self.assertRaises(ValueError, signer.verify, hash_obj, signature)
示例#33
0
    def test_asn1_encoding(self):
        """Verify ASN.1 encoding"""

        self.description = "ASN.1 encoding test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3', 'der')
        signature = signer.sign(hash_obj)

        # Verify that output looks like a DER SEQUENCE
        self.assertEqual(bord(signature[0]), 48)
        signer.verify(hash_obj, signature)

        # Verify that ASN.1 parsing fails as expected
        signature = bchr(7) + signature[1:]
        self.assertRaises(ValueError, signer.verify, hash_obj, signature)
示例#34
0
def sha1(inp, hexdigest=False, return_object=False):
    global _CryptoLog
    # if _CryptoLog is None:
    #     _CryptoLog = os.environ.get('CRYPTO_LOG') == '1'
    if not strng.is_bin(inp):
        raise ValueError('input must by byte string')
    h = SHA1.new(inp)
    if _Debug:
        if _CryptoLog:
            lg.args(_DebugLevel, hexdigest=h.hexdigest())
    if return_object:
        return h
    if hexdigest:
        return strng.to_bin(h.hexdigest())
    return h.digest()
示例#35
0
 def verify_signature(self, signature_algorithm, signature, cert, data):
     pubkey = asymmetric.load_public_key(cert.public_key).unwrap().dump()
     rsakey = RSA.importKey(pubkey)
     signer = PKCS1_v1_5.new(rsakey)
     if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS:
         digest = \
             SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS[
                 signature_algorithm].new()
     else:
         # the last resort. should not happen.
         digest = SHA1.new()
     digest.update(data.dump())
     if not signer.verify(digest, signature):
         raise RevocationCheckError(msg="Failed to verify the signature",
                                    errno=ER_INVALID_OCSP_RESPONSE)
示例#36
0
    def decrypt(self, key, entropy = None):
        keyHash = SHA1.new(key).digest()
        sessionKey = HMAC.new(keyHash, self['Salt'], ALGORITHMS_DATA[self['HashAlgo']][1])
        if entropy is not None:
            sessionKey.update(entropy)

        sessionKey = sessionKey.digest()

        # Derive the key
        derivedKey = self.deriveKey(sessionKey)

        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(derivedKey[:ALGORITHMS_DATA[self['CryptAlgo']][0]],
                                mode=ALGORITHMS_DATA[self['CryptAlgo']][2], iv=b'\x00'*ALGORITHMS_DATA[self['CryptAlgo']][3])
        cleartext = unpad(cipher.decrypt(self['Data']), ALGORITHMS_DATA[self['CryptAlgo']][1].block_size)

        # Now check the signature

        # ToDo Fix this, it's just ugly, more testing so we can remove one
        toSign = (self.rawData[20:][:len(self.rawData)-20-len(self['Sign'])-4])

        # Calculate the different HMACKeys
        keyHash2 = keyHash + b"\x00"*ALGORITHMS_DATA[self['HashAlgo']][1].block_size
        ipad = bytearray([i ^ 0x36 for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
        opad = bytearray([i ^ 0x5c for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
        a = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad)
        a.update(self['HMac'])

        hmacCalculated1 = ALGORITHMS_DATA[self['HashAlgo']][1].new(opad)
        hmacCalculated1.update(a.digest())

        if entropy is not None:
            hmacCalculated1.update(entropy)

        hmacCalculated1.update(toSign)

        hmacCalculated3 = HMAC.new(keyHash, self['HMac'], ALGORITHMS_DATA[self['HashAlgo']][1])
        if entropy is not None:
            hmacCalculated3.update(entropy)

        hmacCalculated3.update(toSign)

        if hmacCalculated1.digest() == self['Sign'] or hmacCalculated3.digest() == self['Sign']:
            return cleartext
        else:
            return None
示例#37
0
    def test_streaming(self):
        """Verify that an arbitrary number of bytes can be encrypted/decrypted"""
        from Cryptodome.Hash import SHA1

        segments = (1, 3, 5, 7, 11, 17, 23)
        total = sum(segments)

        pt = b("")
        while len(pt) < total:
            pt += SHA1.new(pt).digest()

        cipher1 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
        ct = cipher1.encrypt(pt)

        cipher2 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
        cipher3 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
        idx = 0
        for segment in segments:
            self.assertEqual(cipher2.decrypt(ct[idx:idx+segment]), pt[idx:idx+segment])
            self.assertEqual(cipher3.encrypt(pt[idx:idx+segment]), ct[idx:idx+segment])
            idx += segment
示例#38
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()

        return key1, key2
 def runTest(self):
     verifier = pkcs1_15.new(RSA.importKey(self.rsakey))
     hashed = SHA1.new(self.msg)
     verifier.verify(hashed, self.signature)