Beispiel #1
0
    def test_params_not_bytes(self, nonce, data, associated_data, backend):
        key = AESGCM.generate_key(128)
        aesgcm = AESGCM(key)
        with pytest.raises(TypeError):
            aesgcm.encrypt(nonce, data, associated_data)

        with pytest.raises(TypeError):
            aesgcm.decrypt(nonce, data, associated_data)
Beispiel #2
0
    def test_data_too_large(self):
        key = AESGCM.generate_key(128)
        aesgcm = AESGCM(key)
        nonce = b"0" * 12

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

        with pytest.raises(OverflowError):
            aesgcm.encrypt(nonce, b"", FakeData())
Beispiel #3
0
 def test_associated_data_none_equal_to_empty_bytestring(self, backend):
     key = AESGCM.generate_key(128)
     aesgcm = AESGCM(key)
     nonce = os.urandom(12)
     ct1 = aesgcm.encrypt(nonce, b"some_data", None)
     ct2 = aesgcm.encrypt(nonce, b"some_data", b"")
     assert ct1 == ct2
     pt1 = aesgcm.decrypt(nonce, ct1, None)
     pt2 = aesgcm.decrypt(nonce, ct2, b"")
     assert pt1 == pt2
Beispiel #4
0
 def test_buffer_protocol(self, backend):
     key = AESGCM.generate_key(128)
     aesgcm = AESGCM(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = aesgcm.encrypt(nonce, pt, ad)
     computed_pt = aesgcm.decrypt(nonce, ct, ad)
     assert computed_pt == pt
     aesgcm2 = AESGCM(bytearray(key))
     ct2 = aesgcm2.encrypt(bytearray(nonce), pt, ad)
     assert ct2 == ct
     computed_pt2 = aesgcm2.decrypt(bytearray(nonce), ct2, ad)
     assert computed_pt2 == pt
Beispiel #5
0
def test_aes_gcm_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"])
    aesgcm = AESGCM(key)
    if wycheproof.valid or wycheproof.acceptable:
        computed_ct = aesgcm.encrypt(iv, msg, aad)
        assert computed_ct == ct + tag
        computed_msg = aesgcm.decrypt(iv, ct + tag, aad)
        assert computed_msg == msg
    elif len(iv) == 0:
        with pytest.raises(ValueError):
            aesgcm.encrypt(iv, msg, aad)
    else:
        with pytest.raises(InvalidTag):
            aesgcm.decrypt(iv, ct + tag, aad)
Beispiel #6
0
def getlist():
    ts = random.getrandbits(8)
    temp["ts"] = ts
    listdict = {"msg": "list", "ts": ts}
    # print "dict okay"
    aesgcm = AESGCM(temp["sk"])
    # print aesgcm
    nonce = os.urandom(12)
    ct = aesgcm.encrypt(nonce, bytes(listdict), None)
    # print "encryption okay"
    batch = {"edict": ct, "nonce": nonce}
    # print "batch okay"
    fillauthpacket(pkt1, "List", 1, bytes(batch))
    sendpacket(pkt1.SerializeToString(), SIP, UDP_PORT)
def encrypt_opaque(sessionid, hmac_key, expiration_time,
                   hash_mask, auth_headers, extra_auth_headers):
    aesgcm = AESGCM(SECRET_KEY)
    # start the nonce off with the current epoch time
    nonce = struct.pack(">I", int(time.time()))
    # add 8 random bytes for a total of 128 bits
    nonce += os.urandom(8)

    plaintext = '|'.join((sessionid, hmac_key, expiration_time))
    auth_data = '|'.join((hash_mask, auth_headers, extra_auth_headers))

    ciphertext = aesgcm.encrypt(nonce, plaintext, auth_data)
    ciphertext, tag = ciphertext[:-16], ciphertext[-16:]
    return ciphertext, nonce, tag
def test_aes_gcm_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 backend._fips_enabled and len(iv) != 12:
        # Red Hat disables non-96-bit IV support as part of its FIPS
        # patches.
        pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
    aesgcm = AESGCM(key)
    if wycheproof.valid or wycheproof.acceptable:
        computed_ct = aesgcm.encrypt(iv, msg, aad)
        assert computed_ct == ct + tag
        computed_msg = aesgcm.decrypt(iv, ct + tag, aad)
        assert computed_msg == msg
    elif len(iv) == 0:
        with pytest.raises(ValueError):
            aesgcm.encrypt(iv, msg, aad)
    else:
        with pytest.raises(InvalidTag):
            aesgcm.decrypt(iv, ct + tag, aad)
def Algo3(filename, key, nonce):
    aad = "authenticated but unencrypted data"
    aesgcm = AESGCM(key)
    source_filename = 'files/' + filename
    target_filename = 'encrypted/' + filename
    file = open(source_filename, 'rb')
    target_file = open(target_filename, 'wb')
    raw = b""
    for line in file:
        raw = raw + line
    secret_data = aesgcm.encrypt(nonce, raw, aad)
    target_file.write(secret_data)
    file.close()
    target_file.close()
Beispiel #10
0
def encrypt(clear, key, salt, nonce):
    password_bytes = key.encode('utf-8')
    kdf = PBKDF2HMAC(algorithm=hashes.SHA512(),
                     length=32,
                     salt=salt,
                     iterations=10000,
                     backend=default_backend())
    key = kdf.derive(password_bytes)
    aesgcm = AESGCM(key)
    cipher_text_bytes = aesgcm.encrypt(nonce=nonce,
                                       data=clear.encode('utf-8'),
                                       associated_data=None)
    cipher_text = base64.urlsafe_b64encode(cipher_text_bytes)
    return cipher_text
Beispiel #11
0
def init_host_key():
    nonce = utils.generate_secret_len(16)
    nonces_add(nonce)

    data = {
        'n': nonce,
        't': int(time.time()),
        'h': settings.local.se_host_key,
    }

    auth_data = data['n'] + '&' + str(data['t']) + '&' + data['h']

    data['a'] = base64.b64encode(hmac.new(
        settings.local.se_authorize_key,
        auth_data,
        hashlib.sha512,
    ).digest())

    gcm = AESGCM(settings.local.se_encryption_key)

    nonce = os.urandom(12)

    ciphertext = gcm.encrypt(
        nonce,
        json.dumps(data),
        None,
    )

    nonce64 = base64.b64encode(nonce)
    nonces_add(nonce64)

    payload = {
        'n': nonce64,
        'd': base64.b64encode(ciphertext),
    }

    resp = requests.post(
        'http://127.0.0.1:9758/key',
        verify=False,
        headers={
            'User-Agent': 'pritunl',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        data=json.dumps(payload),
    )

    if resp.status_code != 200:
        raise RequestError('Vault bad status %s' % resp.status_code)
Beispiel #12
0
    def encrypt(key, pt, associated_data=None):
        if not isinstance(key, bytes):
            raise TypeError("key must be of type: bytes")
        if not len(key) == AES256GCM.KEY_LEN:
            raise ValueError("key must be 32 bytes")
        if not isinstance(pt, bytes):
            raise TypeError("pt must be of type: bytes")
        if associated_data and not isinstance(associated_data, bytes):
            raise TypeError("associated_data must be of type: bytes")

        aesgcm = AESGCM(key)
        iv = os.urandom(AES256GCM.IV_LEN)
        ct = aesgcm.encrypt(iv, pt, associated_data)

        return ct + iv
Beispiel #13
0
    def encrypt_data(cls, priv_key_path, input_filename):
        # FIXME: if file is larger than memory, we should read in chunks
        with open(priv_key_path, "rb") as priv_key, open(input_filename,
                                                         "rb") as input_file:

            key = priv_key.read()
            data = input_file.read()
            cipher = AESGCM(key)

            nonce = os.urandom(cls.NONCE_SIZE)
            enc_data = cipher.encrypt(nonce, data, b"")

            data = nonce + enc_data

            return data
Beispiel #14
0
def sendfunction(rec, availusers):
    if rec in known_users:
        kAB = known_users[rec]["ssAB"]
        aesgcm = AESGCM(kAB)
        nonceformsg = os.urandom(12)
        message = aesgcm.encrypt(nonceformsg, keyestfunction.smsg, None)
        msgtosend = {"nonceformsg": nonceformsg, "msg": message}
        fillauthpacket(pkt1, "Data", 0, bytes(msgtosend))
        sendpacket(pkt1.SerializeToString(), availusers[rec]["ipaddr"],
                   availusers[rec]["port"])

    else:
        fillauthpacket(pkt1, "KEY_EST", 3, "Connect")
        sendpacket(pkt1.SerializeToString(), availusers[rec]["ipaddr"],
                   availusers[rec]["port"])
Beispiel #15
0
def test_encryption():
    data = b"a secret message"
    nonce = b"84b41aa0e4c1277ee3d785e2"  # need to be same during en- and decryption
    key = hashlib.sha256(getpass.getpass().encode()).digest()
    print("data: '{}'  nonce: {}   key: {}".format(data.decode(), a(nonce),
                                                   a(key)))

    # encrypt
    aesgcm = AESGCM(key)
    ct = aesgcm.encrypt(nonce, data, None)
    print("Ciphertext: {}".format(a(ct)))

    # decrypt
    msg = aesgcm.decrypt(nonce, ct, None)
    print("Plaintext: {}".format(msg.decode()))
Beispiel #16
0
class Connection:
    def __init__(self):
        self.CODEC = "utf-8"
        self.PACKET_SIZE = 1024

        HOST = "127.0.0.1"
        PORT = 10001
        KEY = b'\xbch`9\xd6k\xcbT\xed\xa5\xef_\x9d*\xda\xd2sER\xedA\xc0a\x1b)\xcc9\xb2\xe7\x91\xc2A'

        self.crypter = AESGCM(KEY)

        if len(sys.argv) == 3:
            try:
                HOST = str(sys.argv[1])
                PORT = int(sys.argv[2])
            except ValueError:  # InvalidCommandlineArguments
                HOST = "127.0.0.1"
                PORT = 10001

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        while True:
            try:
                self.sock.connect((HOST, PORT))
                break
            except socket.error:
                time.sleep(30)

    def send(self, data: dict):
        data = self.encrypt(json.dumps(data.copy()).encode(self.CODEC))
        self.sock.sendall(str(len(data)).encode("utf8"))
        self.sock.recv(self.PACKET_SIZE)
        self.sock.sendall(data)

    def recv(self) -> dict:
        header = int(self.sock.recv(self.PACKET_SIZE).decode("utf8"))
        self.sock.send("READY".encode("utf8"))
        data = bytearray()
        for _ in range(math.ceil(header / self.PACKET_SIZE)):
            data.extend(self.sock.recv(self.PACKET_SIZE))
        return json.loads(self.decrypt(bytes(data)).decode(self.CODEC))

    def encrypt(self, data):
        nonce = os.urandom(12)
        return nonce + self.crypter.encrypt(nonce, data, b"")

    def decrypt(self, cipher):
        return self.crypter.decrypt(cipher[:12], cipher[12:], b"")
Beispiel #17
0
    def __load(self, args):
        if len(args) != 2:
            print('load <remote_filename> <pbkdf2_pwd>\n')
            print('pbkdf2_pwd\t at most 64 printable ASCII characters')
            return

        try:
            mapfile = open(args[0] + '.map', 'r')
            self.mapstr = mapfile.read()
            mapfile.close()
        except OSError:
            print('No .map file found for the specified index')
            return

        padded_pwd = bytearray(64)  # 64 \x00 bytes
        pwd_bytes = args[1].encode("ascii", errors="ignore")

        for i in range(0, min(64, len(pwd_bytes))):
            padded_pwd[i] = pwd_bytes[i]

        # encrypt such data
        iv = os.urandom(12)

        gcm = AESGCM(self.context.SK)
        enc_pwd_mac = gcm.encrypt(iv, bytes(padded_pwd), None)
        # get mac
        mac = enc_pwd_mac[-16:]
        # get encrypted password
        enc_pwd = enc_pwd_mac[0:64]

        # append filename
        payload = enc_pwd + bytes(args[0], encoding='utf-8')

        # build json
        msg = {}
        msg['iv'] = base64.b64encode(iv).decode('utf-8')
        msg['mac'] = base64.b64encode(mac).decode('utf-8')
        msg['payload'] = base64.b64encode(payload).decode('utf-8')

        jmsg = json.dumps(msg)
        req = requests.post(self.url_base + '/load',
                            headers=self.session_cookie,
                            data=jmsg)

        if req.status_code != 202:
            print(req.json()['error'])
        else:
            self.filename = args[0]
Beispiel #18
0
def encrypt_token(context):
    token_file = os.path.join(base_dir, context)
    nonce = os.urandom(16)
    data = input("OTP Token: ")
    key = hashlib.sha256(getpass.getpass().encode()).digest()
    print("data: '{}'  nonce: {}   key: {}".format(data, a(nonce), a(key)))

    # encrypt
    aesgcm = AESGCM(key)
    ct = aesgcm.encrypt(nonce, data.encode(), None)
    print("Ciphertext: {}".format(a(ct)))

    with open(token_file, "w") as f:
        f.write(a(nonce) + "\n" + a(ct))
    os.system("chmod 600 {}".format(token_file))
    print("Wrote encrpyted OTP Token to file")
Beispiel #19
0
def create_token(plaintext, key):
    # decode key
    _key = base64.urlsafe_b64decode(key)

    # record time
    timestamp = time.time_ns().to_bytes(_ts_size, byteorder="big", signed=False)

    # generate nonce
    nonce = os.urandom(_nonce_size)

    # encrypt plaintext
    aesgcm = AESGCM(_key)
    ciphertext = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), timestamp)

    # concatenate token and base64url encode
    return base64.urlsafe_b64encode(timestamp + nonce + ciphertext)
Beispiel #20
0
    def write(self, data):
        logger.debug('CRAP: {} side transport.write() data of len {}'.format(self.mode, len(data)))

        aes_gcm = AESGCM(self.enc_key)

        logger.debug('CRAP: {} side Encrypting the data received from higher layer: {}\n'.format(self.mode, data))
        encrypted_data = aes_gcm.encrypt(self.self_IV, data, None)

        logger.debug('CRAP: {} side incrementing self_IV by one from {} to {}'.format(self.mode, self.self_IV, increment_large_binary(self.self_IV)))
        self.self_IV = increment_large_binary(self.self_IV)

        packet = DataPacket(data=encrypted_data)
        packet_bytes = packet.__serialize__()
        logger.debug('CRAP: {} side sending data packet. Info:\n'
                     'data: {}\n'.format(self.mode, packet.data))
        self.lowerTransport().write(packet_bytes)
Beispiel #21
0
    def __encrypt_string(self, data):
        report_metric(self.api_key)

        header_type = map_header_type(data)
        coerced_data = self.__coerce_type(data)
        iv = token_bytes(12)
        aesgcm = AESGCM(self.shared_key)

        encrypted_bytes = aesgcm.encrypt(iv, bytes(coerced_data, "utf8"), None)

        return self.__format(
            header_type,
            base64.b64encode(iv).decode("utf"),
            base64.b64encode(self.generated_ecdh_key).decode("utf"),
            base64.b64encode(encrypted_bytes).decode("utf"),
        )
Beispiel #22
0
def encrypt(input_filename, key):
    aesgcm = AESGCM(key)

    data = None
    encrypted_data = None

    with open(input_filename, 'rb') as fin:
        data = fin.read()  # Read the bytes of the input file

        nonce = os.urandom(12)
        auth = str(uuid.uuid4()).encode()

        encrypted_data = aesgcm.encrypt(nonce, data, auth)
        encrypted_data += b'NC:' + nonce + b'AUTH:' + auth

    return encrypted_data
 def encrypt(string: str, enc_key: str) -> bytes:
     """
     Args:
     :argument enc_key:
     :argument string:
     """
     # String to bytes
     enc_key = base64.b64decode(enc_key)
     # Create key
     aes_gcm = AESGCM(enc_key)
     # Create nonce
     nonce = create_nonce()
     # Create ciphered data
     data = string.encode()
     ct_ = aes_gcm.encrypt(nonce, data, None)
     return base64.b64encode(nonce + ct_)
Beispiel #24
0
class AESGCMKey(ContentEncryptionKey):
    """ """

    def __init__(self, params: Dict[int, Any]):
        """ """
        super().__init__(params)

        self._cipher: AESGCM

        # Validate alg.
        if self._alg == 1:  # A128GCM
            if not self._key:
                self._key = AESGCM.generate_key(bit_length=128)
            if len(self._key) != 16:
                raise ValueError("The length of A128GCM key should be 16 bytes.")
        elif self._alg == 2:  # A192GCM
            if not self._key:
                self._key = AESGCM.generate_key(bit_length=192)
            if len(self._key) != 24:
                raise ValueError("The length of A192GCM key should be 24 bytes.")
        elif self._alg == 3:  # A256GCM
            if not self._key:
                self._key = AESGCM.generate_key(bit_length=256)
            if len(self._key) != 32:
                raise ValueError("The length of A256GCM key should be 32 bytes.")
        else:
            raise ValueError(f"Unsupported or unknown alg(3) for AES GCM: {self._alg}.")

        self._cipher = AESGCM(self._key)
        return

    def generate_nonce(self):
        return token_bytes(_CWT_NONCE_SIZE_AESGCM)

    def encrypt(self, msg: bytes, nonce: bytes, aad: Optional[bytes] = None) -> bytes:
        """ """
        try:
            return self._cipher.encrypt(nonce, msg, aad)
        except Exception as err:
            raise EncodeError("Failed to encrypt.") from err

    def decrypt(self, msg: bytes, nonce: bytes, aad: Optional[bytes] = None) -> bytes:
        """ """
        try:
            return self._cipher.decrypt(nonce, msg, aad)
        except Exception as err:
            raise DecodeError("Failed to decrypt.") from err
Beispiel #25
0
def keyeststep9():
    received = ast.literal_eval(pkt1.smsg.actMsg)
    Session_AB = temp_known_users[addr]["Sab"]
    aesgcm = AESGCM(Session_AB)
    try:
        data = ast.literal_eval(
            aesgcm.decrypt(received["noncefordata"], received["enc_data"],
                           None))
        if int(data["newn2"]) == keyeststep7.N2 - 1:
            s_g = received["g"]
            s_p = received["p"]
            u1_pubkey = data["dhA"]
            u2_prikey = int(random.getrandbits(32))
            u2_pubkey = pow(s_g, u2_prikey, s_p)
            ssAB = pow(u1_pubkey, u2_prikey, s_p)
            # print "ssAB okay"
            # print ssAB

            backend = default_backend()
            salt = os.urandom(16)
            # derive
            kdf = Scrypt(salt=salt,
                         length=32,
                         n=2**14,
                         r=8,
                         p=1,
                         backend=backend)
            kAB = kdf.derive(bytes(ssAB))
            known_users[temp_known_users[addr]["name"]] = {
                "ssAB": kAB,
                "addr": addr
            }
            # print known_users
            nonceforu2pubkey = os.urandom(12)
            enc_u2pubkey = aesgcm.encrypt(nonceforu2pubkey, bytes(u2_pubkey),
                                          None)
            step10output = {
                "nonceforu2pubkey": nonceforu2pubkey,
                "enc_u2pubkey": enc_u2pubkey,
                "salt": salt
            }
            fillauthpacket(pkt1, "KEY_EST", 10, bytes(step10output))
            sendpacket(pkt1.SerializeToString(), addr[0], addr[1])
        else:
            print "Client's key invalid"
    except cryptography.exceptions.InvalidTag:
        print "Decrypt not okay"
def aesgcmEncrypt(input_file, key, salt, aad, output_file):
    print("AES-GCM ENCRYPTION")

    with open(input_file, 'rb') as f:
        data = f.read()
    print("creating aesgcm instance")
    aesgcm = AESGCM(key)
    print("generating nonce")
    nonce = os.urandom(12)
    print("encrypting using aesgcm")
    encrypted = aesgcm.encrypt(nonce, data, aad)
    print("adding salt and nonce")
    encrypted = salt + encrypted + nonce
    print("writing bytes")
    with open(output_file, 'wb') as f:
        f.write(encrypted)
    print("AES-GCM ENCRYPTION SUCCESSFUL")
Beispiel #27
0
 def test_vectors(self, vector):
     key = binascii.unhexlify(vector["key"])
     nonce = binascii.unhexlify(vector["iv"])
     aad = binascii.unhexlify(vector["aad"])
     ct = binascii.unhexlify(vector["ct"])
     pt = binascii.unhexlify(vector.get("pt", b""))
     tag = binascii.unhexlify(vector["tag"])
     aesgcm = AESGCM(key)
     if vector.get("fail") is True:
         with pytest.raises(InvalidTag):
             aesgcm.decrypt(nonce, ct + tag, aad)
     else:
         computed_ct = aesgcm.encrypt(nonce, pt, aad)
         assert computed_ct[:-16] == ct
         assert computed_ct[-16:] == tag
         computed_pt = aesgcm.decrypt(nonce, ct + tag, aad)
         assert computed_pt == pt
Beispiel #28
0
    def enc(self, byts, asscd=None):
        '''
        Encrypt the given bytes and return an envelope dict in msgpack form.

        Args:
            byts (bytes): The message to be encrypted.
            asscd (bytes): Extra data that needs to be authenticated (but not encrypted).

        Returns:
            bytes: The encrypted message. This is a msgpacked dictionary
            containing the IV, ciphertext, and associated data.
        '''
        iv = os.urandom(16)
        encryptor = AESGCM(self.ekey)
        byts = encryptor.encrypt(iv, byts, asscd)
        envl = {'iv': iv, 'data': byts, 'asscd': asscd}
        return s_msgpack.en(envl)
Beispiel #29
0
 def test_vectors(self, vector):
     key = binascii.unhexlify(vector["key"])
     nonce = binascii.unhexlify(vector["iv"])
     aad = binascii.unhexlify(vector["aad"])
     ct = binascii.unhexlify(vector["ct"])
     pt = binascii.unhexlify(vector.get("pt", b""))
     tag = binascii.unhexlify(vector["tag"])
     aesgcm = AESGCM(key)
     if vector.get("fail") is True:
         with pytest.raises(InvalidTag):
             aesgcm.decrypt(nonce, ct + tag, aad)
     else:
         computed_ct = aesgcm.encrypt(nonce, pt, aad)
         assert computed_ct[:-16] == ct
         assert computed_ct[-16:] == tag
         computed_pt = aesgcm.decrypt(nonce, ct + tag, aad)
         assert computed_pt == pt
 def _encrypt(self, plaintext: str) -> str:
     """
     Encrypt payload
     :oarans plaintext: plain string to encrypt
     :return: A string including salr, iv, and encrypted payload
     """
     aes = AESGCM(self.key)
     iv = os.urandom(16)
     plaintext = plaintext.encode("utf8")
     plaintext = lzma.compress(plaintext)
     ciphertext = aes.encrypt(iv, plaintext, None)
     logger.info(
         f'Size of encrypted secret payload : {sys.getsizeof(ciphertext)} bytes'
     )
     return "%s-%s-%s" % (hexlify(
         self.salt).decode("utf8"), hexlify(iv).decode("utf8"),
                          hexlify(ciphertext).decode("utf8"))
Beispiel #31
0
    def enc(self, byts, asscd=None):
        '''
        Encrypt the given bytes and return an envelope dict in msgpack form.

        Args:
            byts (bytes): The message to be encrypted.
            asscd (bytes): Extra data that needs to be authenticated (but not encrypted).

        Returns:
            bytes: The encrypted message. This is a msgpacked dictionary
            containing the IV, ciphertext, and associated data.
        '''
        iv = os.urandom(16)
        encryptor = AESGCM(self.ekey)
        byts = encryptor.encrypt(iv, byts, asscd)
        envl = {'iv': iv, 'data': byts, 'asscd': asscd}
        return s_msgpack.en(envl)
Beispiel #32
0
    def encryptParams(self, params, key):
        """
        :param params:
        :type params: list
        :param key:
        :type key: ECPublicKey
        :return:
        :rtype: list
        """
        keypair = Curve.generateKeyPair()
        encodedparams = self.urlencodeParams(params)

        cipher = AESGCM(Curve.calculateAgreement(key, keypair.privateKey))
        ciphertext = cipher.encrypt(b'\x00\x00\x00\x00' + struct.pack('>Q', 0), encodedparams.encode(), b'')

        payload = base64.b64encode(keypair.publicKey.serialize()[1:] + ciphertext)
        return [('ENC', payload)]
Beispiel #33
0
def get_retry_integrity_tag(packet_without_tag: bytes,
                            original_destination_cid: bytes) -> bytes:
    """
    Calculate the integrity tag for a RETRY packet.
    """
    # build Retry pseudo packet
    buf = Buffer(capacity=1 + len(original_destination_cid) +
                 len(packet_without_tag))
    buf.push_uint8(len(original_destination_cid))
    buf.push_bytes(original_destination_cid)
    buf.push_bytes(packet_without_tag)
    assert buf.eof()

    # run AES-128-GCM
    aead = AESGCM(RETRY_AEAD_KEY)
    integrity_tag = aead.encrypt(RETRY_AEAD_NONCE, b"", buf.data)
    assert len(integrity_tag) == RETRY_INTEGRITY_TAG_SIZE
    return integrity_tag
Beispiel #34
0
    def process(self, msg=b""):

        # Read Key and Nonce.
        file = open('keyAndNonce.key', 'rb')
        keyAndNonce = file.read()
        file.close()

        # Number of Message.
        self.msg_cnt += 1

        print('Input your message.')
        textInput = input().encode()

        # Encrypt Message to send to Server.
        aesgcm = AESGCM(keyAndNonce[:16])
        encryptMessage = aesgcm.encrypt(keyAndNonce[16:], textInput, None)

        return encryptMessage if len(encryptMessage) > 0 else None
Beispiel #35
0
def aes_gcm_encryption():
    data = "a secret message"
    aad = "authenticated but unencrypted data"
    data = data.encode()
    aad = aad.encode()

    key = AESGCM.generate_key(bit_length=128)
    write_bytes_to_file('key.key', key)
    aesgcm = AESGCM(key)
    iv = os.urandom(12)
    write_bytes_to_file('iv', iv)

    ct = aesgcm.encrypt(iv, data, aad)
    print(ct)
    print(type(ct))
    ct = ct.decode('ISO-8859-1')
    print(ct)
    dct = aesgcm.decrypt(iv, ct.encode('ISO-8859-1'), aad)
    print(dct.decode())
Beispiel #36
0
    def encryptParams(self, params, key):
        """
        :param params:
        :type params: list
        :param key:
        :type key: ECPublicKey
        :return:
        :rtype: list
        """
        keypair = Curve.generateKeyPair()
        encodedparams = self.urlencodeParams(params)

        cipher = AESGCM(Curve.calculateAgreement(key, keypair.privateKey))
        ciphertext = cipher.encrypt(b'\x00\x00\x00\x00' + struct.pack('>Q', 0),
                                    encodedparams.encode(), b'')

        payload = base64.b64encode(keypair.publicKey.serialize()[1:] +
                                   ciphertext)
        return [('ENC', payload)]
Beispiel #37
0
def aescc_func():
    try:
        print('ENCRYPTION')
        data = input("Secret Message :")
        aad = input("authenticated but unencrypted data :")
        key = AESGCM.generate_key(bit_length=128)
        aesgcm = AESGCM(key)
        nonce = os.urandom(12)
        ct = aesgcm.encrypt(nonce, data.encode(), aad.encode())
        ad = aesgcm.decrypt(nonce, ct, aad.encode())
        print("Encrypted :",
              str(ct)[2:-1], "\nKey:",
              str(key)[2:-1], "\nNonce :",
              str(nonce)[2:-1])

        print('\nDECRYPTION')
        print(str(ad)[2:-1])
    except:
        print("Wrong Value..!")
Beispiel #38
0
class AES_GCMEncrypter(Encrypter):
    def __init__(self, bit_length=0, key=None):
        Encrypter.__init__(self)
        if key:
            self.key = AESGCM(key)
        elif bit_length:
            if bit_length not in [128, 192, 256]:
                raise UnsupportedBitLength(bit_length)

            self.key = AESGCM(AESGCM.generate_key(bit_length=bit_length))
        else:
            raise ValueError("Need key or key bit length")

    def encrypt(self, msg, iv="", auth_data=None):
        """
        Encrypts and authenticates the data provided as well as authenticating
        the associated_data.

        :param msg: The message to be encrypted
        :param iv: MUST be present, at least 96-bit long
        :param auth_data: Associated data
        :return: The cipher text bytes with the 16 byte tag appended.
        """
        if not iv:
            raise ValueError("Missing Nonce")

        return self.key.encrypt(iv, msg, auth_data)

    def decrypt(self, cipher_text, iv="", auth_data=None, tag=b""):
        """
        Decrypts the data and authenticates the associated_data (if provided).

        :param cipher_text: The data to decrypt including tag
        :param iv: Initialization Vector
        :param auth_data: Associated data
        :param tag: Authentication tag
        :return: The original plaintext
        """
        if not iv:
            raise ValueError("Missing Nonce")

        return self.key.decrypt(iv, cipher_text + tag, auth_data)
def encrypt(input_file_names, key):
    #fernet = Fernet(key)
    aesgcm = AESGCM(key)

    i = 0
    l = len(input_file_names)
    printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=50)
    for input_file_name in input_file_names:
        i = i + 1
        if i % 4 == 0:
            printProgressBar(i,
                             l,
                             prefix='Progress:',
                             suffix='Complete',
                             length=50)

        with open(input_file_name[0] + os.sep + input_file_name[1],
                  'rb') as fin:
            data = fin.read()  # Read the bytes of the input file

            data += b'DIR:' + input_file_name[0].encode(
            ) + b'FILENAME:' + input_file_name[1].encode()

            nonce = os.urandom(12)
            auth = str(uuid.uuid4()).encode()

            encrypted_data = aesgcm.encrypt(nonce, data, auth)

            encrypted_data += b'NC:' + nonce + b'AUTH:' + auth

            # Generate random filename
            encrypted_file_name = "Encrypted" + os.sep + str(uuid.uuid4())
            while (os.path.exists(encrypted_file_name)
                   ):  # Chances for this happening are astronomically small
                encrypted_file_name = "Encrypted" + os.sep + str(uuid.uuid4())

            os.makedirs(os.path.dirname(encrypted_file_name), exist_ok=True)
            with open(encrypted_file_name, 'wb') as fout:
                fout.write(encrypted_data
                           )  # Write the encrypted bytes to the output file

    printProgressBar(l, l, prefix='Progress:', suffix='Complete', length=50)
    def encrypt(string: str, enc_key: str) -> bytes:
        """

        Args:
            enc_key (str):
            string (str):

        Returns:
            bytes:
        """
        # String to bytes
        enc_key = enc_key.encode()
        # Create key
        aes_gcm = AESGCM(enc_key)
        # Create nonce
        nonce = create_nonce()
        # Create ciphered data
        data = string.encode()
        ct = aes_gcm.encrypt(nonce, data, None)
        return base64.b64encode(nonce + ct)
Beispiel #41
0
 def test_invalid_nonce_length(self, backend):
     key = AESGCM.generate_key(128)
     aesgcm = AESGCM(key)
     with pytest.raises(ValueError):
         aesgcm.encrypt(b"", b"hi", None)