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
Beispiel #2
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 #3
0
    def unpack_request(self, packet):
        # pylint: disable=too-many-locals
        """Unpack an incoming request

        :param packet: Incoming packet to unpack
        :type packet: bytes

        :raises PSSSTUnsupportedCipher: cipher suite indicated in packet is not supported.
        :raises PSSSTNotRequest: packet is not a request packet.
        :raises PSSSTDecryptFailed: payload did not decrypt to valid and authentic data
        :raises PSSSTClientAuthFailed: client auth was present but did not match request
        :returns: tuple of unpacked data, authenticated client public key and reply handler

        """
        hdr = Header.from_packet(packet[:4])
        if hdr.reply:
            raise PSSSTNotRequest()
        if hdr.cipher_suite != self._suite:
            raise PSSSTUnsupportedCipher()
        dh_bytes = packet[4:36]
        exchange_dh = X25519PublicKey.from_public_bytes(dh_bytes)
        shared_secret = self._server_private.exchange(exchange_dh)

        key, nonce_client, nonce_server = _DKF_SHA256(dh_bytes, shared_secret)

        cipher = AESGCM(key)

        try:
            plaintext = cipher.decrypt(nonce_client, packet[36:], packet[:4])
        except InvalidTag as err:
            raise PSSSTDecryptFailed() from err

        if hdr.client_auth:
            client_public_key = X25519PublicKey.from_public_bytes(
                plaintext[:32])
            temp_privte_key = X25519PrivateKey.from_private_bytes(
                plaintext[32:64])
            auth_dh = temp_privte_key.exchange(client_public_key)
            if auth_dh != exchange_dh.public_bytes(encoding=Encoding.Raw,
                                                   format=PublicFormat.Raw):
                raise PSSSTClientAuthFailed()
            plaintext = plaintext[64:]
        else:
            client_public_key = None

        reply_handler = _ServerReplyHandler(packet[4:36], hdr.client_auth,
                                            hdr.cipher_suite, cipher,
                                            nonce_server)

        return (plaintext, client_public_key, reply_handler)
Beispiel #4
0
    def decrypt_data(cls, priv_key_filename, enc_data, output_filename):
        with open(priv_key_filename,
                  "rb") as priv_key, open(output_filename,
                                          "wb") as output_file:

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

            nonce = enc_data[:cls.NONCE_SIZE]
            data = enc_data[cls.NONCE_SIZE:]  # noqa: E203

            aad = b""
            dec_data = cipher.decrypt(nonce, data, aad)
            output_file.write(dec_data)
def Algo3(filename, key, nonce, fname):
	aad = "authenticated but unencrypted data"
	aesgcm = AESGCM(key)
	source_filename = 'files/' + filename
	target_filename = './encrypted/' + fname + '/files/' + filename
	file = open(source_filename,'rb')
	target_file = open(target_filename,'wb')
	raw = ""
	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 #6
0
def decrypt(passphrase: str, ciphertext: str) -> str:
    """decrypts ciphertext data using the user supplied passphrase and the salt and iv."""
    try:
        salt, initialization_vector, ciphertext = map(unhexlify, ciphertext.split("-"))
        key, _ = derive_key(passphrase, salt)
        aes = AESGCM(key)
        plaintext = aes.decrypt(initialization_vector, ciphertext, None)
        print('=================================================================================')
        print('Decrypted:')
        print(plaintext.decode("utf8"))
        print('=================================================================================')
    except:
        print(sys.exc_info())
        print('Decryption failed, wrong key or wrong bytes?')
Beispiel #7
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)
Beispiel #8
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 #9
0
def decrypt_message(data_packet, hex_key, node_id):
    retval = None
    log.debug("decrypting for node " + node_id)
    log.debug("aesgcm:eMFEP2:data_packet:pp (len) (" + str(len(data_packet)) +
              ") ")
    log.debug(prettyprint(data_packet))

    # key is from the csv file, 128 bits
    # aad is additional data, from (length, type, seqlen, 4xID bytes, bodyLength)
    # iv is initialisation vector, from
    # ciphertext is from packet
    # tag is from
    # data_packet is a handful of byte
    if data_packet[len(data_packet) - 1] == 0x80:
        log.debug("aesgcm encryption used")

        # packet contains the entire packet, except for the leading length byte
        # indices are reference as per normal Python from 0 - hence the frame type (cf) is at index 0

        log.debug("initialisation vector...")
        iv = initialisation_vector(data_packet, node_id)
        log.debug("cipher text...")
        ct = cipher_text(data_packet)
        log.debug("tag...")
        tg = tag(data_packet)
        log.debug("additional data...")
        ad = additional_data(data_packet)
        key = hex_string_to_bytes(hex_key)
        log.debug("preparation complete")
        debug_array = [iv, ct, tg, ad, key]
        log.debug("len | pp:iv,ct,tg,ad,key")
        [
            log.debug("{:>2} | {}".format(repr(len(x)), prettyprint(x)))
            for x in debug_array
        ]

        log.debug("attempting decryption...")
        try:
            buf = ct + tg  # aesgcm.decrypt takes a buffer with the tag appended to the ciphertext.
            aesgcm = AESGCM(
                key)  # (DE20170807) Shiny new interface in cryptography v2.x
            retval = aesgcm.decrypt(iv, buf, ad)
            log.debug("decrypted")

        except Exception as e:
            log.error('decryption failed with exception: {}: {}'.format(
                e.__class__.__name__, e))

    return retval
Beispiel #10
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 #11
0
def aesgcm_decrypt(key: AES128Key,
                   nonce: Nonce,
                   cipher_text: bytes,
                   authenticated_data: bytes
                   ) -> bytes:
    validate_aes128_key(key)
    validate_nonce(nonce)

    aesgcm = AESGCM(key)
    try:
        plain_text = aesgcm.decrypt(nonce, cipher_text, authenticated_data)
    except InvalidTag as error:
        raise DecryptionError() from error
    else:
        return plain_text
def Decrypt(key, encryptedMessageBytes):
    NonceLength = 12
    TagLength = 16

    nonce = encryptedMessageBytes[:NonceLength]
    tag = encryptedMessageBytes[NonceLength:NonceLength + TagLength]
    ciphertext = encryptedMessageBytes[NonceLength + TagLength:]

    try:
        aesgcm = AESGCM(key)
        m = aesgcm.decrypt(nonce, ciphertext + tag, None)
    except Exception as e:
        return None, str(e)

    return m, None
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 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 #15
0
def decrypt_token(context):
    token_file = os.path.join(base_dir, context)
    with open(token_file, "r") as f:
        f = f.read()
    nonce, ciphertext = f.splitlines()
    #print(nonce, ciphertext)
    key = hashlib.sha256(getpass.getpass().encode()).digest()
    aesgcm = AESGCM(key)
    try:
        token = aesgcm.decrypt(b(nonce), b(ciphertext), None).decode()
        #print("Decrypted: {}".format(token))
    except cryptography.exceptions.InvalidTag:
        print("wrong password")
        exit()
    return token
Beispiel #16
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 #17
0
def logoutack():
    if pkt1.smsg.stepNumber == 2:
        packet = ast.literal_eval(pkt1.smsg.actMsg)
        nonce = packet["nonce"]
        ct = packet["ct"]
        aesgcm = AESGCM(temp["sk"])
        try:
            newNl = long(aesgcm.decrypt(nonce, ct, None))
            if newNl == logout.Nl + 1:
                return 1
            else:
                print "Someone else wants to log you out!"
                return 0
        except cryptography.exceptions.InvalidTag:
            print "Decrypt not okay"
Beispiel #18
0
def aes_gcm_encryption():
    did = '1'
    dtype = 'TemperatureSensor'
    aad = "authenticated but unencrypted data"
    # key = AESGCM.generate_key(bit_length=128)
    # iv = os.urandom(12)
    key = read_data_from_file("/home/shihab/Desktop", 'key.key')
    iv = read_data_from_file("/home/shihab/Desktop", 'iv')
    aesgcm = AESGCM(key)
    devId = aesgcm.encrypt(iv, did.encode(), aad.encode())
    devType = aesgcm.encrypt(iv, dtype.encode(), aad.encode())
    data = aesgcm.encrypt(iv, str(round(random.uniform(25.0, 30.0), 2)).encode(), aad.encode())
    d = {'deviceId': devId.decode('ISO-8859-1'), 'deviceType': devType.decode('ISO-8859-1'),
         'data': {'temp': data.decode('ISO-8859-1')}}
    return d
Beispiel #19
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 #20
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 #21
0
    def _decrypt_payload(self, payload):
        payload = copy.deepcopy(payload)

        fields = payload.pop("encryption", None)
        if fields is None:
            raise KeyError("Missing encryption fields from response")

        scheme = fields["encryptionScheme"]
        if scheme != self.ENCRYPTION_SCHEME:
            raise ValueError(f"Unexpected encryption scheme: {scheme}")

        aes_enc = base64.b64decode(fields["encryptedAES"])
        aes_tag = base64.b64decode(fields["authTag"])
        aes_iv = base64.b64decode(fields["iv"])

        # Decrypt AES key using our private key
        aes_key = self._private_key.decrypt(
            aes_enc,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None,
            ),
        )

        # Decrypt actual value using decrypted AES key
        ciphertext = base64.b64decode(payload.pop("value")) + aes_tag
        data = AESGCM(aes_key).decrypt(binascii.hexlify(aes_iv), ciphertext,
                                       b"")
        payload["values"] = json.loads(data)

        return payload
Beispiel #22
0
def encrypter():
    tools.empty_folder('key')
    tools.empty_folder('encrypted')
    key_1 = Fernet.generate_key()
    key_1_1 = Fernet.generate_key()
    key_1_2 = Fernet.generate_key()
    key_2 = ChaCha20Poly1305.generate_key()
    key_3 = AESGCM.generate_key(bit_length=128)
    key_4 = AESCCM.generate_key(bit_length=128)
    nonce13 = os.urandom(13)
    nonce12 = os.urandom(12)
    files = sorted(tools.list_dir('files'))
    for index in range(0, len(files)):
        if index % 4 == 0:
            Algo1_extented(files[index], key_1_1, key_1_2)
        elif index % 4 == 1:
            Algo2(files[index], key_2, nonce12)
        elif index % 4 == 2:
            Algo3(files[index], key_3, nonce12)
        else:
            Algo4(files[index], key_4, nonce13)
    secret_information = (key_1_1) + ":::::" + (key_1_2) + ":::::" + (
        key_2) + ":::::" + (key_3) + ":::::" + (key_4) + ":::::" + (
            nonce12) + ":::::" + (nonce13)
    Algo1(secret_information, key_1)
    public_key = open("./key/Taale_Ki_Chabhi.pem", "wb")
    public_key.write(key_1)
    public_key.close()
    tools.empty_folder('files')
Beispiel #23
0
def finish_desktop_flow(request: HttpRequest, user_profile: UserProfile,
                        otp: str) -> HttpResponse:
    """
    The desktop otp flow returns to the app (through the clipboard)
    a token that allows obtaining (through log_into_subdomain) a logged in session
    for the user account we authenticated in this flow.
    The token can only be used once and within ExternalAuthResult.LOGIN_KEY_EXPIRATION_SECONDS
    of being created, as nothing more powerful is needed for the desktop flow
    and this ensures the key can only be used for completing this authentication attempt.
    """
    result = ExternalAuthResult(user_profile=user_profile)
    token = result.store_data()
    key = bytes.fromhex(otp)
    iv = os.urandom(12)
    desktop_data = (iv + AESGCM(key).encrypt(iv, token.encode(), b"")).hex()
    context = {
        'desktop_data':
        desktop_data,
        'browser_url':
        reverse('zerver.views.auth.login_page',
                kwargs={'template_name': 'zerver/login.html'}),
        'realm_icon_url':
        realm_icon_url(user_profile.realm)
    }
    return render(request, 'zerver/desktop_redirect.html', context=context)
Beispiel #24
0
 def data_received_duplex(self, packet):
     print("data_received_duplex")
     #self.key_iv()
     data = AESGCM(self.dec).decrypt(self.peer_iv, packet.data, None)       
     self.peer_iv = self.increIv(self.peer_iv)
     self.higherProtocol().data_received(data)
     print("crap received and decrypted data")
Beispiel #25
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
Beispiel #26
0
    def authenticated_as(self, cookie=None, authorization="", **kwargs):
        """

        :param cookie: A HTTP Cookie
        :param authorization: The HTTP Authorization header
        :param kwargs: extra key word arguments
        :return:
        """
        (encmsg, iv) = base64.b64decode(authorization).split(":")
        try:
            aesgcm = AESGCM(self.symkey)
            user = aesgcm.decrypt(iv, encmsg, None)
        except (AssertionError, KeyError):
            raise FailedAuthentication("Decryption failed")

        return {"uid": user}, time.time()
 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 #28
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 #29
0
def aesgcm_pbkdf2_cryptor(pw, salt=None, params=_pbkdf2_params):
    if salt is None:
        salt = settings.SECRET_KEY
    salt = force_bytes(salt)

    return AESGCM(
        pbkdf2_hmac(password=pw[:128].encode("utf-8"), salt=salt, **params))
    def _generate_key(self):
        full_file_path = os.path.join(self.credentials_dir, self._key_filename)

        if os.path.exists(full_file_path):
            key, nonce = self._get_key()
            return full_file_path, key, nonce

        key = AESGCM.generate_key(128)
        nonce = secrets.token_hex(12)
        with open(full_file_path, 'w') as f:
            f.write(f'{key.hex()}.{nonce}')

        self.key = AESGCM(key)
        self.nonce = bytes.fromhex(nonce)

        self._ignore_key(full_file_path)
Beispiel #31
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 #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 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 #34
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 #35
0
def decrypt_message(data_packet, hex_key, node_id):
    retval = None
    log.debug("decrypting for node " + node_id)
    log.debug("aesgcm:eMFEP2:data_packet:pp (len) (" + str(len(data_packet)) + ") ")
    log.debug(prettyprint(data_packet))

    # key is from the csv file, 128 bits
    # aad is additional data, from (length, type, seqlen, 4xID bytes, bodyLength)
    # iv is initialisation vector, from
    # ciphertext is from packet
    # tag is from
    # data_packet is a handful of byte
    if data_packet[len(data_packet) - 1] == 0x80:
        log.debug("aesgcm encryption used")

        # packet contains the entire packet, except for the leading length byte
        # indices are reference as per normal Python from 0 - hence the frame type (cf) is at index 0

        log.debug("initialisation vector...")
        iv = initialisation_vector(data_packet, node_id)
        log.debug("cipher text...")
        ct = cipher_text(data_packet)
        log.debug("tag...")
        tg = tag(data_packet)
        log.debug("additional data...")
        ad = additional_data(data_packet)
        key = hex_string_to_bytes(hex_key)
        log.debug("preparation complete")
        debug_array = [iv, ct, tg, ad, key]
        log.debug("len | pp:iv,ct,tg,ad,key")
        [log.debug("{:>2} | {}".format(repr(len(x)), prettyprint(x))) for x in debug_array]

        log.debug("attempting decryption...")
        try:
            buf = ct + tg  # aesgcm.decrypt takes a buffer with the tag appended to the ciphertext.
            aesgcm = AESGCM(key)  # (DE20170807) Shiny new interface in cryptography v2.x
            retval = aesgcm.decrypt(iv, buf, ad)
            log.debug("decrypted")

        except Exception as e:
            log.error('decryption failed with exception: {}: {}'.format(e.__class__.__name__, e))

    return retval
    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)
def decrypt_opaque(opaque, nonce, tag,
                   hash_mask, auth_headers, extra_auth_headers):
    aesgcm = AESGCM(SECRET_KEY)
    
    auth_data = '|'.join((hash_mask, auth_headers, extra_auth_headers))

    try:
        plaintext = aesgcm.decrypt(nonce, opaque + tag, auth_data)
    except InvalidTag:
        raise OpaqueInvalid(
            "Opaque token from the client failed to authenticate")

    try:
        sessionid, remainder = plaintext.split('|', 1)
        hmac_key, expiration_time = (remainder[:16], remainder[17:])
    except ValueError:
        raise OpaqueInvalid(
            "Plaintext from opaque token didn't have required fields")

    return sessionid, hmac_key, int(expiration_time)
Beispiel #38
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 #39
0
    def dec(self, byts):
        '''
        Decode an envelope dict and decrypt the given bytes.

        Args:
            byts (bytes): Bytes to decrypt.

        Returns:
            bytes: Decrypted message.
        '''
        envl = s_msgpack.un(byts)
        iv = envl.get('iv', b'')
        asscd = envl.get('asscd', b'')
        data = envl.get('data', b'')

        decryptor = AESGCM(self.ekey)

        try:
            data = decryptor.decrypt(iv, data, asscd)
        except Exception:
            logger.exception('Error decrypting data')
            return None
        return data
Beispiel #40
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 #41
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 #42
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 #43
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 #44
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)
Beispiel #45
0
    def test_bad_generate_key(self, backend):
        with pytest.raises(TypeError):
            AESGCM.generate_key(object())

        with pytest.raises(ValueError):
            AESGCM.generate_key(129)