コード例 #1
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises MacMismatchError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called" " when encrypting a message")
        self._next = [self.verify]

        if not self._mac_tag:
            tag = bchr(0) * self.block_size
            for i in xrange(3):
                tag = strxor(tag, self._omac[i].digest())
            self._mac_tag = tag[: self._mac_len]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #2
0
    def verify(self, received_mac_tag):
        """Validate the *binary* authentication tag (MAC).

        The receiver invokes this method at the very end, to
        check if the associated data (if any) and the decrypted
        messages are valid.

        :param bytes/bytearray/memoryview received_mac_tag:
            This is the 16-byte *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = (self.verify,)

        secret = get_random_bytes(16)

        self._compute_mac()

        mac1 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #3
0
def _create_cbc_cipher(factory, **kwargs):
    """Instantiate a cipher object that performs CBC encryption/decryption.

    :Parameters:
      factory : module
        The underlying block cipher, a module from ``Cryptodome.Cipher``.

    :Keywords:
      iv : byte string
        The IV to use for CBC.

      IV : byte string
        Alias for ``iv``.

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    cipher_state = factory._create_base_cipher(kwargs)
    iv = kwargs.pop("IV", None)
    IV = kwargs.pop("iv", None)

    if (None, None) == (iv, IV):
        iv = get_random_bytes(factory.block_size)
    if iv is not None:
        if IV is not None:
            raise TypeError("You must either use 'iv' or 'IV', not both")
    else:
        iv = IV

    if kwargs:
        raise TypeError("Unknown parameters for CBC: %s" % str(kwargs))

    return CbcMode(cipher_state, iv)
コード例 #4
0
def _create_eax_cipher(factory, **kwargs):
    """Create a new block cipher, configured in EAX mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Cryptodome.Cipher` (like
        `Cryptodome.Cipher.AES`).

    :Keywords:
      key : byte string
        The secret key to use in the symmetric cipher.

      nonce : byte string
        A value that must never be reused for any other encryption.
        There are no restrictions on its length, but it is recommended to use
        at least 16 bytes.

        The nonce shall never repeat for two different messages encrypted with
        the same key, but it does not need to be random.

        If not specified, a 16 byte long random string is used.

      mac_len : integer
        Length of the MAC, in bytes. It must be no larger than the cipher
        block bytes (which is the default).
    """

    try:
        key = kwargs.pop("key")
        nonce = kwargs.pop("nonce", None)
        if nonce is None:
            nonce = get_random_bytes(16)
        mac_len = kwargs.pop("mac_len", factory.block_size)
    except KeyError, e:
        raise TypeError("Missing parameter: " + str(e))
コード例 #5
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        Call this method after the final `decrypt` (the one with no arguments)
        to check if the message is authentic and valid.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called now for this cipher")

        assert(len(self._cache_P) == 0)

        self._next = [self.verify]

        if self._mac_tag is None:
            self._compute_mac_tag()

        secret = get_random_bytes(16)
        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #6
0
def _create_openpgp_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OpenPGP mode.

    :Parameters:
      factory : module
        The module.

    :Keywords:
      key : byte string
        The secret key to use in the symmetric cipher.

      IV : byte string
        The initialization vector to use for encryption or decryption.

        For encryption, the IV must be as long as the cipher block size.

        For decryption, it must be 2 bytes longer (it is actually the
        *encrypted* IV which was prefixed to the ciphertext).
    """

    iv = kwargs.pop("IV", None)
    IV = kwargs.pop("iv", None)

    if (None, None) == (iv, IV):
        iv = get_random_bytes(factory.block_size)
    if iv is not None:
        if IV is not None:
            raise TypeError("You must either use 'iv' or 'IV', not both")
    else:
        iv = IV

    try:
        key = kwargs.pop("key")
    except KeyError, e:
        raise TypeError("Missing component: " + str(e))
コード例 #7
0
def _create_ocb_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OCB mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Cryptodome.Cipher`
        (like `Cryptodome.Cipher.AES`).

    :Keywords:
      nonce : byte string
        A  value that must never be reused for any other encryption.
        Its length can vary from 1 to 15 bytes.
        If not specified, a random 15 bytes long nonce is generated.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be in the range ``[8..16]``.
        The default is 16 (128 bits).

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    try:
        nonce = kwargs.pop("nonce", None)
        if nonce is None:
            nonce = get_random_bytes(15)
        mac_len = kwargs.pop("mac_len", 16)
    except KeyError, e:
        raise TypeError("Keyword missing: " + str(e))
コード例 #8
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : bytes/bytearray/memoryview
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = [self.verify]

        self._digest()
        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #9
0
def encryptDataWithPubKey(data, pubKeyFile=RSA_pubKeyFile, outFile=None):
    from Cryptodome.PublicKey   import RSA
    from Cryptodome.Random      import get_random_bytes
    from Cryptodome.Cipher      import AES, PKCS1_OAEP


    recipient_key   = RSA.import_key(open(pubKeyFile).read())
    session_key     = get_random_bytes(16)

        # Encrypt the session key with the public RSA key
    cipher_rsa      = PKCS1_OAEP.new(recipient_key)


        # Encrypt the data with the AES session key
    cipher_aes = AES.new(session_key, AES.MODE_EAX)
    ciphertext, tag = cipher_aes.encrypt_and_digest(data)
    print ()
    print (ciphertext)
    print ()
    print (tag)
    print ()
    if outFile:
        file_out = open(outFile, "wb")
        file_out.write(cipher_rsa.encrypt(session_key))
        [ file_out.write(x) for x in (ciphertext.nonce, tag, ciphertext) ]
コード例 #10
0
ファイル: ChaCha20.py プロジェクト: chevah/python-package
def new(**kwargs):
    """Create a new ChaCha20 cipher

    :keyword key: The secret key to use. It must be 32 bytes long.
    :type key: byte string

    :keyword nonce:
        A mandatory value that must never be reused for any other encryption
        done with this key. It must be 8 or 12 bytes long.

        If not provided, a random 8-byte string will be generated
        (you can read it back via the ``nonce`` attribute of the returned object).
    :type nonce: bytes, bytearray, memoryview

    :Return: a :class:`Cryptodome.Cipher.ChaCha20.ChaCha20Cipher` object
    """

    try:
        key = kwargs.pop("key")
    except KeyError as e:
        raise TypeError("Missing parameter %s" % e)

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(8)

    if len(key) != 32:
        raise ValueError("ChaCha20 key must be 32 bytes long")
    if len(nonce) not in (8, 12):
        raise ValueError("ChaCha20 nonce must be 8 or 12 bytes long")

    if kwargs:
        raise TypeError("Unknown parameters: " + str(kwargs))

    return ChaCha20Cipher(key, nonce)
コード例 #11
0
ファイル: Poly1305.py プロジェクト: 2216288075/meiduo_project
    def verify(self, mac_tag):

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #12
0
def _create_gcm_cipher(factory, **kwargs):
    """Create a new block cipher, configured in Galois Counter Mode (GCM).

    :Parameters:
      factory : module
        A block cipher module, taken from `Cryptodome.Cipher`.
        The cipher must have block length of 16 bytes.
        GCM has been only defined for `Cryptodome.Cipher.AES`.

    :Keywords:
      key : bytes/bytearray/memoryview
        The secret key to use in the symmetric cipher.
        It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
        or 32 (e.g. *AES-256*) bytes long.

      nonce : bytes/bytearray/memoryview
        A value that must never be reused for any other encryption.

        There are no restrictions on its length,
        but it is recommended to use at least 16 bytes.

        The nonce shall never repeat for two
        different messages encrypted with the same key,
        but it does not need to be random.

        If not provided, a 16 byte nonce will be randomly created.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be no larger than 16 bytes (which is the default).
    """

    try:
        key = kwargs.pop("key")
    except KeyError as e:
        raise TypeError("Missing parameter:" + str(e))

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(16)
    mac_len = kwargs.pop("mac_len", 16)

    # Not documented - only used for testing
    use_clmul = kwargs.pop("use_clmul", True)
    if use_clmul and _ghash_clmul:
        ghash_c = _ghash_clmul
    else:
        ghash_c = _ghash_portable

    return GcmMode(factory, key, nonce, mac_len, kwargs, ghash_c)
コード例 #13
0
def _create_ccm_cipher(factory, **kwargs):
    """Create a new block cipher, configured in CCM mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Cryptodome.Cipher` (like
        `Cryptodome.Cipher.AES`).

    :Keywords:
      key : bytes/bytearray/memoryview
        The secret key to use in the symmetric cipher.

      nonce : bytes/bytearray/memoryview
        A value that must never be reused for any other encryption.

        Its length must be in the range ``[7..13]``.
        11 or 12 bytes are reasonable values in general. Bear in
        mind that with CCM there is a trade-off between nonce length and
        maximum message size.

        If not specified, a 11 byte long random string is used.

      mac_len : integer
        Length of the MAC, in bytes. It must be even and in
        the range ``[4..16]``. The default is 16.

      msg_len : integer
        Length of the message to (de)cipher.
        If not specified, ``encrypt`` or ``decrypt`` may only be called once.

      assoc_len : integer
        Length of the associated data.
        If not specified, all data is internally buffered.
    """

    try:
        key = key = kwargs.pop("key")
    except KeyError as e:
        raise TypeError("Missing parameter: " + str(e))

    nonce = kwargs.pop("nonce", None)  # N
    if nonce is None:
        nonce = get_random_bytes(11)
    mac_len = kwargs.pop("mac_len", factory.block_size)
    msg_len = kwargs.pop("msg_len", None)      # p
    assoc_len = kwargs.pop("assoc_len", None)  # a
    cipher_params = dict(kwargs)

    return CcmMode(factory, key, nonce, mac_len, msg_len,
                   assoc_len, cipher_params)
コード例 #14
0
ファイル: utils.py プロジェクト: nuxeo/nuxeo-drive
def encrypt(
    plaintext: Union[bytes, str], secret: Union[bytes, str], lazy: bool = True
) -> bytes:
    """ Symetric encryption using AES. """

    import base64
    from Cryptodome.Random import get_random_bytes
    from Cryptodome.Cipher import AES

    plaintext = force_encode(plaintext)
    secret = force_encode(secret)
    secret = _lazysecret(secret) if lazy else secret
    iv = get_random_bytes(AES.block_size)
    encobj = AES.new(secret, AES.MODE_CFB, iv)
    return base64.b64encode(iv + encobj.encrypt(plaintext))
コード例 #15
0
ファイル: AES.py プロジェクト: 2216288075/meiduo_project
def _derive_Poly1305_key_pair(key, nonce):
    """Derive a tuple (r, s, nonce) for a Poly1305 MAC.
    
    If nonce is ``None``, a new 16-byte nonce is generated.
    """

    if len(key) != 32:
        raise ValueError("Poly1305 with AES requires a 32-byte key")

    if nonce is None:
        nonce = get_random_bytes(16)
    elif len(nonce) != 16:
        raise ValueError("Poly1305 with AES requires a 16-byte nonce")

    s = new(key[:16], MODE_ECB).encrypt(nonce)
    return key[16:], s, nonce
コード例 #16
0
ファイル: _mode_cfb.py プロジェクト: chevah/python-package
def _create_cfb_cipher(factory, **kwargs):
    """Instantiate a cipher object that performs CFB encryption/decryption.

    :Parameters:
      factory : module
        The underlying block cipher, a module from ``Cryptodome.Cipher``.

    :Keywords:
      iv : bytes/bytearray/memoryview
        The IV to use for CFB.

      IV : bytes/bytearray/memoryview
        Alias for ``iv``.

      segment_size : integer
        The number of bit the plaintext and ciphertext are segmented in.
        If not present, the default is 8.

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    cipher_state = factory._create_base_cipher(kwargs)

    iv = kwargs.pop("IV", None)
    IV = kwargs.pop("iv", None)

    if (None, None) == (iv, IV):
        iv = get_random_bytes(factory.block_size)
    if iv is not None:
        if IV is not None:
            raise TypeError("You must either use 'iv' or 'IV', not both")
    else:
        iv = IV

    if len(iv) != factory.block_size:
        raise ValueError("Incorrect IV length (it must be %d bytes long)" %
                factory.block_size)

    segment_size_bytes, rem = divmod(kwargs.pop("segment_size", 8), 8)
    if segment_size_bytes == 0 or rem != 0:
        raise ValueError("'segment_size' must be positive and multiple of 8 bits")

    if kwargs:
        raise TypeError("Unknown parameters for CFB: %s" % str(kwargs))
    return CfbMode(cipher_state, iv, segment_size_bytes)
コード例 #17
0
    def verify(self, mac_tag):
        """Verify that a given **binary** MAC (computed by another party)
        is valid.

        :Parameters:
          mac_tag : byte string
            The expected MAC of the message.
        :Raises ValueError:
            if the MAC does not match. It means that the message
            has been tampered with or that the MAC key is incorrect.
        """

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #18
0
ファイル: BLAKE2b.py プロジェクト: 2216288075/meiduo_project
    def verify(self, mac_tag):
        """Verify that a given **binary** MAC (computed by another party)
        is valid.

        Args:
          mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.

        Raises:
            ValueError: if the MAC does not match. It means that the message
                has been tampered with or that the MAC key is incorrect.
        """

        secret = get_random_bytes(16)

        mac1 = new(digest_bits=160, key=secret, data=mac_tag)
        mac2 = new(digest_bits=160, key=secret, data=self.digest())

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
コード例 #19
0
def new(**kwargs):
    """Create a new ChaCha20-Poly1305 AEAD cipher.

    :keyword key: The secret key to use. It must be 32 bytes long.
    :type key: byte string

    :keyword nonce:
        A value that must never be reused for any other encryption
        done with this key. It must be 8 or 12 bytes long.

        If not provided, 12 ``bytes`` will be generated randomly
        (you can find them back in the ``nonce`` attribute).
    :type nonce: bytes, bytearray, memoryview

    :Return: a :class:`Cryptodome.Cipher.ChaCha20.ChaCha20Poly1305Cipher` object
    """

    try:
        key = kwargs.pop("key")
    except KeyError as e:
        raise TypeError("Missing parameter %s" % e)

        self._len_ct += len(plaintext)
    
    if len(key) != 32:
        raise ValueError("Key must be 32 bytes long")

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(12)

    if len(nonce) not in (8, 12):
        raise ValueError("Nonce must be 8 or 12 bytes long")

    if not is_buffer(nonce):
        raise TypeError("nonce must be bytes, bytearray or memoryview")

    if kwargs:
        raise TypeError("Unknown parameters: " + str(kwargs))

    return ChaCha20Poly1305Cipher(key, nonce)
コード例 #20
0
ファイル: Salsa20.py プロジェクト: 2216288075/meiduo_project
def new(key, nonce=None):
    """Create a new Salsa20 cipher

    :keyword key: The secret key to use. It must be 16 or 32 bytes long.
    :type key: bytes/bytearray/memoryview

    :keyword nonce:
        A value that must never be reused for any other encryption
        done with this key. It must be 8 bytes long.

        If not provided, a random byte string will be generated (you can read
        it back via the ``nonce`` attribute of the returned object).
    :type nonce: bytes/bytearray/memoryview

    :Return: a :class:`Cryptodome.Cipher.Salsa20.Salsa20Cipher` object
    """

    if nonce is None:
        nonce = get_random_bytes(8)

    return Salsa20Cipher(key, nonce)
コード例 #21
0
    def encrypt(self, data, esn, sequence_number):
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        iv = get_random_bytes(16)
        encryption_envelope = {
                'ciphertext': '',
                'keyid': esn + '_' + str(sequence_number),
                'sha256': 'AA==',
                'iv': base64.standard_b64encode(iv)
        }
        # Padd the plaintext
        plaintext = Padding.pad(data, 16)
        # Encrypt the text
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv)
        citext = cipher.encrypt(plaintext)
        encryption_envelope['ciphertext'] = base64.standard_b64encode(citext)

        return encryption_envelope;
コード例 #22
0
def new(key, nonce=None):
    """Create a new Salsa20 cipher

    :Parameters:
      key : byte string
        The secret key to use in the symmetric cipher.
        It must be 16 or 32 bytes long.

      nonce : byte string
        A value that must never be reused for any other encryption.
        It must be 8 bytes long.

        If not provided, a random byte string will be generated (you can
        read it back via the ``nonce`` attribute).

    :Return: an `Salsa20Cipher` object
    """

    if nonce is None:
        nonce = get_random_bytes(8)

    return Salsa20Cipher(key, nonce)
コード例 #23
0
from getpass import getpass
from Cryptodome.Random import get_random_bytes
from Cryptodome.Protocol.KDF import scrypt
from Cryptodome.Cipher import AES
import os
import datetime
import shutil
import argparse
from sys import exit

#salt = b'\xbc\'\xf2\xff\x9d\xa1"\x0f\x7f?tUZ\xcb\xe0(\xe1\x8d\x08\x9e\x8a\xa0\x1du\xbf\xf3t\x9c\x05n\x9f\xd6'
status = False
salt = get_random_bytes(32)  # Generate salt
BUFFER_SIZE = 64 * 1024


def get_out_filepath(filepath):
    if os.path.exists(filepath + '.aes'):
        suffix = datetime.datetime.now().strftime("%d%m%y_%H%M%S")
        out_filepath = filepath + suffix + '.aes'
        return out_filepath
    else:
        return filepath + '.aes'


def get_decrypted_filepath(filepath):
    out_filepath = os.path.splitext(filepath)[0]
    if os.path.splitext(filepath)[1] == '.aes':
        if os.path.exists(out_filepath):
            suffix = datetime.datetime.now().strftime("%d%m%y_%H%M%S")
            out_filepath += suffix
コード例 #24
0
import socket
from Cryptodome.Cipher import AES, PKCS1_OAEP
from Cryptodome.Util.Padding import pad, unpad
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA
from Cryptodome.Hash import HMAC, SHA256
from Cryptodome.Signature import pkcs1_15

portNum = 8000
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(('127.0.0.1', portNum))
serv.listen(5)

#Generate shared key for HMAC
HMAC_key_file = open("HMAC_key_file.bin", "wb")
HMAC_key = get_random_bytes(16)
HMAC_key_file.write(HMAC_key)
HMAC_key_file.close()

# Generate RSA public key and place in key file.
RSA_key = RSA.generate(2048)
print("\nRSA public key generated (hidden).")
public_key = RSA_key.export_key()
RSA_key_file = open("RSA_key_file.pem", "wb")
RSA_key_file.write(public_key)
RSA_key_file.close()

print("\nWaiting for connection on 0.0.0.0:" + str(portNum) + " ...")


# Verify an HMAC given a message and shared key
コード例 #25
0
def generate_aes():
    """Generate an AES key."""
    key = get_random_bytes(AES_SIZE)
    return key
コード例 #26
0
def AES_cipher():
	key = get_random_bytes(16)
	cipher = AES.new(key, AES.MODE_CBC)
	print(cipher)
コード例 #27
0
def generate_random_key(size=32):
    return get_random_bytes(size)
コード例 #28
0
# pip3 install pycryptodomex
from Cryptodome.Cipher import DES
from Cryptodome.Util.Padding import unpad, pad
from Cryptodome.Random import get_random_bytes
# pour les arguments passés en ligne de commande
import sys

# Verifier si on a fourni le texte à chiffrer
if len(sys.argv) == 1:
    print("Usage : \n\t", sys.argv[0], "<TEXTE A CHIFFRER>")
    exit(1)

user_text = " ".join(sys.argv[1:])
text_clair = user_text

cle = get_random_bytes(DES.key_size)  # 8 bytes pour la clé du DES
iv = get_random_bytes(8)  # 8 bytes pour le mode CBC

cipher1 = DES.new(cle, DES.MODE_CBC, iv)
text_chiffre = cipher1.encrypt(pad(text_clair.encode('utf-8'), DES.block_size))

cipher2 = DES.new(cle, DES.MODE_CBC, iv)
text_dechiffre = unpad(cipher2.decrypt(text_chiffre), DES.block_size)

print(__doc__)
print("Texte clair       :", text_clair)
print("Texte chiffré     :", text_chiffre.hex())
print("Texte dechiffré   :", text_dechiffre.decode('utf-8'))
print("Decryptage reussi ?",
      'Oui' if text_dechiffre == text_clair.encode('utf-8') else 'Non')
コード例 #29
0
    ]
    decryptor = AES.new(sk, AES.MODE_EAX, nonce)
    msg = decryptor.decrypt(enc_msg)
    return msg.decode()


if __name__ == "__main__":
    # setting server
    serverPort = int(input('Enter the port number: '))
    server = s.socket(s.AF_INET, s.SOCK_STREAM)
    server.bind(('', serverPort))
    server.listen(5)
    userName = getpass.getuser()
    while True:
        clientSocket, address = server.accept()
        sessionKey = get_random_bytes(16)
        if authenticate(clientSocket, sessionKey, userName):
            while True:
                #print('Receiving..')
                cmd = receiveMessage(clientSocket, sessionKey)
                output = b'NULL'
                if (cmd.lower() == 'exit'):
                    break
                if (len(cmd) >= 2 and 'cd' == cmd[:2]):
                    if cmd == 'cd':
                        #print('calling cd here')
                        os.chdir(os.path.expanduser('/'))
                    else:
                        #print('changing directory')
                        try:
                            os.chdir(cmd[3:])
コード例 #30
0
def gen_random_key():
    return get_random_bytes(KEY_SIZE)
コード例 #31
0
ファイル: config.py プロジェクト: PawNode/cdn
    nonce = b64decode(split[1])
    tag = b64decode(split[2])
    encryptedStr = b64decode(split[3])

    aes = AES.new(AES_KEY, AES.MODE_GCM, nonce=nonce)
    plaintextStr = aes.decrypt_and_verify(encryptedStr, tag)
    return plaintextStr

def encryptString(plaintextStr):
    if isinstance(plaintextStr, str):
        plaintextStr = plaintextStr.encode('utf-8')
    aes = AES.new(AES_KEY, AES.MODE_GCM)
    encryptedStr, tag = aes.encrypt_and_digest(plaintextStr)
    return "2.%s.%s.%s" % (b64encode(aes.nonce).decode('utf-8'), b64encode(tag).decode('utf-8'), b64encode(encryptedStr).decode('utf-8'))

config = None
with open(path.join(__dir__, './config.yml'), 'r') as f:
    config = yaml_load(f)

config['serverId'] = serverId

if __name__ == '__main__':
    from sys import argv
    from Cryptodome.Random import get_random_bytes

    if argv[1] == 'encrypt':
        print(encryptString(argv[2]))
    elif argv[1] == 'newkey':
        print(b64encode(get_random_bytes(16)))
コード例 #32
0
    def generate_aes_key(self):  #This function generates the AES key
        self.aes_key = get_random_bytes(AES.block_size)

        return self.aes_key
コード例 #33
0
def gen_random_nonce():
    return get_random_bytes(NONCE_SIZE)
コード例 #34
0
def handler(conn, addr, passwd):
    now = datetime.datetime.now()
    sessionServerRSAPrivateKey = generateServerRSAKeyPair(conn)
    # Indicating that the server has generated the key and sent public key to client
    time.sleep(2)
    print(
        f"Server's RSA public key has been generated and sent to the client {addr[0]}:{addr[1]}\n"
    )
    sessionClientRSAPublicKey = ClientRSAPublicKeyreceive(conn)
    # Indicating that the data has been received from the client
    print(
        f"Client's Public RSA key (Client {addr[0]}:{addr[1]}) has been received!\n"
    )
    # Send the encrypted diffie hellman key to the client, encrypted with the client's public RSA key
    serverDHPublicKey = encryptDiffie(diffieHellmanKeyExchange(),
                                      sessionClientRSAPublicKey)
    send(serverDHPublicKey, conn)
    print(
        f"Diffie Hellman key has been generated and sent to the client (Client {addr[0]}:{addr[1]})\n"
    )
    # Receive client's public DH key and decrypt it with server's private RSA key
    clientEncryptedDHPublicKey = receive_data(conn)
    clientDHPublicKey = int((decryptDiffieHellman(clientEncryptedDHPublicKey,
                                                  sessionServerRSAPrivateKey)))
    AESSessionKey = diffieHellmanKeyExchangeCalculations(clientDHPublicKey)
    print(
        f"Client's ({addr[0]}:{addr[1]}) Diffie Hellman public key has been received!\n"
    )
    # Receive data from client, CMD_GETMENU
    if hashcheck(conn, cmd_GET_MENU, addr):
        # Send menuPayload with 'clientRSAPublicKey', but it is actually server's generated public key. Same attribute type to make them recognizable in each other's program
        menuPayload = encryptedPayloadSent(clientDHPublicKey, AESSessionKey)
        send(menuPayload, conn)
    print(
        f"Client's ({addr[0]}:{addr[1]}) Menu of the day command has been received and its integrity verified. Sending encrypted menu to client!\n"
    )
    if hashcheck(conn, cmd_END_DAY, addr):
        # Receving day_end.csv from server
        dataReceived = encryptedPayloadReceived(
            pickle.loads(AESDecrypt(receive_data(conn), AESSessionKey)))
        # Verifying data and storing it on server
        if VerifierHMACDSIG(dataReceived[0], dataReceived[1], dataReceived[2],
                            dataReceived[3], dataReceived[4],
                            clientDHPublicKey):
            filename = default_save_base + "127.0.0.1" + "-" + now.strftime(
                "%Y-%m-%d_%H%M")
            dest_file = open("database/" + filename, "wb")

            # If encrypted key file does not exist
            if not os.path.exists("database/key"):
                random_key = get_random_bytes(32)
                info_encrypted = AESEncrypt(dataReceived[0], random_key)
                dest_file.write(info_encrypted)
                encryptedKey = AESEncrypt(random_key, passwd)
                with open("database/key", 'wb') as f:
                    f.write(encryptedKey)
                    f.close()
            # If it exists, decrypt it and get key to encrypt file
            else:
                key = open("database/key", 'rb').read()
                decryptedKey = AESDecrypt(key, passwd)
                dest_file.write(AESEncrypt(dataReceived[0], decryptedKey))
                dest_file.close()
        else:
            conn.close()
コード例 #35
0
ファイル: cipher.py プロジェクト: vesellov/bitdust.public
def make_key(cipher_type='AES'):
    if cipher_type == 'AES':
        return get_random_bytes(AES.block_size)
    elif cipher_type == 'DES3':
        return get_random_bytes(DES3.block_size)
    raise Exception('unsupported cipher type')
コード例 #36
0
def encrypt(data, key):
  iv = ''.join('{:02x}'.format(x) for x in get_random_bytes(8)).encode('utf8')
  aes = AES.new(key, AES.MODE_CBC, iv)
  padded_size = len(data) + (16 - len(data) % 16)
  message = iv + aes.encrypt(data.ljust(padded_size, '\x00').encode('utf8'))
  return message
コード例 #37
0
def DES3_generation():
    key = DES3.adjust_key_parity(get_random_bytes(24))
    return key
コード例 #38
0
def dsa_verify(y: int, msg: bytes, sig) -> bool:
    r, s = sig
    if not (0 < r < q and 0 < s < q):
        return False
    w = pow(s, -1, q)  # w = k/(h+xr) mod q
    h = int.from_bytes(SHA1.new(msg).digest(), 'big')
    u1 = (h * w) % q  # u1 = hk/(h+xr)
    u2 = (r * w) % q  # u2 = rk/(h+xr)
    v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
    # v0 = g^(hk/(h+xr)) * (g^x)^(rk/(h+xr)) mod p
    #    = g^(k(h+xr)/(h+xr))                mod p
    #    = g^k                               mod p
    # v = v0 mod q = r
    return v == r


## Sanity check ##
if __name__ == '__main__':
    print('Sanity check...', end=' ')
    x, y = gen_user_key()
    msg1 = get_random_bytes(100)
    sig1 = dsa_sign(x, msg1)
    assert dsa_verify(y, msg1, sig1)
    msg2 = get_random_bytes(100)
    sig2 = dsa_sign(x, msg2)
    assert dsa_verify(y, msg2, sig2)
    assert not dsa_verify(y, msg1, sig2)
    assert not dsa_verify(y, msg2, sig1)
    print('OK')
コード例 #39
0
ファイル: AESCipher.py プロジェクト: berrym/lair
 def encrypt(self, rawdata: str) -> bytes:
     """Encrypt raw data."""
     raw_data = pad(rawdata.encode("utf-8"), AES.block_size)
     iv = get_random_bytes(AES.block_size)
     cipher = AES.new(self.key, AES.MODE_CBC, iv)
     return base64.b64encode(iv + cipher.encrypt(raw_data))
コード例 #40
0
from Cryptodome.PublicKey import RSA
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_OAEP

with open('encrypted_data.bin', 'wb') as out_file:
    recipient_key = RSA.import_key(open('my_rsa_public.pem').read())

    session_key = get_random_bytes(16)

    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    out_file.write(cipher_rsa.encrypt(session_key))

    cipher_aes = AES.new(session_key, AES.MODE_EAX)
    data = b'blah blah blah Python blah blah'
    ciphertext, tag = cipher_aes.encrypt_and_digest(data)

    out_file.write(cipher_aes.nonce)
    out_file.write(tag)
    out_file.write(ciphertext)
コード例 #41
0
ファイル: Crypto.py プロジェクト: steptospace/Course_works
def gen_session_key():
    key = get_random_bytes(32)
    return key
コード例 #42
0
        done with this key. It must be 8 bytes long.

        If not provided, a random byte string will be generated (you can read
        it back via the ``nonce`` attribute).

    :Return: a `ChaCha20Cipher` object
    """

    try:
        key = kwargs.pop("key")
    except KeyError, e:
        raise TypeError("Missing parameter %s" % e)

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(8)

    if len(key) != 32:
        raise ValueError("ChaCha20 key must be 32 bytes long")
    if len(nonce) != 8:
        raise ValueError("ChaCha20 nonce must be 8 bytes long")

    if kwargs:
        raise TypeError("Unknown parameters: " + str(kwargs))

    return ChaCha20Cipher(key, nonce)

#: Size of a data block (in bytes)
block_size = 1

#: Size of a key (in bytes)
コード例 #43
0
ファイル: 6.41.py プロジェクト: blegloannec/cryptopals

class Server:
    def __init__(self):
        self.k, self.K = rsalib.gen_key(1<<10)
        self.Seen = {}
    
    def decrypt(self, c):
        assert c not in self.Seen
        self.Seen[c] = time.time()
        return rsalib.decrypt(self.k, c)


if __name__=='__main__':
    S = Server()
    e, n = K = S.K
    mess0 = b'platypus:'+base64.b64encode(get_random_bytes(12))
    m0 = int.from_bytes(mess0, 'big')
    print(mess0, hex(m0))
    c0 = rsalib.encrypt(K, m0)  # intercepted
    print('Server:', hex(S.decrypt(c0)))
    s = randint(2, n-1)
    c1 = (pow(s, e, n) * c0) % n
    # c1 = s^e * c0 = (s*m)^e
    # c1^d = s*m
    m1 = S.decrypt(c1)
    m2 = (m1 * pow(s, -1, n)) % n
    mess2 = int_to_bytes(m2)
    print(mess2, hex(m2))
    assert mess2 == mess0
コード例 #44
0
def make_a_blockJ(vector):
    if len(vector) == 12:
        result_vector = vector.bin + "0" * 31 + "1"
        return bitstring_to_bytes(result_vector)
    else:
        length_vector = len(vector.bin)
        s = 128 * ceil(length_vector / 128) - length_vector
        result_vector = vector.bin + "0" * (s + 64) + bin(length_vector)[2:]
        return ghash(result_vector)


if __name__ == '__main__':
    test_str = input("Введите строку:\n")
    res = ''.join(format(ord(i), 'b') for i in test_str)
    addi_auth_data = bitstring.BitArray(get_random_bytes(8)).bin
    lenght_aad = len(addi_auth_data)
    key = long_to_bytes(pow(2, 128) - 1)
    aes = AES.new(key, AES.MODE_EAX)
    H, tag = aes.encrypt_and_digest(bytearray(16))
    H_int = format(int.from_bytes(H, byteorder='big'), "b").rjust(128, "0")
    tag_int = format(int.from_bytes(tag, byteorder='big'), "b").rjust(128, "0")
    init_vector = bitstring.BitArray(bytearray(16))
    j0 = make_a_blockJ(init_vector)
    cipher_text = gctr(inc(j0, 32), res, key)
    if len(cipher_text) % 128 != 0:
        cipher_text = cipher_text.rjust(
            128 - len(cipher_text) % 128 + len(cipher_text), "0")
    u = 128 * ceil(lenght_aad / 128) - len(cipher_text)
    v = 128 * ceil(lenght_aad / 128) - lenght_aad
    addi_auth_dat = addi_auth_data + ("0" * u) + cipher_text + (
コード例 #45
0
        or 32 (e.g. *AES-256*) bytes long.

      nonce : byte string
        A value that must never be reused for any other encryption.

        There are no restrictions on its length,
        but it is recommended to use at least 16 bytes.

        The nonce shall never repeat for two
        different messages encrypted with the same key,
        but it does not need to be random.

        If not provided, a 16 byte nonce will be randomly created.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be no larger than 16 bytes (which is the default).
    """

    try:
        key = kwargs.pop("key")
    except KeyError, e:
        raise TypeError("Missing parameter:" + str(e))

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(16)
    mac_len = kwargs.pop("mac_len", 16)

    return GcmMode(factory, key, nonce, mac_len, kwargs)
コード例 #46
0
ファイル: legacy_gui.py プロジェクト: fmeserver/Bismuth
def send_confirm(amount_input, recipient_input, operation_input,
                 openfield_input):
    top10 = Toplevel()
    top10.title("Confirm")

    # encr check
    if encrypt_var.get() == 1:
        #get recipient's public key
        c.execute(
            "SELECT public_key FROM transactions WHERE address = ? and reward = 0",
            (recipient_input, ))
        target_public_key_hashed = c.fetchone()[0]

        recipient_key = RSA.importKey(
            base64.b64decode(target_public_key_hashed).decode("utf-8"))

        #openfield_input = str(target_public_key.encrypt(openfield_input.encode("utf-8"), 32))

        data = openfield_input.encode("utf-8")
        # print (open("pubkey.der").read())
        session_key = get_random_bytes(16)
        cipher_aes = AES.new(session_key, AES.MODE_EAX)

        # Encrypt the session key with the public RSA key
        cipher_rsa = PKCS1_OAEP.new(recipient_key)

        # Encrypt the data with the AES session key
        ciphertext, tag = cipher_aes.encrypt_and_digest(data)
        enc_session_key = (cipher_rsa.encrypt(session_key))
        openfield_input = str(
            [x for x in (cipher_aes.nonce, tag, ciphertext, enc_session_key)])

    # encr check

    # msg check

    if encode_var.get() == 1:
        openfield_input = base64.b64encode(
            openfield_input.encode("utf-8")).decode("utf-8")

    # msg check
    if msg_var.get() == 1 and encode_var.get() == 1:
        openfield_input = "bmsg=" + openfield_input
    if msg_var.get() == 1 and encode_var.get() == 0:
        openfield_input = "msg=" + openfield_input

    if encrypt_var.get() == 1:
        openfield_input = "enc=" + str(openfield_input)

    fee = '%.8f' % float(0.01 + (float(len(openfield_input)) / 100000) +
                         int(operation_var.get()))  # 0.01 dust

    confirmation_dialog = Text(top10, width=100)
    confirmation_dialog.insert(
        INSERT,
        ("Amount: {}\nTo: {}\nFee: {}\noperation Entry: {}\nOpenField:\n\n{}".
         format(amount_input, recipient_input, fee, operation_input,
                openfield_input)))

    confirmation_dialog.grid(row=0, pady=0)

    enter = Button(
        top10,
        text="Confirm",
        command=lambda: send(amount_input, recipient_input, operation_input,
                             openfield_input, top10, fee))
    enter.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    done = Button(top10, text="Cancel", command=top10.destroy)
    done.grid(row=2, column=0, sticky=W + E, padx=15, pady=(5, 5))
コード例 #47
0
    msg3, mk_hash, sk_hash = c.remote_attestation_update(msg2)
    logger.debug(f'msg3 <- {hexlify(msg3)}')

    report, advisory = ra.recv_msg3_verify(msg3)

    v_mk = mk_hash == SHA256.new(ra.mk).digest()
    v_sk = sk_hash == SHA256.new(ra.sk).digest()
    if v_mk and v_sk:
        logger.info(f'SHA256(MK) = {hexlify(mk_hash)}')
        logger.info(f'SHA256(SK) = {hexlify(sk_hash)}')
    else:
        raise Exception("Remote Attestation Failed")

    # Coin tossing

    # coin = int.from_bytes(get_random_bytes(4), 'little')
    coin = 0x123456
    # iv = unhexlify('5016e1d232e7d0f01e15ce610356054c')
    # key = unhexlify('beb4b02dbce8708c1c0d030f40909b61') # ra.sk
    key = ra.sk

    cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(12))
    ciphertext, tag = cipher.encrypt_and_digest(int.to_bytes(coin, 4, 'little'))
    iv = cipher.nonce

    print(f'key =           {hexlify(key)}')
    print(f'iv =            {hexlify(iv)}')
    print(f'ciphertext =    {hexlify(ciphertext)}')
    print(f'tag =           {hexlify(tag)}')
    c.coin_tossing(iv, ciphertext, tag)
コード例 #48
0
ファイル: _mode_ctr.py プロジェクト: fhl2546374141/dailyfresh
def _create_ctr_cipher(factory, **kwargs):
    """Instantiate a cipher object that performs CTR encryption/decryption.

    :Parameters:
      factory : module
        The underlying block cipher, a module from ``Cryptodome.Cipher``.

    :Keywords:
      nonce : bytes/bytearray/memoryview
        The fixed part at the beginning of the counter block - the rest is
        the counter number that gets increased when processing the next block.
        The nonce must be such that no two messages are encrypted under the
        same key and the same nonce.

        The nonce must be shorter than the block size (it can have
        zero length; the counter is then as long as the block).

        If this parameter is not present, a random nonce will be created with
        length equal to half the block size. No random nonce shorter than
        64 bits will be created though - you must really think through all
        security consequences of using such a short block size.

      initial_value : posive integer or bytes/bytearray/memoryview
        The initial value for the counter. If not present, the cipher will
        start counting from 0. The value is incremented by one for each block.
        The counter number is encoded in big endian mode.

      counter : object
        Instance of ``Cryptodome.Util.Counter``, which allows full customization
        of the counter block. This parameter is incompatible to both ``nonce``
        and ``initial_value``.

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    cipher_state = factory._create_base_cipher(kwargs)

    counter = kwargs.pop("counter", None)
    nonce = kwargs.pop("nonce", None)
    initial_value = kwargs.pop("initial_value", None)
    if kwargs:
        raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs))

    if counter is not None and (nonce, initial_value) != (None, None):
        raise TypeError("'counter' and 'nonce'/'initial_value'"
                        " are mutually exclusive")

    if counter is None:
        # Cryptodome.Util.Counter is not used
        if nonce is None:
            if factory.block_size < 16:
                raise TypeError("Impossible to create a safe nonce for short"
                                " block sizes")
            nonce = get_random_bytes(factory.block_size // 2)
        else:
            if len(nonce) >= factory.block_size:
                raise ValueError("Nonce is too long")

        # What is not nonce is counter
        counter_len = factory.block_size - len(nonce)

        if initial_value is None:
            initial_value = 0

        if is_native_int(initial_value):
            if (1 << (counter_len * 8)) - 1 < initial_value:
                raise ValueError("Initial counter value is too large")
            initial_counter_block = nonce + long_to_bytes(
                initial_value, counter_len)
        else:
            if len(initial_value) != counter_len:
                raise ValueError(
                    "Incorrect length for counter byte string (%d bytes, expected %d)"
                    % (len(initial_value), counter_len))
            initial_counter_block = nonce + initial_value

        return CtrMode(
            cipher_state,
            initial_counter_block,
            len(nonce),  # prefix
            counter_len,
            False)  # little_endian

    # Cryptodome.Util.Counter is used

    # 'counter' used to be a callable object, but now it is
    # just a dictionary for backward compatibility.
    _counter = dict(counter)
    try:
        counter_len = _counter.pop("counter_len")
        prefix = _counter.pop("prefix")
        suffix = _counter.pop("suffix")
        initial_value = _counter.pop("initial_value")
        little_endian = _counter.pop("little_endian")
    except KeyError:
        raise TypeError("Incorrect counter object"
                        " (use Cryptodome.Util.Counter.new)")

    # Compute initial counter block
    words = []
    while initial_value > 0:
        words.append(struct.pack('B', initial_value & 255))
        initial_value >>= 8
    words += [b'\x00'] * max(0, counter_len - len(words))
    if not little_endian:
        words.reverse()
    initial_counter_block = prefix + b"".join(words) + suffix

    if len(initial_counter_block) != factory.block_size:
        raise ValueError("Size of the counter block (%d bytes) must match"
                         " block size (%d)" %
                         (len(initial_counter_block), factory.block_size))

    return CtrMode(cipher_state, initial_counter_block, len(prefix),
                   counter_len, little_endian)
コード例 #49
0
from Cryptodome.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES
from Cryptodome.Random import get_random_bytes

key = b'-8B key-'
DES.new(
    key, DES.MODE_OFB
)  # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search

key = DES3.adjust_key_parity(get_random_bytes(24))
cipher = DES3.new(
    key, DES3.MODE_CFB
)  # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack

key = b'Sixteen byte key'
cipher = ARC2.new(
    key,
    ARC2.MODE_CFB)  # Noncompliant: RC2 is vulnerable to a related-key attack

key = b'Very long and confidential key'
cipher = ARC4.new(
    key
)  # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security)

key = b'An arbitrarily long key'
cipher = Blowfish.new(
    key, Blowfish.MODE_CBC
)  # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks
コード例 #50
0
def make_key():
    return get_random_bytes(16)
コード例 #51
0
ファイル: cipher.py プロジェクト: vesellov/bitdust.public
def generate_secret_text(size):
    return base64.b32encode(get_random_bytes(size)).decode()
コード例 #52
0
ファイル: servent_v3.py プロジェクト: hannurs/AESchat
def send_fun():
    # connect to the other client
    SENDHOST = '192.168.51.208'
    SENDPORT = 65432
    sock_send =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_send.connect((SENDHOST, SENDPORT))

    global path
    global filename
    global attach_name
    global progress_bar
    global session_key

    if session_key == False:
        # generate session key and send it
        # exchange_session_key()
        session_key = get_random_bytes(16)

        cipher_rsa = PKCS1_OAEP.new(recipients_public_key)
        enc_session_key = cipher_rsa.encrypt(session_key)
        sock_send.sendall(enc_session_key)
        # print("wyslany session key "+ str(enc_session_key))
        time.sleep(0.1)

    # send the AES encryption mode
    sock_send.sendall(bytes(str(encrypt_mode.get()), "utf-8"))
    #time.sleep(0.1)

    # send the content of input (message)
    print(filename)
    message_string = message_input.get()
    if message_string == '' or filename != '':
        message_string = message_string+"+załącznik: "+filename

    message_encrypted = encrypt(bytes(message_string, 'utf-8'))
    sock_send.sendall(message_encrypted)
    # print('wyslana wiadomosc: '+ str(message_encrypted))
    time.sleep(0.1)

    # display my message
    messages_display.config(state='normal')
    messages_display.insert(tkinter.INSERT, 'Ty: '+message_string+'\n')
    messages_display.config(state='disabled')
    message_input.delete(0, 'end')

    # send the filename so that server knows if there is an attachment
    filename_enc = encrypt(bytes(filename, 'utf-8'))
    sock_send.sendall(filename_enc)
    print('wyslany zalacznik: '+str(filename))
    time.sleep(0.1)

    # if there is an attachent (filename is not null), send the content of it
    if path != '':
        attach_name.destroy()
        encrypt_file(path)
        f = open(path+".enc", 'rb')
        filesize = os.stat(path).st_size
        step_in_progress = 100/(filesize/1024)
        #print("rozmiar: "+str(filesize))
        # TODO progress bar
        data = f.read(1024)
        # data = encrypt(data)
        while(data):
            # TODO progress bar
            sock_send.sendall(data)
            progress_bar['value'] += step_in_progress
            root.update_idletasks()
            data = f.read(1024)
            # data = encrypt(data)
        f.close()
        os.remove(path+".enc")
        path = ''
        filename = ''
        progress_bar.destroy()
    sock_send.close()
コード例 #53
0
ファイル: _mode_ctr.py プロジェクト: chevah/python-package
def _create_ctr_cipher(factory, **kwargs):
    """Instantiate a cipher object that performs CTR encryption/decryption.

    :Parameters:
      factory : module
        The underlying block cipher, a module from ``Cryptodome.Cipher``.

    :Keywords:
      nonce : bytes/bytearray/memoryview
        The fixed part at the beginning of the counter block - the rest is
        the counter number that gets increased when processing the next block.
        The nonce must be such that no two messages are encrypted under the
        same key and the same nonce.

        The nonce must be shorter than the block size (it can have
        zero length; the counter is then as long as the block).

        If this parameter is not present, a random nonce will be created with
        length equal to half the block size. No random nonce shorter than
        64 bits will be created though - you must really think through all
        security consequences of using such a short block size.

      initial_value : posive integer or bytes/bytearray/memoryview
        The initial value for the counter. If not present, the cipher will
        start counting from 0. The value is incremented by one for each block.
        The counter number is encoded in big endian mode.

      counter : object
        Instance of ``Cryptodome.Util.Counter``, which allows full customization
        of the counter block. This parameter is incompatible to both ``nonce``
        and ``initial_value``.

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    cipher_state = factory._create_base_cipher(kwargs)

    counter = kwargs.pop("counter", None)
    nonce = kwargs.pop("nonce", None)
    initial_value = kwargs.pop("initial_value", None)
    if kwargs:
        raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs))

    if counter is not None and (nonce, initial_value) != (None, None):
            raise TypeError("'counter' and 'nonce'/'initial_value'"
                            " are mutually exclusive")

    if counter is None:
        # Cryptodome.Util.Counter is not used
        if nonce is None:
            if factory.block_size < 16:
                raise TypeError("Impossible to create a safe nonce for short"
                                " block sizes")
            nonce = get_random_bytes(factory.block_size // 2)
        else:
            if len(nonce) >= factory.block_size:
                raise ValueError("Nonce is too long")
        
        # What is not nonce is counter
        counter_len = factory.block_size - len(nonce)

        if initial_value is None:
            initial_value = 0

        if isinstance(initial_value, (int, long)):
            if (1 << (counter_len * 8)) - 1 < initial_value:
                raise ValueError("Initial counter value is too large")
            initial_counter_block = nonce + long_to_bytes(initial_value, counter_len)
        else:
            if len(initial_value) != counter_len:
                raise ValueError("Incorrect length for counter byte string (%d bytes, expected %d)" % (len(initial_value), counter_len))
            initial_counter_block = nonce + initial_value

        return CtrMode(cipher_state,
                       initial_counter_block,
                       len(nonce),                     # prefix
                       counter_len,
                       False)                          # little_endian

    # Cryptodome.Util.Counter is used

    # 'counter' used to be a callable object, but now it is
    # just a dictionary for backward compatibility.
    _counter = dict(counter)
    try:
        counter_len = _counter.pop("counter_len")
        prefix = _counter.pop("prefix")
        suffix = _counter.pop("suffix")
        initial_value = _counter.pop("initial_value")
        little_endian = _counter.pop("little_endian")
    except KeyError:
        raise TypeError("Incorrect counter object"
                        " (use Cryptodome.Util.Counter.new)")

    # Compute initial counter block
    words = []
    while initial_value > 0:
        words.append(struct.pack('B', initial_value & 255))
        initial_value >>= 8
    words += [ b'\x00' ] * max(0, counter_len - len(words))
    if not little_endian:
        words.reverse()
    initial_counter_block = prefix + b"".join(words) + suffix

    if len(initial_counter_block) != factory.block_size:
        raise ValueError("Size of the counter block (%d bytes) must match"
                         " block size (%d)" % (len(initial_counter_block),
                                               factory.block_size))

    return CtrMode(cipher_state, initial_counter_block,
                   len(prefix), counter_len, little_endian)
コード例 #54
0
def generate_key(path='32byteskey.pem'):
	key = get_random_bytes(32)
	with open(path, mode='wb') as f:
		f.write(key)