Esempio n. 1
0
File: gcm.py Progetto: hdknr/jose
    def decrypt(cls, cek, ciphert, iv, aad, tag, *args,  **kwargs):
        assert cek and len(cek) == cls._KEY_LEN
        assert iv and len(iv) == cls._IV_LEN
        assert tag and len(tag) == cls._TAG_LEN

        ci = AES_GCM(bytes_to_long(cek))
        try:
            plaint = ci.decrypt(bytes_to_long(iv), ciphert,
                                bytes_to_long(tag), aad)
            return plaint, True
        except InvalidTagException:
            return (None, False)
Esempio n. 2
0
        for i in range(1000):
            iv = getrandbits(96)
            a = long_to_bytes(getrandbits(1024))
            s, t = test_gcm.encrypt(iv, s, a)
            states.append(s)
            tags.append(t)
            ivs.append(iv)
            aads.append(a)

        # extra decryptions
        for i in range(999, -1, -1):
            assert s == states[i]
            iv = ivs[i]
            t = tags[i]
            a = aads[i]
            s = test_gcm.decrypt(iv, s, t, a)
        encrypted = s

        decrypted = test_gcm.decrypt(
            test_data['init_value'],
            encrypted,
            tag,
            test_data['auth_data']
        )

        if encrypted != test_data['ciphertext'] or \
                tag != test_data['auth_tag'] or \
                decrypted != test_data['plaintext']:
            num_failures += 1
            print 'This test case failed:'
            pprint(test_data)
Esempio n. 3
0
        for i in range(1000):
            iv = getrandbits(96)
            a = long_to_bytes(getrandbits(1024))
            s, t = test_gcm.encrypt(iv, s, a)
            states.append(s)
            tags.append(t)
            ivs.append(iv)
            aads.append(a)

        # extra decryptions
        for i in range(999, -1, -1):
            assert s == states[i]
            iv = ivs[i]
            t = tags[i]
            a = aads[i]
            s = test_gcm.decrypt(iv, s, t, a)
        encrypted = s

        decrypted = test_gcm.decrypt(test_data['init_value'], encrypted,
                                     test_data['auth_tag'],
                                     test_data['auth_data'])

        if encrypted != test_data['ciphertext'] or \
                tag != test_tag or \
                decrypted != test_data['plaintext']:
            num_failures += 1
            print('This test case failed:')
            pprint(test_data)
            print("Encrypted: %s (%s)" %
                  (enc_dbg, encrypted == test_data['ciphertext']))
            print("Tag: %s (%s)" % (tag_dbg, tag == test_tag))
Esempio n. 4
0
def process(line):
    global current_test
    global success_count
    global fail_count
    sline = line.strip()
    if sline.startswith("["):
        data = sline[1:-1]
        key, value = data.split("=", 1)
        current_test_parameters[key.strip()] = int(value)
    elif (sline == "" and not current_test) or line.startswith("#"):
        return
    elif sline == "" and 'count' in current_test.keys():
        errors = []
        if 'PT' not in current_test.keys():
            current_test['PT'] = ''
        test_gcm = AES_GCM(int(current_test['Key'], 16))
        test_aad = b'' if (len(current_test['AAD']) == 0) else long_to_bytes(
            int(current_test['AAD'], 16))
        test_tag = b'' if (len(current_test['Tag']) == 0) else int(
            current_test['Tag'], 16)
        test_crypttext = b'' if (len(current_test['CT'])
                                 == 0) else long_to_bytes(
                                     int(current_test['CT'], 16))
        test_plaintext = b'' if (len(current_test['PT'])
                                 == 0) else long_to_bytes(
                                     int(current_test['PT'], 16))
        test_iv = int(current_test['IV'], 16)
        tag_len = int(int(current_test_parameters['Taglen']) / 8)
        try:
            computed_crypttext, computed_tag = test_gcm.encrypt(
                test_iv, test_plaintext, test_aad, tag_len)
        except ValueError as e:
            errors.append(e)
        if computed_tag != test_tag:
            errors.append("Tag mismatch after encryption")
        computed_plaintext = b''
        try:
            computed_plaintext = test_gcm.decrypt(test_iv, test_crypttext,
                                                  test_tag, test_aad, tag_len)
            if computed_plaintext != test_plaintext:
                errors.append("Plaintext mismatch")
        except InvalidTagException:
            errors.append("Tag mismatch while decrypting")
        test_passed = current_test['fail'] == (len(errors) > 0)
        if not test_passed:
            fail_count += 1
            print("\n\nFailed test %s" % current_test['count'])
            print("Parameters:")
            print(current_test_parameters)
            print("Test case:")
            print(current_test)
            print(errors)
            print("Crypttext")
            print(" Test:     %s" % test_crypttext)
            print(" Computed: %s" % computed_crypttext)
            print("Plaintext")
            print(" Test:     %s" % test_plaintext)
            print(" Computed: %s" % computed_plaintext)
            print("Tags")
            print(" Test:     %s" % hex(test_tag))
            print(" Computed: %s" % hex(computed_tag))
            print("Failed: %s | Success: %s" % (fail_count, success_count))
        else:
            success_count += 1
        current_test = None
    elif line.startswith("Count ="):
        current_test = {'count': int(line.split("=", 1)[1]), 'fail': False}
    elif " = " in line:
        name, value = line.split(" = ", 1)
        current_test[name.strip()] = value.strip()
    elif sline == "FAIL":
        current_test['fail'] = True
    else:
        print("unknown line: %s" % line)
Esempio n. 5
0
        for i in range(1000):
            iv = getrandbits(96)
            a = long_to_bytes(getrandbits(1024))
            s, t = test_gcm.encrypt(iv, s, a)
            states.append(s)
            tags.append(t)
            ivs.append(iv)
            aads.append(a)

        # extra decryptions
        for i in range(999, -1, -1):
            assert s == states[i]
            iv = ivs[i]
            t = tags[i]
            a = aads[i]
            s = test_gcm.decrypt(iv, s, t, a)
        encrypted = s

        decrypted = test_gcm.decrypt(test_data["init_value"], encrypted, tag, test_data["auth_data"])

        if encrypted != test_data["ciphertext"] or tag != test_data["auth_tag"] or decrypted != test_data["plaintext"]:
            num_failures += 1
            print("This test case failed:")
            pprint(test_data)
            print()

    if num_failures == 0:
        print("All test cases passed!")
    else:
        print(num_failures, "test cases failed in total.")