示例#1
0
 def test_nonce_too_long(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me" * 6600
     # pt can be no more than 65536 bytes when nonce is 13 bytes
     nonce = os.urandom(13)
     with pytest.raises(ValueError):
         aesccm.encrypt(nonce, pt, None)
示例#2
0
 def test_nonce_too_long(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me" * 6600
     # pt can be no more than 65536 bytes when nonce is 13 bytes
     nonce = os.urandom(13)
     with pytest.raises(ValueError):
         aesccm.encrypt(nonce, pt, None)
示例#3
0
    def test_invalid_nonce_length(self, backend):
        key = AESCCM.generate_key(128)
        aesccm = AESCCM(key)
        pt = b"hello"
        nonce = os.urandom(14)
        with pytest.raises(ValueError):
            aesccm.encrypt(nonce, pt, None)

        with pytest.raises(ValueError):
            aesccm.encrypt(nonce[:6], pt, None)
示例#4
0
 def test_associated_data_none_equal_to_empty_bytestring(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     nonce = os.urandom(12)
     ct1 = aesccm.encrypt(nonce, b"some_data", None)
     ct2 = aesccm.encrypt(nonce, b"some_data", b"")
     assert ct1 == ct2
     pt1 = aesccm.decrypt(nonce, ct1, None)
     pt2 = aesccm.decrypt(nonce, ct2, b"")
     assert pt1 == pt2
示例#5
0
    def test_data_too_large(self):
        key = AESCCM.generate_key(128)
        aesccm = AESCCM(key)
        nonce = b"0" * 12

        with pytest.raises(OverflowError):
            aesccm.encrypt(nonce, FakeData(), b"")

        with pytest.raises(OverflowError):
            aesccm.encrypt(nonce, b"", FakeData())
示例#6
0
    def test_invalid_nonce_length(self, backend):
        key = AESCCM.generate_key(128)
        aesccm = AESCCM(key)
        pt = b"hello"
        nonce = os.urandom(14)
        with pytest.raises(ValueError):
            aesccm.encrypt(nonce, pt, None)

        with pytest.raises(ValueError):
            aesccm.encrypt(nonce[:6], pt, None)
示例#7
0
 def test_associated_data_none_equal_to_empty_bytestring(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     nonce = os.urandom(12)
     ct1 = aesccm.encrypt(nonce, b"some_data", None)
     ct2 = aesccm.encrypt(nonce, b"some_data", b"")
     assert ct1 == ct2
     pt1 = aesccm.decrypt(nonce, ct1, None)
     pt2 = aesccm.decrypt(nonce, ct2, b"")
     assert pt1 == pt2
示例#8
0
    def test_data_too_large(self):
        key = AESCCM.generate_key(128)
        aesccm = AESCCM(key)
        nonce = b"0" * 12

        with pytest.raises(OverflowError):
            aesccm.encrypt(nonce, FakeData(), b"")

        with pytest.raises(OverflowError):
            aesccm.encrypt(nonce, b"", FakeData())
示例#9
0
 def test_buffer_protocol(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = aesccm.encrypt(nonce, pt, ad)
     computed_pt = aesccm.decrypt(nonce, ct, ad)
     assert computed_pt == pt
     aesccm2 = AESCCM(bytearray(key))
     ct2 = aesccm2.encrypt(bytearray(nonce), pt, ad)
     assert ct2 == ct
     computed_pt2 = aesccm2.decrypt(bytearray(nonce), ct2, ad)
     assert computed_pt2 == pt
示例#10
0
 def test_buffer_protocol(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = aesccm.encrypt(nonce, pt, ad)
     computed_pt = aesccm.decrypt(nonce, ct, ad)
     assert computed_pt == pt
     aesccm2 = AESCCM(bytearray(key))
     ct2 = aesccm2.encrypt(bytearray(nonce), pt, ad)
     assert ct2 == ct
     computed_pt2 = aesccm2.decrypt(bytearray(nonce), ct2, ad)
     assert computed_pt2 == pt
示例#11
0
 def test_vectors(self, subtests, backend):
     vectors = _load_all_params(
         os.path.join("ciphers", "AES", "CCM"),
         [
             "DVPT128.rsp",
             "DVPT192.rsp",
             "DVPT256.rsp",
             "VADT128.rsp",
             "VADT192.rsp",
             "VADT256.rsp",
             "VNT128.rsp",
             "VNT192.rsp",
             "VNT256.rsp",
             "VPT128.rsp",
             "VPT192.rsp",
             "VPT256.rsp",
         ],
         load_nist_ccm_vectors,
     )
     for vector in vectors:
         with subtests.test():
             key = binascii.unhexlify(vector["key"])
             nonce = binascii.unhexlify(vector["nonce"])
             adata = binascii.unhexlify(vector["adata"])[: vector["alen"]]
             ct = binascii.unhexlify(vector["ct"])
             pt = binascii.unhexlify(vector["payload"])[: vector["plen"]]
             aesccm = AESCCM(key, vector["tlen"])
             if vector.get("fail"):
                 with pytest.raises(InvalidTag):
                     aesccm.decrypt(nonce, ct, adata)
             else:
                 computed_pt = aesccm.decrypt(nonce, ct, adata)
                 assert computed_pt == pt
                 assert aesccm.encrypt(nonce, pt, adata) == ct
示例#12
0
def aesccm_mode_encryption(bitlength, filename, key):
    fd = open(filename, "r")
    data = fd.read()
    data = data.encode()
    fd.close()

    if not key:
        print("****Generating key with key length:" + str(bitlength))
        key = AESCCM.generate_key(bit_length=bitlength)
    else:
        fd = shelve.open(key)
        key = fd["key"]
        key = key[0]
    key1 = AESCCM(key)
    nonce = os.urandom(12)

    print("***Encrypting your data***")
    ct = key1.encrypt(nonce, data, None)
    ls = [key, nonce]
    print("***Saving your data to file:" + filename + "_encrypted.db***")
    new_name = filename + "_encrypted"
    db = shelve.open(new_name)
    db["data"] = ct
    db.close()
    print("***saving you key and nonces to file:" + filename + "_keys.db")
    key_file = filename + "_keys"
    db = shelve.open(key_file)
    db["key"] = ls
    db.close()
示例#13
0
def encryptMessage(message, sessionKey, nonce):

    aesccm = AESCCM(sessionKey)

    encMessage = aesccm.encrypt(nonce, message, None)

    return encMessage
示例#14
0
文件: cose.py 项目: IO42630/ace
    def _encrypt(self, key: bytes, iv: bytes, aad: bytes):
        cipher = AESCCM(key, tag_length=8)
        ciphertext = cipher.encrypt(nonce=iv,
                                    data=self.plaintext,
                                    associated_data=aad)

        return ciphertext
示例#15
0
def aes_ccm_encrypt(key: Key, nonce: Nonce, data: bytes, mic_len=32, associated_data: Optional[bytes] = None) -> Tuple[
	bytes, MIC]:
	tag_len = mic_len // 8
	aes_ccm = AESCCM(key.key_bytes, tag_len)
	raw = aes_ccm.encrypt(nonce.as_be_bytes(), data, associated_data)
	mic = MIC(raw[-tag_len:])
	return raw[:-tag_len], mic
示例#16
0
def test_aes_ccm_aead_api(backend, wycheproof):
    key = binascii.unhexlify(wycheproof.testcase["key"])
    iv = binascii.unhexlify(wycheproof.testcase["iv"])
    aad = binascii.unhexlify(wycheproof.testcase["aad"])
    msg = binascii.unhexlify(wycheproof.testcase["msg"])
    ct = binascii.unhexlify(wycheproof.testcase["ct"])
    tag = binascii.unhexlify(wycheproof.testcase["tag"])

    if (wycheproof.invalid
            and wycheproof.testcase["comment"] == "Invalid tag size"):
        with pytest.raises(ValueError):
            AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8)
        return

    aesccm = AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8)
    if wycheproof.valid or wycheproof.acceptable:
        computed_ct = aesccm.encrypt(iv, msg, aad)
        assert computed_ct == ct + tag
        computed_msg = aesccm.decrypt(iv, ct + tag, aad)
        assert computed_msg == msg
    elif not 7 <= len(iv) <= 13:
        with pytest.raises(ValueError):
            aesccm.decrypt(iv, ct + tag, aad)
    else:
        with pytest.raises(InvalidTag):
            aesccm.decrypt(iv, ct + tag, aad)
示例#17
0
 def test_default_tag_length(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     nonce = os.urandom(12)
     pt = b"hello"
     ct = aesccm.encrypt(nonce, pt, None)
     assert len(ct) == len(pt) + 16
示例#18
0
 def test_default_tag_length(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     nonce = os.urandom(12)
     pt = b"hello"
     ct = aesccm.encrypt(nonce, pt, None)
     assert len(ct) == len(pt) + 16
示例#19
0
def main():

    if len(sys.argv) <= 4:
        print("Need path to binary file and library name.")
        print("Exiting...")
        sys.exit()

    filepath_aad = sys.argv[1]  # authenticated associated data
    filepath = sys.argv[2]
    use_encryption = sys.argv[3]
    libname = sys.argv[4]

    if not os.path.isfile(filepath):
        print("File {} does not exist. Exiting...".format(filepath))
        sys.exit()

    if not os.path.isfile(filepath_aad):
        print("File {} does not exist. Exiting...".format(filepath_aad))
        sys.exit()

    with open(filepath, "rb") as f:
        data = f.read()

    with open(filepath_aad, "rb") as f:
        data_aad = f.read()

    if use_encryption == "1":
        aesccm = AESCCM(key, tag_size)
        # Put the nonce at the start of the file.
        data_enc = nonce + aesccm.encrypt(nonce, data, data_aad)
        with open(libname, "wb") as f:
            f.write(data_enc)
    else:
        with open(libname, "wb") as f:
            f.write(data)
示例#20
0
def test_aes_ccm_aead_api(backend, wycheproof):
    key = binascii.unhexlify(wycheproof.testcase["key"])
    iv = binascii.unhexlify(wycheproof.testcase["iv"])
    aad = binascii.unhexlify(wycheproof.testcase["aad"])
    msg = binascii.unhexlify(wycheproof.testcase["msg"])
    ct = binascii.unhexlify(wycheproof.testcase["ct"])
    tag = binascii.unhexlify(wycheproof.testcase["tag"])

    if (
        wycheproof.invalid and
        wycheproof.testcase["comment"] == "Invalid tag size"
    ):
        with pytest.raises(ValueError):
            AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8)
        return

    aesccm = AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8)
    if wycheproof.valid or wycheproof.acceptable:
        computed_ct = aesccm.encrypt(iv, msg, aad)
        assert computed_ct == ct + tag
        computed_msg = aesccm.decrypt(iv, ct + tag, aad)
        assert computed_msg == msg
    elif not 7 <= len(iv) <= 13:
        with pytest.raises(ValueError):
            aesccm.decrypt(iv, ct + tag, aad)
    else:
        with pytest.raises(InvalidTag):
            aesccm.decrypt(iv, ct + tag, aad)
示例#21
0
    def encrypt(self,key,msg):

        aesccm = AESCCM(key)
        nonce = get_random_bytes(13)
        ct = aesccm.encrypt(nonce, msg,None)
        return (nonce,ct)

        return msg
示例#22
0
 def test_roundtrip(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = aesccm.encrypt(nonce, pt, ad)
     computed_pt = aesccm.decrypt(nonce, ct, ad)
     assert computed_pt == pt
示例#23
0
def AES_CCM_ecnrypt(text):
    data = bytes(text,'utf-8')
    aad = bytes("Research",'utf-8')
    key = AESCCM.generate_key(bit_length=128)
    aesccm = AESCCM(key)
    nonce = os.urandom(12)
    ct = aesccm.encrypt(nonce, data, aad)
    aesccm.decrypt(nonce, ct, aad)
    return True 
示例#24
0
 def test_roundtrip(self, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = aesccm.encrypt(nonce, pt, ad)
     computed_pt = aesccm.decrypt(nonce, ct, ad)
     assert computed_pt == pt
示例#25
0
def repo_thread(conn):
    while True:
        try:
            # get data
            data = recvall(conn)
            if data:
                s = data.decode("utf-8")
                data = json.loads(s)
                # first messages from the client
                # This message is not secure
                if "type" in data.keys() and (data["type"] == "otp_needed" or data["type"] == "requestId"):
                    print("MESSAGE REQUEST:", data["type"])
                    resp = message_execute(data)
                    if resp != None:
                        resp_json = json.dumps(resp)
                        conn.send(bytes(resp_json, 'utf-8'))
                # deal with the message to save session key
                elif 'from' not in data.keys():
                    print("MESSAGE REQUEST:", data["type"])
                    resp, serial = message_execute(data)
                    if resp != None:
                        resp_json = json.dumps(resp)
                        nonce = os.urandom(13)
                        aesccm = AESCCM(myAuction.clients_keys[int(serial)])
                        b = aesccm.encrypt(nonce, bytes(resp_json, 'utf-8'), None)
                        data_str = json.dumps({"nonce": base64.b64encode(nonce).decode(), "data" : base64.b64encode(b).decode()})
                        conn.send(bytes(data_str, 'utf-8'))
                # deal with all the other messages with the structure : "{ from : id , data : encrypted_data , nonce : nonce used }"
                else:
                    aesccm = AESCCM(myAuction.clients_keys[data['from']])
                    d = aesccm.decrypt(base64.b64decode(data['nonce']), base64.b64decode(data['data']), None)
                    j = json.loads(d.decode())
                    print("MESSAGE REQUEST:", j["type"])
                    resp = message_execute(j)
                    if resp != None:
                        resp_json = json.dumps(resp)
                        data_str = json.dumps({"message" : resp_json})
                        nonce = os.urandom(8)
                        b = aesccm.encrypt(nonce, bytes(data_str, 'utf-8'), None)
                        data_str = json.dumps({"nonce": base64.b64encode(nonce).decode(), "data" : base64.b64encode(b).decode()})
                        conn.send(bytes(data_str, 'utf-8'))
            
        except SocketError:
            pass
示例#26
0
def test_java_bouncy_castle_ccm_matching():
    K = codecs.decode("404142434445464748494a4b4c4d4e4f", "hex")
    N = codecs.decode("10111213141516", "hex")
    P = codecs.decode("68656c6c6f20776f726c642121", "hex")
    C = codecs.decode("39264f148b54c456035de0a531c8344f46db12b388", "hex")

    cipher = AESCCM(K, tag_length=8)
    ciphertext = cipher.encrypt(N, P, None)

    assert ciphertext == C
示例#27
0
def _encrypt_ccm(secret_key, value, field_max_length=None):
    aesccm = AESCCM(secret_key)
    nonce = os.urandom(AES_CCM_NONCE_LENGTH)
    ct = aesccm.encrypt(nonce, value.encode("utf-8"), None)
    encrypted = base64.b64encode(nonce + ct)
    if field_max_length:
        msg = "Tried to encode a value too large for this field"
        assert (len(encrypted) +
                _RESERVED_FIELD_SPACE) <= field_max_length, msg

    return encrypted
示例#28
0
文件: privacy.py 项目: mazent/CY5677
class CYBLE_AESCCM:
    """
    To be used with cyble internal functions
    """
    def __init__(self, key16):
        self.aesccm = AESCCM(key16, tag_length=4)

    def CyBle_AesCcmEncrypt(self, nonce13, plaintext):
        """
        Acts like the cyble function

        :param nonce13: bytes
        :param plaintext: bytes (1..27)
        :return: ciphertext (bytes)
        """
        return self.aesccm.encrypt(nonce13, plaintext, bytes([1]))

    def CyBle_AesCcmDecrypt(self, nonce13, ciphertext):
        """
        Acts like the cyble function

        :param nonce13: bytes
        :param ciphertext: bytes (1..27)
        :return: plaintext (bytes)
        """
        return self.aesccm.decrypt(nonce13, ciphertext, bytes([1]))

    def crypt(self, cosa):
        """
        receives plaintext and returns the ciphertext

        :param cosa: bytes/str
        :return: bytes
        """
        if isinstance(cosa, str):
            cosa = bytes(cosa.encode('ascii'))

        # an handful of random bytes
        ahorb = bytes(secrets.token_bytes(13))

        return ahorb + self.CyBle_AesCcmEncrypt(ahorb, cosa)

    def decrypt(self, cosa):
        """
        receives ciphertext and returns the plaintext

        :param cosa: bytes
        :return: bytes
        """

        return self.CyBle_AesCcmDecrypt(bytes(cosa[:13]), bytes(cosa[13:]))
示例#29
0
 def test_vectors(self, vector, backend):
     key = binascii.unhexlify(vector["key"])
     nonce = binascii.unhexlify(vector["nonce"])
     adata = binascii.unhexlify(vector["adata"])[:vector["alen"]]
     ct = binascii.unhexlify(vector["ct"])
     pt = binascii.unhexlify(vector["payload"])[:vector["plen"]]
     aesccm = AESCCM(key, vector["tlen"])
     if vector.get('fail'):
         with pytest.raises(InvalidTag):
             aesccm.decrypt(nonce, ct, adata)
     else:
         computed_pt = aesccm.decrypt(nonce, ct, adata)
         assert computed_pt == pt
         assert aesccm.encrypt(nonce, pt, adata) == ct
示例#30
0
 def test_vectors(self, vector, backend):
     key = binascii.unhexlify(vector["key"])
     nonce = binascii.unhexlify(vector["nonce"])
     adata = binascii.unhexlify(vector["adata"])[:vector["alen"]]
     ct = binascii.unhexlify(vector["ct"])
     pt = binascii.unhexlify(vector["payload"])[:vector["plen"]]
     aesccm = AESCCM(key, vector["tlen"])
     if vector.get('fail'):
         with pytest.raises(InvalidTag):
             aesccm.decrypt(nonce, ct, adata)
     else:
         computed_pt = aesccm.decrypt(nonce, ct, adata)
         assert computed_pt == pt
         assert aesccm.encrypt(nonce, pt, adata) == ct
示例#31
0
def Algo4(filename, key, nonce):
    aad = "authenticated but unencrypted data"
    aesccm = AESCCM(key)
    source_filename = 'files/' + filename
    target_filename = 'encrypted/' + filename
    file = open(source_filename, 'rb')
    target_file = open(target_filename, 'wb')
    raw = ""
    for line in file:
        raw = raw + line
    secret_data = aesccm.encrypt(nonce, raw, aad)
    target_file.write(secret_data)
    file.close()
    target_file.close()
示例#32
0
    def configure(self):
        my_private_key = self.generate_private_key()
        self.my_pub_key_data = self.encode_pub_key(my_private_key.public_key())

        self.bt_write(service_uuid, step1, True, "\x01\x00")
        self.bt_write(service_uuid, step1plus, True, "\x01\x00")
        self.bt_write(service_uuid, step1plus, False, CMD_GET_INFO)

        while self.state != WR_DID_STATE:
            if self.p.waitForNotifications(1.0):
                # handleNotification() was called
                continue

            print "Waiting..."
            # Perhaps do something else here
        remote_key = self.decode_pub_key(self.remote_key_data)
        e_share_key = self.create_e_share_key(remote_key, my_private_key)
        print("eShareKey:", e_share_key.encode("hex"))

        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=64,
                           salt=None,
                           info=b'mible-setup-info',
                           backend=default_backend()).derive(e_share_key)
        print("HKDF result:", derived_key.encode("hex"))
        token = derived_key[0:12]
        bind_key = derived_key[12:28]
        A = derived_key[28:44]
        print("token:", token.encode("hex"))
        print("bind_key:", bind_key.encode("hex"))
        print("A:", A.encode("hex"))

        aesccm = AESCCM(A)
        nonce = bytearray([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27])
        did = "blt.3.129vl4ap05o01".encode()
        aad = "devID".encode()
        self.did_ct = aesccm.encrypt(nonce, did, aad)

        print("AES did CT:", self.did_ct.encode("hex"))

        self.bt_write(service_uuid, step1, False, CMD_WR_DID)

        while self.state != FINISHED_STATE:
            if self.p.waitForNotifications(1.0):
                # handleNotification() was called
                continue

            print "Waiting..."
示例#33
0
def Myencrypt(M, key):
    # If the key length is too short, return with error
    if (len(key) < 32):
        return "Your key length is too short: " + str(len(key))

    # Class object to perform AES encryption with CBC-MAC integrity checks
    aesccm = AESCCM(key)

    # Check if the Message is not a byte array.
    if (not isinstance(M, bytes)):
        data = M.encode('utf-8')
    else:
        data = M

    # OS entropy pool IV
    IV = os.urandom(13)

    # Encrypt using the AES/CBC-MAC object
    ct = aesccm.encrypt(IV, data, "None".encode('utf-8'))
    return ct, IV
示例#34
0
def encrypt_file(input_file_name : str, output_file_name : str, key : bytes) -> None:

    input_file = open(input_file_name, "rb")
    output_file = open(output_file_name, "wb")

    # AES-CCM instance.
    aesccm = AESCCM(key, tag_length=TAG_SIZE_BYTES)

    # Nonce is starting with 1 for the first page.
    nonce_value = 1

    while True:

        data_page = input_file.read(EFFECTIVE_PAGE_SIZE_BYTES)
        if len(data_page) == 0:
            break

        # Convert nonce to machine representation.
        nonce = nonce_value.to_bytes(NONCE_SIZE_BYTES, NONCE_BYTE_ORDER)

        # Encrypt page.
        aesccm_output = aesccm.encrypt(nonce, data_page, None)

        encrypted_data = aesccm_output[0:len(data_page)]
        tag = aesccm_output[len(data_page):]

        # Verify sizes are as they are expected to be.
        assert len(tag) == TAG_SIZE_BYTES
        assert len(encrypted_data) + len(tag) == len(aesccm_output)

        # Write tag and encrypted data (in reverse order compared to
        # output of encryption function).
        output_file.write(tag)
        output_file.write(encrypted_data)

        nonce_value += 1

    input_file.close()
    output_file.close()
    return hex_.hex()


if __name__ == '__main__':
    args = arguments()
    print(args)
    if args['generate_key'] and args['key_size']:
        key = AESCCM.generate_key(bit_length=int(args['key_size']))
        aesccm = AESCCM(key)
        aad = b'authentic'
        nouce = os.urandom(13)
        for file_ in args['file']:
            ct = None
            with open(file_, 'rb') as data:
                if args['operation'] == 'encrypt':
                    ct = aesccm.encrypt(nouce, data.read(), aad)
            with open(file_, 'wb') as writer:
                writer.write(ct)
        print(hexdigest(key))
        print(hexdigest(nouce))
    else:
        aesccm = AESCCM(str_2_hex(args['key']))
        aad = b'authentic'
        nouce = os.urandom(13)
        for file_ in args['file']:
            ct = None
            with open(file_, 'rb') as data:
                if args['operation'] == 'encrypt':
                    ct = aesccm.encrypt(nouce, data.read(), aad)
                else:
                    nouce = str_2_hex(args['nouce'])
示例#36
0
def Encrypt(key_ccm, nonce, data, aad):
    aesccm = AESCCM(key_ccm, 8)
    return aesccm.encrypt(nonce, data, aad)
示例#37
0
 def test_params_not_bytes(self, nonce, data, associated_data, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     with pytest.raises(TypeError):
         aesccm.encrypt(nonce, data, associated_data)
示例#38
0
    #    devices = scanner.scan(10.0)
    #
    #    for dev in devices:
    #        print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
    #        for (adtype, desc, value) in dev.getScanData():
    #            print("  %s = %s" % (desc, value))

    private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    public_key = private_key.public_key()
    shared_key = private_key.exchange(ec.ECDH(), public_key)
    print(" shared key :", shared_key.hex())
    derived_key = HKDF(algorithm=hashes.SHA256(),
                       length=64,
                       salt=None,
                       info=b'mible-setup-info',
                       backend=default_backend()).derive(shared_key)
    print("derived key :", derived_key.hex())
    token = derived_key[0:12]
    bind_key = derived_key[12:28]
    A = derived_key[28:44]
    print("      token :", token.hex())
    print("   bind_key :", bind_key.hex())
    print("          A :", A.hex())

    aesccm = AESCCM(A)
    nonce = bytearray([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27])
    did = "blt.3.129vl4ap05o01".encode()
    aad = "devID".encode()
    did_ct = aesccm.encrypt(nonce, did, aad)
    print("    AES did :", did_ct.hex())
示例#39
0
from cryptography.hazmat.primitives.ciphers.aead import AESCCM
from cryptography.hazmat.backends import default_backend
import os

# The sample code is extracted from the book Python Cryptography
# The book can be downloaded from https://leanpub.com/cryptop
# Online Crypto Playgroud https://8gwifi.org
# Author Anish Nath

backend = default_backend()

nonce = os.urandom(13)
message = "Hello 8gwifi.org"
aaed = "Not Secret"

# This AES key is 128 but long
key = AESCCM.generate_key(256)
aesccm = AESCCM(key)

#AES-256 GCM Mode Encyption
ct = aesccm.encrypt(nonce, message, aaed)

print ct

assert message, aesccm.decrypt(nonce, ct, aaed)
示例#40
0
 def test_params_not_bytes(self, nonce, data, associated_data, backend):
     key = AESCCM.generate_key(128)
     aesccm = AESCCM(key)
     with pytest.raises(TypeError):
         aesccm.encrypt(nonce, data, associated_data)