예제 #1
0
    def decrypt_master_key(self, master_password, data):
        '''
        dkLen=32 corresponds to AES256 key (32 bytes).
        Return (kdf_salt, hmac_salt, encrypted data, hmac(kdf_salt, hmac_salt, encrypted data)).
        hashlib.sha3_256 produces 32 bytes hash.

        :Arguments:
            master_password: string or byte string
            data: bytes

        :Returns:
            bytes

        [
        PBKDF2 :Arguments:
             password: string or byte string
             salt: string or byte string
             dkLen: integer
             count: integer
             prf: callable
             hmac_hash_module: module

        PBKDF2 :Returns:
            A byte string of length ``dkLen`` that can be used as key material.
        ]
        '''

        kdf_salt = data[:self.SALT_SIZE]
        hmac_salt = data[self.SALT_SIZE:self.SALT_SIZE * 2]

        encryption_key = KDF.PBKDF2(
            master_password,
            kdf_salt,
            dkLen=self.DK_LEN,
            count=self.KDF_COUNT,
            hmac_hash_module=self.PBKDF_HMAC_HASH_MODULE)
        hmac_key = KDF.PBKDF2(master_password,
                              hmac_salt,
                              dkLen=self.DK_LEN,
                              count=self.KDF_COUNT,
                              hmac_hash_module=self.PBKDF_HMAC_HASH_MODULE)

        hmac_ = hmac.new(hmac_key,
                         data[:-self.HMAC_HASH_SIZE],
                         digestmod=self.HMAC_DIGESTMOD).digest()

        if hmac_ != data[-self.HMAC_HASH_SIZE:]:
            raise Exception('Bad hmac!')

        master_key = self.decrypt(
            encryption_key, data[self.SALT_SIZE * 2:-self.HMAC_HASH_SIZE])
        return master_key
예제 #2
0
def derive_hkdf_key(
    master_key: bytes,
    dklen: int,
    hashalgo: typing.Union[str, BaseHash],
    salt: bytes,
    cipher_ctx: bytes = b"enc-key",
    auth_ctx: bytes = b"auth-key",
) -> typing.Tuple[bytes, bytes]:
    """Derive key materials for HMAC from given master key.

    Args:
        master_key (bytes): The key used to derive the keys from.
        dklen (int): Desired lenth of the derived key.
        hashalgo (str, BaseHash): The name of the hash algorithm.
        salt (bytes): The salt to use.
        cipher_ctx (bytes): Context for cipher.
        auth_ctx (bytes): Context for HMAC.

    Returns:
        tuple[bytes, bytes]: A pair of *cipher key* and *MAC key*.
    """
    if isinstance(hashalgo, str):
        hash_ = Hash.new(hashalgo)
    elif isinstance(hashalgo, BaseHash):
        # use our hashalgo
        hash_ = hashalgo.new()
    else:
        raise TypeError(
            "hashalgo must be a str or an object implementing BaseHash."
        )

    key = KDF.HKDF(
        master=master_key,
        key_len=dklen,
        salt=salt,
        hashmod=hash_,
        num_keys=1,
        context=cipher_ctx,
    )

    hkey = KDF.HKDF(
        master=master_key,
        key_len=hash_.digest_size,
        salt=salt,
        hashmod=hash_,
        num_keys=1,
        context=auth_ctx,
    )
    return key, hkey
예제 #3
0
    def encrypt_master_key(self, master_password, master_key):
        '''
        dkLen=32 corresponds to AES256 key (32 bytes).
        Return (kdf_salt, hmac_salt, encrypted data, hmac(kdf_salt, hmac_salt, encrypted data)).
        hashlib.sha3_256 produces 32 bytes hash.

        :Arguments:
            master_password: string or byte string
            master_key: bytes

        :Returns:
            bytes (total 112 bytes in lenght)

        [
        PBKDF2 :Arguments:
             password: string or byte string
             salt: string or byte string
             dkLen: integer
             count: integer
             prf: callable
             hmac_hash_module: module

        PBKDF2 :Returns:
            A byte string of length ``dkLen`` that can be used as key material.
        ]
        '''

        kdf_salt = self.get_salt()
        hmac_salt = self.get_salt()
        iv = self.get_iv()

        encryption_key = KDF.PBKDF2(
            master_password,
            kdf_salt,
            dkLen=self.DK_LEN,
            count=self.KDF_COUNT,
            hmac_hash_module=self.PBKDF_HMAC_HASH_MODULE)
        hmac_key = KDF.PBKDF2(master_password,
                              hmac_salt,
                              dkLen=self.DK_LEN,
                              count=self.KDF_COUNT,
                              hmac_hash_module=self.PBKDF_HMAC_HASH_MODULE)
        encrypted_master_key = self.encrypt(encryption_key, iv, master_key)

        data = kdf_salt + hmac_salt + encrypted_master_key
        data += hmac.new(hmac_key, data,
                         digestmod=self.HMAC_DIGESTMOD).digest()
        return data
예제 #4
0
def encrypt(plaintext, key, keylen=KEYLEN):
    """Encrypt bytes using AES-CBC with keys of length `keylen` (defaults to
    KEYLEN: 256 bits).

    Key is passed in KDF `PBKDF2` in order to protect weak keys against brute
    force attacks.

    @param plaintext:  Data to be encrypted.
    @type  plaintext:  bytes

    @param key:  Encryption passphrase.
    @type  key:  str, bytes

    @param keylen:  Length of the key to use in bytes. Can be either 16, 24 or
                    32.
    @type  keylen:  str, bytes

    @return:  The produced ciphertext.
    @rtype :  bytes

    @raise ValueError: Incorrect padding. Happens if passphrase is incorrect.
    """
    salt = Random.new().read(AES.block_size)
    iv = Random.new().read(AES.block_size)
    key = KDF.PBKDF2(key, salt, dkLen=keylen)
    plaintext = Padding.pad(plaintext, AES.block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv=iv)
    return base64.b64encode(salt + iv + cipher.encrypt(plaintext))
예제 #5
0
def decrypt(ciphertext, key, keylen=KEYLEN):
    """Decrypt bytes using AES-CBC with keys of length `keylen` (defaults to
    KEYLEN: 256 bits).

    @param ciphertext:  Data to be decrypted.
    @type  ciphertext:  bytes

    @param key:  Encryption passphrase.
    @type  key:  str, bytes

    @param keylen:  Length of the key to use in bytes. Can be either 16, 24 or
                    32.
    @type  keylen:  str, bytes

    @return:  The decrypted ciphertext.
    @rtype :  bytes

    @raise ValueError: Incorrect padding. Happens if passphrase is incorrect.
    """
    ciphertext = base64.b64decode(ciphertext)
    salt = ciphertext[:AES.block_size]
    iv = ciphertext[AES.block_size:2 * AES.block_size]
    key = KDF.PBKDF2(key, salt, dkLen=keylen)
    cipher = AES.new(key, AES.MODE_CBC, iv=iv)
    return Padding.unpad(cipher.decrypt(ciphertext[2 * AES.block_size:]),
                         AES.block_size)
예제 #6
0
 def __init__(self, key):
     self.share_key = key
     #set counter for sending and receiving
     self.sender_counter = 0
     self.receiver_counter = 0
     #derive the encryption key and authentication key from share_key
     self.encry_key = (KDF.HKDF(self.share_key,
                                salt=None,
                                key_len=32,
                                hashmod=SHA256,
                                num_keys=2,
                                context=None))[0]
     self.auth_key = (KDF.HKDF(self.share_key,
                               salt=None,
                               key_len=32,
                               hashmod=SHA256,
                               num_keys=2,
                               context=None))[1]
예제 #7
0
파일: ffdb.py 프로젝트: g-insana/ffdb.py
def derive_key(passphrase, keysize):
    """
    derive key of desired bytesize from passphrase
    """
    key = KDF.PBKDF2(passphrase, SALT, keysize)
    if len(key) != keysize:
        msg = "Attention! Something has gone wrong when deriving key from passphrase!"
        raise RuntimeError(msg)
    ks2cipher = {16: 'aes128', 24: 'aes192', 32: 'aes256'}
    cipher_name = ks2cipher[keysize]
    return cipher_name, key
예제 #8
0
 def __init__(self):
     self.name = 'Bob'
     self.key = RSA.generate(1024)
     self.publicKey = self.key.publickey()
     self.CAdic = {}
     self.Sb = 10
     self.share_key = ''
     self.certificate = None
     self.sender_counter = 0
     self.receiver_counter = 0
     self.encry_key = (KDF.HKDF(self.share_key,
                                salt=None,
                                key_len=32,
                                hashmod=SHA256,
                                num_keys=2,
                                context=None))[0]
     self.auth_key = (KDF.HKDF(self.share_key,
                               salt=None,
                               key_len=32,
                               hashmod=SHA256,
                               num_keys=2,
                               context=None))[1]
예제 #9
0
파일: auth.py 프로젝트: jedrecord/confluent
def _apply_pbkdf(passphrase, salt):
    return KDF.PBKDF2(passphrase, salt, 32, 10000,
                      lambda p, s: hmac.new(p, s, hashlib.sha256).digest())
예제 #10
0
def kdf(password, salt):
    return KDF.PBKDF2(password, salt, dkLen=32, count=2000)
예제 #11
0
파일: __init__.py 프로젝트: r4nx/rcrypt
 def __init__(self, key, salt):
     self.__key = KDF.PBKDF2(password=key,
                             salt=salt.encode(),
                             dkLen=32,
                             count=10000,
                             prf=_prf)
예제 #12
0
        "--passphrase",
        help="Pssphrase as an ASCII string to use to generate an encryption key"
    )
    parser.add_argument(
        "--salt",
        help=
        "Salt to use with KDF for generating a key from a passphrase. Must be a 128-bit hex string beginning with 0x"
    )
    parser.add_argument("--metadata_file",
                        help="File to hold metadata",
                        required=True)
    args = parser.parse_args()
    encryption_key = ''
    print "Starting key"
    if args.encryption_key is not None:
        encryption_key = binascii.unhexlify(args.encryption_key)
    else:
        if args.salt is None:
            print "A salt is required when using a passphrase"
            sys.exit(-1)
        encryption_key = KDF.scrypt(args.passphrase, args.salt, 16, 16384, 8,
                                    1)
    print "Finished with Key"
    FUSE(EncryptedFS(args.storage_dir, encryption_key, args.metadata_file),
         args.mount_point,
         nothreads=True,
         foreground=True,
         big_writes=True,
         max_read=1000000000,
         max_write=1000000000)
예제 #13
0
 def generate_kd(self, password: str, salt: str):
     dk = KDF.scrypt(password, salt, self.__dk_len, self.__n, self.__r,
                     self.__p)
     return dk
예제 #14
0
 def generate_kd(self, password: bytes, salt: bytes):
     dk = KDF.scrypt(password, salt, self.dk_len, self.n, self.r, self.p)
     return dk
 def generate_kd(self, password: str, salt: str):
     dk = KDF.scrypt(password, salt, self.dkLen, self.n, self.r, self.p)
     return dk
예제 #16
0
 def generate_kd(self, password: bytes or str, salt: bytes or str) -> bytes:
     dk = KDF.scrypt(password, salt, self.__dk_len, self.__n, self.__r,
                     self.__p)
     return dk
예제 #17
0
#print decryptor.decrypt_and_verify(binascii.unhexlify('16042f8a8df1c09dee68e56a1a1d9157ce8aaa8490d12a99e538f499eabab47b0f3578c16aecd9e4bbb0d8f52f0e4f0e'), tag)
#print decryptor.decrypt(binascii.unhexlify('16042f8a8df1c09dee68e56a1a1d9157ce8aaa8490d12a99e538f499eabab47b0f3578c16aecd9e4bbb0d8f52f0e4f0e'))
#16042f8a8df1c09dee68e56a1a1d9157
#ce8aaa8490d12a99e538f499eabab47b
#0f3578c16aecd9e4bbb0d8f52f0e4f0f

#===============================================
#print len(hashlib.sha256(format(0, 'x')).hexdigest()[:16])

from Cryptodome.Protocol import KDF
from Crypto.Hash import SHA256
master = "abcd"
array = (KDF.HKDF(master,
                  salt=None,
                  key_len=32,
                  hashmod=SHA256,
                  num_keys=2,
                  context=None))
#print len(array[0].encode('hex')), (binascii.hexlify(array[1]))
#
#print (("Msg from alice to bob").encode('hex'))
#print (("Msg from alice to bob").encode('hex') + (16 - len("Msg from alice to bob") % 16)*'80')


class Peer(object):
    def __init__(self, key):
        self.share_key = key
        #set counter for sending and receiving
        self.sender_counter = 0
        self.receiver_counter = 0
        #derive the encryption key and authentication key from share_key