def saveToDisk(cls, data, logFile, token, compress=False):
        if data is None or logFile is None or token is None:
            raise InvalidLogFileException()

        salt = get_random_bytes(cls._salt_size)
        if len(salt) != cls._salt_size:
            raise EncryptionException()

        (enc_key, hmac_key) = cls._getKeys(token, salt)

        nonce = get_random_bytes(cls._nonce_size)
        if len(nonce) != cls._nonce_size:
            raise EncryptionException()

        ctr = Crypto.Util.Counter.new(cls._counter_size, prefix=nonce)
        cipher = Crypto.Cipher.AES.new(enc_key, Crypto.Cipher.AES.MODE_CTR, counter=ctr)

        if compress:
            data = bz2.compress(bytes(data, 'utf-8'), cls._compression_level)

        ciphertext = cipher.encrypt(data)
        ciphertext_len = len(ciphertext)
        new_hmac = hmac.new(hmac_key, salt + nonce + ciphertext + struct.pack(">I", ciphertext_len), cls._hmac_hash_algo)

        (fd, temporary_file_name) = tempfile.mkstemp()
        os.write(fd, salt)
        os.write(fd, nonce)
        os.write(fd, new_hmac.digest())
        os.write(fd, ciphertext)
        os.fsync(fd)
        os.rename(temporary_file_name, logFile)
        os.close(fd)
Beispiel #2
0
def main():
    print 'enter input:'
    inp = sys.stdin.readline()
    inp = _normalize(inp, 16)
    key8 = get_random_bytes(8)
    key16 = get_random_bytes(16)
    iv8 = get_random_bytes(8)
    iv16 = get_random_bytes(16)
    print 'key8\t', _to_hex(key8)
    print 'key16\t', _to_hex(key16)
    print 'iv8\t', _to_hex(iv8)
    print 'iv16\t', _to_hex(iv16)
    print 'DES, ECB mode'
    des = DES.new(key8, DES.MODE_ECB)
    enc = des.encrypt(inp)
    print '\tencoded:', _to_hex(enc)
    print '\tentropy:', _entropy_hex(_to_hex(enc))
    print 'DES, CBC mode'
    des = DES.new(key8, DES.MODE_CBC, iv8)
    enc = des.encrypt(inp)
    print '\tencoded:', _to_hex(enc)
    print '\tentropy:', _entropy_hex(_to_hex(enc))
    print 'AES, ECB mode'
    aes = AES.new(key16, AES.MODE_ECB)
    enc = aes.encrypt(inp)
    print '\tencoded:', _to_hex(enc)
    print '\tentropy:', _entropy_hex(_to_hex(enc))
    print 'DES, CBC mode'
    aes = AES.new(key16, AES.MODE_CBC, iv16)
    enc = aes.encrypt(inp)
    print '\tencoded:', _to_hex(enc)
    print '\tentropy:', _entropy_hex(_to_hex(enc))
Beispiel #3
0
    def write(self, filename=None):
        '''' 
        Write out DB to given filename with optional master key.
        If no master key is given, the one used to create this DB is used.
        '''
        import hashlib

        outfilename = filename or self.filename
        self.header.ngroups = len(self.groups)
        self.header.nentries = len(self.entries)

        self.header.final_master_seed = get_random_bytes(16)
        self.header.encryption_iv = get_random_bytes(16)
        self.header.transform_seed = get_random_bytes(32)
        header = DBHDR(self.header.encode())

        # fixme: should regenerate encryption_iv, master_seed,
        # master_seed2 and allow for the number of rounds to change

        payload = self.encode_payload()
        header.contents_hash = hashlib.sha256(payload).digest()


        payload = self.encrypt_payload(payload, self.final_key(), 
                                       header.encryption_type(),
                                       header.encryption_iv)

        fp = open(outfilename,'w')
        fp.write(header.encode())
        fp.write(payload)
        fp.close()
        return
Beispiel #4
0
def encrypt(text):
    salt        = get_random_bytes(16)
    passwd      = get_random_bytes(32)
    iv          = get_random_bytes(iv_size)
    key         = PBKDF2(passwd, salt, dkLen=32, count=iterations)
    cipher      = AES.new(key, AES.MODE_CBC, iv)
    return (clean((iv + cipher.encrypt(pad(text)))),
            clean((key)))
Beispiel #5
0
def encrypt_and_sign(msg, senderPrivPem, receiverPubPem):
    """
   Encrypts a message using AES256-CTR. The procedure first creates a new
   random key/nonce for symmetric encryption and encrypt/signs that via RSA.
   The procedure then symmatrically encrypts the actual message using that key/nonce.

   :param msg: Message to be encrypted.
   :type msg: str
   :param senderPrivPem: Sender private RSA key in PEM format.
   :type senderPrivPem: str
   :param receiverPubPem: Receiver public RSA key in PEM format.
   :type receiverPubPem: str
   :returns tuple -- (AES256-CTR encrypted message, RSA Encrypted Key+IV, RSA Signature) all Base64 encoded.
   """
    ## read in sender/receiver RSA keys
    ##
    skey = RSA.importKey(senderPrivPem)
    rkey = RSA.importKey(receiverPubPem)

    ## create new random key/nonce for AES
    ##
    key = get_random_bytes(CIPHERBITS / 8)
    nonce = get_random_bytes(8)
    kv = key + nonce

    # print binascii.b2a_hex(kv)
    # print binascii.b2a_hex(key)
    # print binascii.b2a_hex(nonce)

    ## encrypt key/nonce using RSA
    ##
    emsg = rkey.encrypt(kv, 0)[0]

    ## encrypt msg using AES-256 in CTR mode
    ##
    c = AES.new(key, AES.MODE_CTR, counter=Counter.new(64, prefix=nonce))
    pmsg = c.encrypt(pad(msg))

    ## create a digest of the unencrypted message
    ##
    md = hashlib.sha256()
    md.update(msg)
    dmsg = md.digest()

    ## create a RSA signature over encrypted message + key/nonce
    ##
    ed = hashlib.sha256()
    ed.update(pmsg)
    ed.update(emsg)
    sig = long_to_bytes(skey.sign(ed.digest(), 0)[0])

    return (
        binascii.b2a_base64(pmsg).strip(),
        binascii.b2a_base64(emsg).strip(),
        binascii.b2a_base64(dmsg).strip(),
        binascii.b2a_base64(sig).strip(),
    )
Beispiel #6
0
def encrypt_aes(string):
    key_bytes = get_random_bytes(key_size)
    pad = block_size - len(string.encode('utf-8')) % block_size
    data = string.encode('utf-8') + pad * chr(pad)
    iv_bytes = get_random_bytes(block_size)
    encrypted_bytes = iv_bytes + AES.new(key_bytes, mode, iv_bytes).encrypt(data)
    string_encrypted = base64.urlsafe_b64encode(str(encrypted_bytes))
    key = base64.urlsafe_b64encode(str(key_bytes))
    return (string_encrypted, key)
Beispiel #7
0
    def create_msg(self, from_jid, jid, plaintext):
        key = get_random_bytes(16)
        iv = get_random_bytes(16)
        encrypted_keys = {}

        devices_list = self.device_list_for(jid)
        if len(devices_list) == 0:
            log.error('No known devices')
            return

        for dev in devices_list:
            self.get_session_cipher(jid, dev)
        session_ciphers = self.session_ciphers[jid]
        if not session_ciphers:
            log.warning('No session ciphers for ' + jid)
            return

        # Encrypt the message key with for each of receivers devices
        for rid, cipher in session_ciphers.items():
            try:
                if self.isTrusted(cipher) == TRUSTED:
                    encrypted_keys[rid] = cipher.encrypt(key).serialize()
                else:
                    log.debug('Skipped Device because Trust is: ' +
                              str(self.isTrusted(cipher)))
            except:
                log.warning('Failed to find key for device ' + str(rid))

        if len(encrypted_keys) == 0:
            log_msg = 'Encrypted keys empty'
            log.error(log_msg)
            raise NoValidSessions(log_msg)

        my_other_devices = set(self.own_devices) - set({self.own_device_id})
        # Encrypt the message key with for each of our own devices
        for dev in my_other_devices:
            try:
                cipher = self.get_session_cipher(from_jid, dev)
                if self.isTrusted(cipher) == TRUSTED:
                    encrypted_keys[dev] = cipher.encrypt(key).serialize()
                else:
                    log.debug('Skipped own Device because Trust is: ' +
                              str(self.isTrusted(cipher)))
            except:
                log.warning('Failed to find key for device ' + str(dev))

        payload = encrypt(key, iv, plaintext)

        result = {'sid': self.own_device_id,
                  'keys': encrypted_keys,
                  'jid': jid,
                  'iv': iv,
                  'payload': payload}

        log.debug('Finished encrypting message')
        return result
    def create_msg(self, from_jid, jid, plaintext):
        key = get_random_bytes(16)
        iv = get_random_bytes(16)
        encrypted_keys = {}

        devices_list = self.device_list_for(jid)
        if len(devices_list) == 0:
            log.error('No known devices')
            return

        payload, tag = encrypt(key, iv, plaintext)

        key += tag

        # Encrypt the message key with for each of receivers devices
        for device in devices_list:
            try:
                if self.isTrusted(jid, device) == TRUSTED:
                    cipher = self.get_session_cipher(jid, device)
                    cipher_key = cipher.encrypt(key)
                    prekey = isinstance(cipher_key, PreKeyWhisperMessage)
                    encrypted_keys[device] = (cipher_key.serialize(), prekey)
                else:
                    log.debug('Skipped Device because Trust is: ' +
                              str(self.isTrusted(jid, device)))
            except:
                log.warning('Failed to find key for device ' + str(device))

        if len(encrypted_keys) == 0:
            log.error('Encrypted keys empty')
            raise NoValidSessions('Encrypted keys empty')

        my_other_devices = set(self.own_devices) - set({self.own_device_id})
        # Encrypt the message key with for each of our own devices
        for device in my_other_devices:
            try:
                if self.isTrusted(from_jid, device) == TRUSTED:
                    cipher = self.get_session_cipher(from_jid, device)
                    cipher_key = cipher.encrypt(key)
                    prekey = isinstance(cipher_key, PreKeyWhisperMessage)
                    encrypted_keys[device] = (cipher_key.serialize(), prekey)
                else:
                    log.debug('Skipped own Device because Trust is: ' +
                              str(self.isTrusted(from_jid, device)))
            except:
                log.warning('Failed to find key for device ' + str(device))

        result = {'sid': self.own_device_id,
                  'keys': encrypted_keys,
                  'jid': jid,
                  'iv': iv,
                  'payload': payload}

        log.debug('Finished encrypting message')
        return result
def encrypt_blob(public_key, data, aes_bytes=32, aes_mode=AES_MODE):
    public_crypto = PKCS1_OAEP.new(public_key)

    aes_key = get_random_bytes(aes_bytes)
    aes_iv = get_random_bytes(16)
    aes_crypto = AES.new(aes_key, aes_mode, aes_iv)

    data_pickle = pickle.dumps(data, protocol=-1)
    data_enc = aes_crypto.encrypt(pad_data(data_pickle))

    aes_key_enc = public_crypto.encrypt(aes_key)
    aes_key_len = bytes([int(math.log2(len(aes_key_enc)))])
    return aes_iv + aes_key_len + aes_key_enc + data_enc
def encrypt_blob(public_key, data, aes_bytes=32, aes_mode=AES_MODE):
    public_crypto = PKCS1_OAEP.new(public_key)

    aes_key = get_random_bytes(aes_bytes)
    aes_iv = get_random_bytes(16)
    # TODO: what AES mode should we use here?
    aes_crypto = AES.new(aes_key, aes_mode, iv)

    data_pickle = pickle.dumps(data, protocol=-1)
    data_enc = aes_crypto.encrypt(pad_data(data_pickle))
    
    aes_key_enc = public_crypto.encrypt(aes_key)
    return iv + len(aes_key_enc) + aes_key_enc + data_enc
Beispiel #11
0
    def encrypt(self, password):
        from Crypto.Random import get_random_bytes

        salt = get_random_bytes(self.block_size)
        from Crypto.Cipher import AES

        IV = get_random_bytes(AES.block_size)
        cipher = self._create_cipher(self.keyring_key, salt, IV)
        password_encrypted = cipher.encrypt(self.pw_prefix + password)
        # Serialize the salt, IV, and encrypted password in a secure format
        data = dict(salt=salt, IV=IV, password_encrypted=password_encrypted)
        for key in data:
            data[key] = base64.encodestring(data[key]).decode()
        return json.dumps(data).encode()
Beispiel #12
0
    def __init__(self,buf=None):
        'Create a header, read self from binary string if given'

        if buf:
            self.decode(buf)
        else:
            (self.signature1, self.signature2) = self.signatures
            self.flags = 3 # SHA2 + Rijndael seems to be the standard here
            self.version = self.version1
            self.final_master_seed = get_random_bytes(16)
            self.encryption_iv = get_random_bytes(16)
            self.transform_seed = get_random_bytes(32)

            self.contents_hash = ''
            self.transform_rounds = 50000
Beispiel #13
0
def sym_encrypt_cfb_128(secret_key, cleartext, hmac_algo="sha256", kdf_iterations=ITERATIONS):
    """perform AES-128 symmetric encryption on an arbitrary cleartext
    using the given secret_key in CFB mode.

    AES-CFB does not require padding the input, so simplifies the task a bit.
    returns a dict of the base64-encoded ciphertext, base64-encoded IV,
    the HMAC-digest-hex, the HMAC-digest-algorithm name,
    the key-derivation function used/number of rounds.
    presently, PBKDF2 is used for key-derivation.

    """
    secret_key = force_bytes(secret_key)
    cleartext = force_bytes(cleartext)
    assert hmac_algo in getattr(
        hashlib,
        "algorithms_available",  # See [PEP0466](https://www.python.org/dev/peps/pep-0466/)
        getattr(hashlib, "algorithms", []),
    )

    # Generate the AES initialisation vector, and the salt used by the key-derivation algo
    salt = get_random_bytes(8)
    iv = get_random_bytes(16)

    # AES-CFB-128 needs a 16byte key.
    # Use PBKDF2 to generate a 16byte key regardless of the secret_key length.
    key = pbkdf2_derive_key("sha1", secret_key, salt, kdf_iterations, 16)

    # we're using AES-128 because Bruce Schneier says not to use 192/256.
    # Who are we to argue?
    # https://www.schneier.com/blog/archives/2009/07/another_new_aes.html#c386957
    crypt = AES.new(key, mode=AES.MODE_CFB, IV=iv)
    ciphertext_64 = base64.b64encode(crypt.encrypt(cleartext))

    # generate the Message Authentication Code according to @hmac_algo
    # The MAC function is passed the cleartext + iv, and password.
    # use the IV to avoid the same cleartext / pw combination giving the same MAC
    hash_fn = getattr(hashlib, hmac_algo)
    h = hmac.new(secret_key, cleartext + iv, hash_fn)

    return {
        "ciphertext_64": ciphertext_64,
        "aes_iv_64": base64.b64encode(iv),
        "kdf_salt_64": base64.b64encode(salt),
        "kdf_algo": "PBKDF2",  # this is currently the only choice
        "kdf_iter": kdf_iterations,
        "hmac_hex": h.hexdigest(),
        "hmac_algo": hmac_algo,
    }
Beispiel #14
0
def generate_secret():
    """Make a secret key suitable for use in TOTP."""
    from Crypto.Random import get_random_bytes

    bytes = get_random_bytes(20)
    encoded = base64.b32encode(bytes)
    return encoded
    def _aes_encrypt(data, algorithm, key):
        '''AES encrypt'''

        if algorithm['subtype'] == 'cbc':
            mode = AES.MODE_CBC
        else:
            raise Exception('AES subtype not supported: %s'
                            % algorithm['subtype'])

        iv_size = algorithm['iv_size']
        block_size = iv_size
        include_iv = True

        if 'iv'in algorithm and algorithm['iv']:
            if len(algorithm['iv']) != algorithm['iv_size']:
                raise Exception('Invalid IV size')
            iv_value = algorithm['iv']
            include_iv = False
        else:
            iv_value = get_random_bytes(iv_size)

        numpad = block_size - (len(data) % block_size)
        data = data + numpad * chr(numpad)

        enc = AES.new(key, mode, iv_value).encrypt(data)

        if include_iv:
            enc = iv_value + enc

        return enc
Beispiel #16
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 range(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")
Beispiel #17
0
def _create_ocb_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OCB mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Crypto.Cipher`
        (like `Crypto.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))
Beispiel #18
0
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 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: byte string

    :Return: a :class:`Crypto.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) != 8:
        raise ValueError("ChaCha20 nonce must be 8 bytes long")

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

    return ChaCha20Cipher(key, nonce)
Beispiel #19
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]

        if self._mac_tag is None:
            self._mac_tag = self._kdf.derive()

        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")
Beispiel #20
0
def _create_ofb_cipher(factory, **kwargs):
    """Instantiate a cipher object that performs OFB encryption/decryption.

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

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

      IV : bytes/bytearray/memoryview
        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 OFB: %s" % str(kwargs))

    return OfbMode(cipher_state, iv)
Beispiel #21
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))
Beispiel #22
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")
Beispiel #23
0
    def encrypt(data, key):
        key = SHA256.new(key).digest()
        nonce = get_random_bytes(CryptoAES.nonce_size)

        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
        ciphertext = cipher.encrypt(data)
        return nonce + ciphertext
Beispiel #24
0
def load_secret_key_file(secret_key_file):
    """
    Loads a secret key from a file and initializes the engine with this key.
    
    This is designed for use in development/debugging and should NOT be used 
    in production, if you value the encrypted database data.
    
    :param secret_key_file: The path to a file containing the 32-byte secret key.
    :type secret_key_file: str
    
    :raise ensconce.exc.CryptoNotInitialized: If the engine cannot be initialized.
    """
    try:
        with open(secret_key_file) as fp:
            key_bytes = binascii.unhexlify(fp.read().strip())
            log.info("Using DEBUG secret.key from file: {0}".format(secret_key_file))
            try:
                secret_key = CombinedMasterKey(key_bytes)
                validate_key(key=secret_key)
            except exc.MissingKeyMetadata:
                log.info("Writng out DEBUG secret.key to key metadata row.")
                initialize_key_metadata(key=secret_key, salt=get_random_bytes(16))
            state.secret_key = secret_key
    except:
        log.exception("Unable to initialize secret key from file.")
        raise exc.CryptoNotInitialized("Crypto engine has not been initialized.")
Beispiel #25
0
 def encrypt(cls, key, keyusage, plaintext, confounder):
     if confounder is None:
         confounder = get_random_bytes(8)
     ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
     cksum = HMAC.new(ki, confounder + plaintext, MD5).digest()
     ke = HMAC.new(ki, cksum, MD5).digest()
     return cksum + ARC4.new(ke).encrypt(confounder + plaintext)
    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")
def test_random_large_chunk():
    sd = SecureDict(priv_rsa, pub_rsa)
    for i in range(100):
        data = get_random_bytes(1 << 15)
        sd['foo'] = data
        assert sd.export()['foo'] != data
        assert sd['foo'] == data
Beispiel #28
0
def init_crypto(options):
    """
    Interactive target to initialize the database with a new crypto passphrase.
    """
    print "Initializing crypto for an empty database."
    if crypto_util.has_encrypted_data():
        raise BuildFailure("Database has existing encrypted contents; use the 'rekey' target instead.")

    passphrase = raw_input("Passphrase: ")
    print "The database will be initialized with the passphrase between the arrows: --->%s<---" % passphrase
    print "The MD5 of the passphrase you entered is: %s" % hashlib.md5(passphrase).hexdigest()
    
    confirm = raw_input("Type 'YES' to confirm passphrase and MD5 are correct: ")
    if confirm != 'YES':
        raise ValueError("You must enter 'YES' to proceed.")
    
    salt = get_random_bytes(16)
    key = crypto_util.derive_key(passphrase=passphrase, salt=salt)
    crypto_util.initialize_key_metadata(key=key, salt=salt, force_overwrite=False)
    
    print "Database key metadata has been initialized.  Your application is ready for use."
    if config.get('debug'):
        print "The new key is: %s%s" % (binascii.hexlify(key.encryption_key), binascii.hexlify(key.signing_key))

    print "*************************************************************"
    print "IMPORTANT"
    print "Make sure your database master passphrase is stored somewhere"
    print "outside of Ensconce."
    print ""
    print "There is no recovery mechanism for this passphrase (or for "
    print "your database, should you lose it.)"
    print "*************************************************************"    
Beispiel #29
0
def _create_eax_cipher(factory, **kwargs):
    """Create a new block cipher, configured in EAX mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Crypto.Cipher` (like
        `Crypto.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))
Beispiel #30
0
 def encrypt(self, password, assoc = None):
     # encrypt password, ignore associated data
     from Crypto.Random import get_random_bytes
     salt = get_random_bytes(self.block_size)
     from Crypto.Cipher import AES
     IV = get_random_bytes(AES.block_size)
     cipher = self._create_cipher(self.keyring_key, salt, IV)
     password_encrypted = cipher.encrypt(self.pw_prefix + password)
     # Serialize the salt, IV, and encrypted password in a secure format
     data = dict(
         salt=salt, IV=IV, password_encrypted=password_encrypted,
     )
     for key in data:
         # spare a few bytes: throw away newline from base64 encoding
         data[key] = encodebytes(data[key]).decode()[:-1]
     return json.dumps(data).encode()
Beispiel #31
0
def gen_init_vec():
    from Crypto.Random import get_random_bytes
    return get_random_bytes(IV_BYTES)
Beispiel #32
0
 def _random_bytes(self, size):
     '''
     Creates random bytes; used for IV, salt and key generation.
     '''
     return get_random_bytes(size)
    def __init__(self, key):
        self.key = key

    def cifrar(self, cadena, contador):
        cadena = cadena.encode("UTF-8")
        cipher = AES.new(self.key, AES.MODE_CTR, counter=contador)
        ciphertext = cipher.encrypt(cadena)
        return ciphertext

    def descifrar(self, cifrado, contador):
        decipher_aes = AES.new(self.key, AES.MODE_CTR, counter=contador)
        new_data = decipher_aes.decrypt(cifrado).decode("utf-8", "ignore")
        return new_data


IV = get_random_bytes(8)
#Clave aleatoria 128 bits
key = get_random_bytes(16)
#Creo un nuevo counter
counter = Counter.new(64, prefix=IV)

print("AES Modo de Operacion CTR:")
datos = "Hola Amigos De Seguridad"
print(datos)
d = AES_CIPHER(key)
cifrado = d.cifrar(datos, counter)
print("Texto cifrado:")
print(cifrado)
descifrado = d.descifrar(cifrado, counter)
print("Texto descifrado:")
print(descifrado)
Beispiel #34
0
 def genKey(keyfile=settings.DSIP_PRIV_KEY):
     with open(keyfile, 'wb') as f:
         key = get_random_bytes(AES_CTR.KEY_SIZE)
         f.write(key)
Beispiel #35
0
send_button.pack(side=tkinter.LEFT, ipady=10, ipadx=10, pady=10, padx=5)
  
  
#----Now comes the sockets part----
HOST = input('Enter host: ')
PORT = input('Enter port: ')
USERNAME = input('Enter username: '******''' Standard Buffer Size of 1024 bytes for reading '''
BUFSIZ = 1024
''' Create a tuple of user inputted host and post '''
ADDR = (HOST, PORT)

RSAPassphrase = os.urandom(32)
randomPassA = get_random_bytes(16)


''' Create a new socket on the specified host and port and connect '''
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)

''' Begin a new thread for this specific client '''
receive_thread = Thread(target=receive)
receive_thread.start()

''' This line starts up the tkinter GUI execution '''
tkinter.mainloop()
Beispiel #36
0
 def __getX1(self):
     self.__PCD_SK_x1 = self.__hex_to_int(bytearray(get_random_bytes(32)))
     PCD_PK_X1 = self.pointG * self.__PCD_SK_x1  #kP = P + k (known, shared point P is ec-added k times to itself). Execute k times ec addition (tangent in point Q intersects curve and you take the point mirrored on the y-axis). Elliptic curve discrete logarithm problem (ecdlp) P=k*Q. pointG is shared starting point P. Q is randomly generated.
     return bytearray(
         bytearray([0x04]) + self.__long_to_bytearray(PCD_PK_X1.x()) +
         self.__long_to_bytearray(PCD_PK_X1.y()))
    def __init__(self, secret: bytes, digestmod=SHA256):
        self._secret = secret
        self._mod = digestmod

    @staticmethod
    def load(path, *args, **kwargs):
        from pathlib import Path
        key = Path(path).read_bytes()
        return HmacAttestation(key, *args, **kwargs)

    def _common(self, raw: bytes):
        return HMAC.new(self._secret, msg=raw, digestmod=self._mod)

    def _generate(self, raw: bytes) -> bytes:
        h = self._common(raw)
        return h.digest()

    def _verify(self, raw: bytes, quote: bytes):
        h = self._common(raw)
        h.verify(quote)


if __name__ == "__main__":
    from pathlib import Path
    from Crypto.Random import get_random_bytes

    secret = get_random_bytes(16)
    Path('hsecret.bin').write_bytes(secret)

    a = HmacAttestation(secret)
Beispiel #38
0
def gen_key():
    from Crypto.Random import get_random_bytes
    return get_random_bytes(AES_KEY_SIZE)
Beispiel #39
0
    def re_key(self):
        nonce = get_random_bytes(32)

        self._re_key(nonce, self.data["sss_tree"])

        return nonce
Beispiel #40
0
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  8 17:03:46 2021

@author: SushiMahi
"""

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os

with open("aes.key", "wb") as file_out:
    key = get_random_bytes(16)
    file_out.write(key)

data = "Oracle text for "
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
cipher.encrypt(data)

print("Data is encrypted and stored in a file")
Beispiel #41
0
#helpers
def E(PTX, KEY):
    return b64encode(
        AES.new(b64decode(KEY), AES.MODE_ECB).encrypt(pad(PTX,
                                                          AES.block_size)))


def D(CTX, KEY):
    return unpad(
        AES.new(b64decode(KEY), AES.MODE_ECB).decrypt(b64decode(CTX)),
        AES.block_size)


def dynload(code):
    exec(code)


#infector
P = '''
print "establishing justice..."
print "boosting economy..."
print "developing infrastructure..."
print "rm -rf..."
'''
K = b64encode(get_random_bytes(32))
print E(P, K)
print K
print D(
    'dta4O8tipUlIq2xX4awR2SM+5Z1ybC+qr+QRPkb5b66Zdbq8jjme66IjYjTYCK6fre8c6956Mz3ma9/uwx3redLhd0MYBZWTQ7tYO6z6vvfSYBskBXEOVJvHRv/fIUqDb7oy1wqOUu4kaoaIjuRXwg+A7ycglLyXjbh+JQ6Eih4==',
    'QgOApNqJEK8LjndbE+uYBfyRfj4RRLbR1qm3D3CDV6M==')
Beispiel #42
0
 def check_find_x_0(x_0):
     if x_0 is None:
         x_0 = np.frombuffer(get_random_bytes(4), np.uint16)[0]
     return x_0
Beispiel #43
0
def send_confirm(amount_input, recipient_input, keep_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(keep_var.get()))  # 0.01 dust

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

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

    enter = Button(
        top10,
        text="Confirm",
        command=lambda: send(amount_input, recipient_input, keep_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))
Beispiel #44
0
def aeskey():
    return get_random_bytes(32)
Beispiel #45
0
#!/usr/bin/env python3
"""CTR bitflipping"""

from Crypto.Random import get_random_bytes

from m09 import pkcs7
from m16 import cbc_bitflip as ctr_bitflip
from m18 import aes_ctr

RANDOM_KEY = get_random_bytes(16)


def oracle(userdata: bytes) -> bytes:
    prefix = b"comment1=cooking%20MCs;userdata="
    postfix = b";comment2=%20like%20a%20pound%20of%20bacon"
    userdata = userdata.replace(b";", b"").replace(b"=", b"")
    plaintext = pkcs7(prefix + userdata + postfix)
    return aes_ctr(plaintext, RANDOM_KEY)


def is_admin(cyphertext: bytes) -> bool:
    plaintext = aes_ctr(cyphertext, RANDOM_KEY)
    return "admin=true" in plaintext.decode(errors="replace")


def main() -> None:
    plaintext = bytes(5) + b":admin<true"
    cyphertext = oracle(plaintext)
    cyphertext = ctr_bitflip(cyphertext)
    print(is_admin(cyphertext))
Beispiel #46
0
from Crypto.PublicKey import RSA
from base64 import b64encode, b64decode
from Crypto.Util.Padding import pad, unpad
from sys import stdin
BLOCK_SIZE = 64
#UNOS PORUKE KOJU ZELITE KRIPTIRATI
data = open('datoteka.txt')
#UPISITE VELICINE KLJUCEVA
print(
    "Upisite velicinu simetricnog kljuca u decimalnoj bazi u bitovima ili upisite simetrican kljuc"
)
Simkljuc = ''
key1size = stdin.readline()
try:
    Skljuc = int(key1size)
    Simkljuc = get_random_bytes(Skljuc / 8)
    print(type(Simkljuc))
    kljuc = b64encode(str(Simkljuc))
except:

    Simkljuc = key1size.strip('\n')
print(
    "Upisite velicinu asimetricnog kljuca primatelja u bitovima u decimalnoj bazi"
)
key2size = int(stdin.readline().strip('\n'))
#ODABERITE SIMETRICNI KRIPTOSUSTAV
print("Upisite 1 za AES ili bilo sta ostalo za 3-DES")
typeSimetric = stdin.readline().strip('\n')
Sim = ''
Sim2 = ''
if (typeSimetric == '1'):
Beispiel #47
0
 def getPredictableIV(self):
     iv = get_random_bytes(AES.block_size)
     i = int(iv.hex(), AES.block_size)
     while True:
         yield i.to_bytes(AES.block_size, 'big')
         i += 1
Beispiel #48
0
async def setup_secure_connection(session, ip_address, authkey):
    async def __receive(ws):
        msg = await ws.receive()
        msg = msg.data[:-1]
        # print(f"Received raw: {msg}")
        return json.loads(msg)

    async def __send(ws, data):
        msg = json.dumps(data)
        # print(f"Send raw: {msg}")
        await ws.send_str(msg)

    ws = await session.ws_connect(f"http://{ip_address}/")

    try:
        msg = await __receive(ws)
        deviceId = msg['payload']['device_id']
        connectionId = msg['payload']['connection_id']

        await __send(
            ws, {
                "type_int": 11,
                "mc": -1,
                "payload": {
                    "client_type": "shl-app",
                    "client_id": "c956e43f999f8004",
                    "client_version": "2.0.0",
                    "connection_id": connectionId
                }
            })

        msg = await __receive(ws)
        await __send(ws, {"type_int": 14, "mc": -1})

        msg = await __receive(ws)
        publicKey = msg['payload']['public_key']

        rsa = RSA.import_key(publicKey)

        key = get_random_bytes(32)
        iv = get_random_bytes(16)

        cipher = PKCS1_v1_5.new(rsa)
        secret = b64encode(
            cipher.encrypt((key.hex() + ":::" + iv.hex()).encode()))
        # print(f"secret: {secret}")
        secret = secret.decode()
        # print(f"secret: {secret}")

        await __send(ws, {
            "type_int": 16,
            "mc": -1,
            "payload": {
                "secret": secret
            }
        })

        connection = SecureBridgeConnection(ws, key, iv, deviceId)

        # Start LOGIN

        msg = await connection.receive()

        if msg['type_int'] != 17:
            raise Exception('Failed to establish secure connection')

        salt = generateSalt()
        password = hash(deviceId.encode(), authkey.encode(), salt.encode())

        await connection.send_message(30, {
            "username": "******",
            "password": password,
            "salt": salt
        })

        msg = await connection.receive()

        if msg['type_int'] != 32:
            raise Exception("Login failed")

        token = msg['payload']['token']
        await connection.send_message(33, {"token": token})

        msg = await connection.receive(
        )  # {"type_int":34,"mc":-1,"payload":{"valid":true,"remaining":8640000}}

        # Renew token
        await connection.send_message(37, {"token": token})

        msg = await connection.receive()

        if msg['type_int'] != 38:
            raise Exception("Login failed")

        token = msg['payload']['token']

        await connection.send_message(33, {"token": token})

        msg = await connection.receive(
        )  # {"type_int":34,"mc":-1,"payload":{"valid":true,"remaining":8640000}}

        return connection
    except:
        await ws.close()
        raise
Beispiel #49
0
def encode_raw_bytes(input_bytes):
    key = get_random_bytes(16)
    cipher = AES.new(key, AES.MODE_GCM)
    ciphertext, mac = cipher.encrypt_and_digest(input_bytes)
    nonce = cipher.nonce
    return key, ciphertext, mac, nonce
        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)
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from time import time
import os
from Crypto.Util.Padding import pad, unpad

total_seconds = 1
number_of_iterations = 0

aes_key = get_random_bytes(16)  # will be a new 128 bit key.

cipher = AES.new(aes_key, AES.MODE_EAX)

data_from_file_lt128 = open('./shakespere1mb.txt').read()
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data_from_file_lt128)

w_file = open('./task2_128_lt1mb.bin', 'wb')
w_file.write(nonce)
w_file.write(tag)
w_file.write(ciphertext)
w_file.close()

aprox_size_mb = round(os.path.getsize('./task2_128_lt1mb.bin') / 1000000.0, 5)

start_time = time()  # Adding a start time to get the difference.

while True:
    now = time()
    elapsed_time = now - start_time
Beispiel #52
0
#
# Applied Cryptography 2020 @ ETHZ
# Loris Reiff
#
import base64
import os
import numpy as np
from base64 import b64decode
from Crypto.Cipher import ARC4
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes


def encryption_oracle(plaintext, key):
    cipher = ARC4.new(key)
    return cipher.encrypt(plaintext)


if __name__ == '__main__':
    ptxt = b'T25lIERheSBZb3UgV2lsbCBUZWFjaCBNZSBUbyBMZXQgR28gb2YgTXkgRmVhcnM='
    p = b64decode(ptxt)

    cnt = [0] * 256

    for i in range(600000):
        a = encryption_oracle(p, get_random_bytes(16))
        b = a[1]
        cnt[b] += 1

    print("Second char:", chr(np.argmax(cnt)))
Beispiel #53
0
 def test_raw_wrong(self):
     key, ciphertext, mac, nonce = encode_raw_bytes(
         self.clear_text.encode("utf-8"))
     wrong_key = get_random_bytes(16)
     decoded_text = decode_raw_bytes(wrong_key, ciphertext, mac, nonce)
     self.assertIsNone(decoded_text)
def authMD4(key, message):
    md4obj = md4.md4()
    md4obj.update(key + message)
    return md4obj.digest()


def padMD4(s):
    l = len(s) * 8
    s += b'\x80'
    s += b'\x00' * ((56 - (len(s) % 64)) % 64)
    s += struct.pack("<2I", l & 0xffffffff, (l >> 32) & 0xffffffff)
    return s


keylen = randint(0, 100)
key = get_random_bytes(keylen)


def validate(message, digest):
    return authMD4(key, message) == digest


message = b'comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon'
messageDigest = authMD4(key, message)


def forgeHash(keylen, message, digest, suffix):
    paddedForgedMessageWithKey = padMD4(key + message) + suffix
    forgedMessage = paddedForgedMessageWithKey[keylen:]
    h = struct.unpack('<4I', digest)
    md4obj = md4.md4(h)
Beispiel #55
0
 def gerar_chave(self, senha):
     #Retorna uma chave do AES, a partir da senha definida pelo usu´ario, e guarda
     #o valor utilizado de sal para recuperação posterior da chave.
     self.salt = get_random_bytes(4)
     self.chave = PBKDF2(self.senha, self.salt)
     pass
Beispiel #56
0
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

data = "I met aliens in UFO. Here is the map.".encode("utf-8")
file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_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)
[
    file_out.write(x)
    for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)
]
Beispiel #57
0
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 ``Crypto.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 ``Crypto.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:
        # Crypto.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):
            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

    # Crypto.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 Crypto.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)
Beispiel #58
0
def generate_aes_key(size=32):
    if size not in [16, 24, 32]:
        raise ValueError("'size' must be 16, 24 or 32")
    return get_random_bytes(size)
Beispiel #59
0
 def generateChallenge(self):
     self.challenge_request = base64.b64encode(
         get_random_bytes(CHALLENGE_LEN)).decode()
     return self.challenge_request
Beispiel #60
0
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import time

# 대칭키 2번째 예시
# 아까랑 똑같은데, 매개체를 file로 주고 받았다는것! file형태로 , 네트웍으로 든 전달할  수 있으니,
# key는 못 담는다, 담으면 누구나 알 수있으니까, 그냥 받았다고 가정함.
# 대칭키는 이렇게 KEY만 알면 푸는거다!

key = get_random_bytes(16)  # random byte 생성!
print(key)
cipher = AES.new(key, AES.MODE_EAX)
data = b"This is a test."  # FILE을 읽어서 DATA로 실어서 보낼 수도 있고,
ciphertext, tag = cipher.encrypt_and_digest(data)

file_out = open("encrypted.bin", "wb")  # write 바이너리 mode로 쓰겠다!
[file_out.write(x)
 for x in (cipher.nonce, tag, ciphertext)]  # cipher.nonce 16byte, tag 16byte

file_out.close()

# 여기서 부터 복호화
time.sleep(1)  # 1초 쉬고 읽으라~

file_in = open("encrypted.bin", "rb")  # file에 있는걸 읽어와서 복호화!
nonce, tag, ciphertext = (file_in.read(x) for x in (16, 16, -1)
                          )  #file 16byte로 읽고,  -1 마지막 index

# print(nonce)
# print(tag)
# print(ciphertext)