示例#1
0
    def AES_encrypt_Login(self, user, psw, returnOrdType=3):
        assert (type(user)) == str
        assert (type(psw)) == str

        logger  = self._SetLogger(package=__name__)
        # if isinstance(user, str): b_user = user.encode('utf-8') # covert to bytes
        # if isinstance(psw,  str): b_psw  = psw.encode('utf-8') # covert to bytes
        # b_user = user.encode('utf-8') # covert to bytes
        # b_psw  = psw.encode('utf-8') # covert to bytes



        logger.info('   encrypting password with user value')
        b_key       = self._prepareKey(user)
        nounce      = Random.get_random_bytes(16)
        cipher      = AES.new(b_key, AES.MODE_CFB, nounce)

            # - text to be ciphered
        ciphertext  = cipher.encrypt(psw.encode('utf-8')) # covert to bytes
            # - encrypting della psw
        b_cipheredPsw = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
        pswLen = len(b_cipheredPsw)
            # - cipheredPsw is bytearray '''
        h_cipheredPsw = self.bytesToHex(b_cipheredPsw) # hex contenuto in string
        logger.info('   h_cipheredPsw  %s' % h_cipheredPsw)






            # crypting dello user, usiamo la HexPSW come Key
        logger.info('   encrypting user value with password in strHex format')
        b_key       = self._prepareKey(b_cipheredPsw)
        nounce      = Random.get_random_bytes(16)
        cipher      = AES.new(b_key, AES.MODE_CFB, nounce)

            # - text to be ciphered
        ciphertext  = cipher.encrypt(user.encode('utf-8')) # convert to bytes
            # - encrypting dello user
        b_cipheredUser = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
            # - cipheredPsw is bytearray '''
        h_cipheredUser = self.bytesToHex(b_cipheredUser) # hex contenuto in string
        logger.info('   h_cipheredUser %s' % h_cipheredUser)


        '''
            costruzione del dato di ritorno composto dai dati HEX di PSW + USER con
            l'aggiunta della lunghezza della PSW calcolata sul bytes_data.
        '''
        myData = h_cipheredPsw + h_cipheredUser + '{0:02x}'.format(pswLen)


        logger  = self._SetLogger(package=__name__, exiting=True)
        return myData
示例#2
0
    def create_entry(self, group = None, title = "", image = 1, url = "",
                     username = "", password = "", comment = "",
                     y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
                     s = 59):
        """This method creates a new entry.
        
        The group which should hold the entry is needed.

        image must be an unsigned int >0, group a v1Group.
        
        It is possible to give an expire date in the following way:
            - y is the year between 1 and 9999 inclusive
            - mon is the month between 1 and 12
            - d is a day in the given month
            - h is a hour between 0 and 23
            - min_ is a minute between 0 and 59
            - s is a second between 0 and 59

        The special date 2999-12-28 23:59:59 means that entry expires never.
        
        """
        
        if (type(title) is not str or
            type(image) is not int or image < 0 or
            type(url) is not str or
            type(username) is not str or
            type(password) is not str or
            type(comment) is not str or
            type(y) is not int or
            type(mon) is not int or
            type(d) is not int or
            type(h) is not int or
            type(min_) is not int
            or type(s) is not int or
            type(group) is not v1Group):
            raise KPError("One argument has not a valid type.")
        elif group not in self.groups:
            raise KPError("Group doesn't exist.")
        elif (y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or
              h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0):
            raise KPError("No legal date")
        elif (((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or
                mon == 10 or mon == 12) and d > 31) or
               ((mon == 4 or mon == 6 or mon == 9 or mon == 11) and d > 30) or
               (mon == 2 and d > 28)):
            raise KPError("Given day doesn't exist in given month")

        Random.atfork()
        uuid = Random.get_random_bytes(16)
        entry = v1Entry(group.id_, group, image, title, url, username,
                         password, comment, 
                         datetime.now().replace(microsecond = 0),
                         datetime.now().replace(microsecond = 0),
                         datetime.now().replace(microsecond = 0),
                         datetime(y, mon, d, h, min_, s),
                         uuid)
        self.entries.append(entry)
        group.entries.append(entry)
        self._num_entries += 1
        return True
 def __init__(self, module, params):
     from Cryptodome import Random
     unittest.TestCase.__init__(self)
     self.module = module
     self.iv = Random.get_random_bytes(module.block_size)
     self.key = b(params['key'])
     self.plaintext = 100 * b(params['plaintext'])
     self.module_name = params.get('module_name', None)
示例#4
0
    def __init__(self, filepath=None, password=None, keyfile=None, 
                 read_only=False, new = False):
        """ Initialize a new or an existing database.

        If a 'filepath' and a 'masterkey' is passed 'load' will try to open
        a database. If 'True' is passed to 'read_only' the database will open
        read-only. It's also possible to create a new one, just pass 'True' to
        new. This will be ignored if a filepath and a masterkey is given this
        will be ignored.
        
        """

        if filepath is not None and password is None and keyfile is None:
            raise KPError('Missing argument: Password or keyfile '
                          'needed additionally to open an existing database!')
        elif type(read_only) is not bool or type(new) is not bool:
            raise KPError('read_only and new must be bool')
        elif ((filepath is not None and type(filepath) is not str) or
              (type(password) is not str and password is not None) or
              (type(keyfile) is not str and keyfile is not None)):
            raise KPError('filepath, masterkey and keyfile must be a string')
        elif (filepath is None and password is None and keyfile is None and 
              new is False):
            raise KPError('Either an existing database should be opened or '
                          'a new should be created.')

        self.groups = []
        self.entries = []
        self.root_group = v1Group()
        self.read_only = read_only
        self.filepath = filepath
        self.password = password
        self.keyfile = keyfile

        # This are attributes that are needed internally. You should not
        # change them directly, it could damage the database!
        self._group_order = []
        self._entry_order = []
        self._signature1 = 0x9AA2D903
        self._signature2 = 0xB54BFB65
        self._enc_flag = 2
        self._version = 0x00030002
        self._final_randomseed = ''
        self._enc_iv = ''
        self._num_groups = 1
        self._num_entries = 0
        self._contents_hash = ''
        Random.atfork()
        self._transf_randomseed = Random.get_random_bytes(32)
        self._key_transf_rounds = 150000

        # Due to the design of KeePass, at least one group is needed.
        if new is True:
            self._group_order = [("id", 1), (1, 4), (2, 9), (7, 4), (8, 2),
                                 (0xFFFF, 0)]
            group = v1Group(1, 'Internet', 1, self, parent = self.root_group)
            self.root_group.children.append(group)
            self.groups.append(group)
示例#5
0
def generate_nonce(size):
    """ Generate a secure random for cryptographic use.

    Args:
        size: Number of bytes for the nonce

    Returns: Generated random bytes
    """
    return Random.get_random_bytes(size)
示例#6
0
    def _generate_key_and_iv(encalg, cek="", iv=""):
        if cek and iv:
            return cek, iv

        try:
            _key = Random.get_random_bytes(ENCALGLEN1[encalg])
            _iv = Random.get_random_bytes(12)
        except KeyError:
            try:
                _key = Random.get_random_bytes(ENCALGLEN2[encalg])
                _iv = Random.get_random_bytes(16)
            except KeyError:
                raise Exception("Unsupported encryption algorithm %s" % encalg)
        if cek:
            _key = cek
        if iv:
            _iv = iv

        return _key, _iv
示例#7
0
    def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataTYPE='bytes'):
        # print (type (clearMsg), clearMsg)
        if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes
        # if isinstance(clearMsg, str): clearMsg = bytes(clearMsg, 'utf-8') # covert to bytes
        # print (type (clearMsg), clearMsg)

        nounce      = Random.get_random_bytes(16)
        cipher      = AES.new(self._key, AES.MODE_CFB, nounce)
        ciphertext  = cipher.encrypt(clearMsg)

        retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)

        if   returnDataTYPE == 'hex':       return self.bytesToHex(retValue)
        elif returnDataTYPE == 'base64':    return self.bytesToBase64(retValue)
        else:                               return bytes(retValue)
示例#8
0
    def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataType='bytes'):
        if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes

        nounce      = Random.get_random_bytes(16)
        cipher      = AES.new(self._key, AES.MODE_CFB, nounce)
        ciphertext  = cipher.encrypt(clearMsg)

        retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
        ''' retValue is bytearray '''

        if   returnDataType == 'hex-str':       return self.bytesToHex(retValue) # hex contenuto in string
        elif returnDataType == 'base64':    return self.bytesToBase64(retValue)


        return bytes(retValue)
示例#9
0
    def PKCS1_OAEP_AES_encrypt(self, data, outFile):


            # recipient_key = Crypto.PublicKey.RSA.import_key(open("receiver.pem").read())
        recipient_key = self._privateKey
        session_key = Random.get_random_bytes(32)

            # 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)

            # creazione del file con i dati crypted
        print ('file {FILE} has been created with encrypted data.'.format(FILE=outFile))
        file_out = open(outFile, "wb")
        file_out.write(cipher_rsa.encrypt(session_key))
        [ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ]

        return ciphertext
示例#10
0
 def generate_random_private_key():
     private_key = Random.get_random_bytes(64).hex()[:64]
     print('Result is:')
     print('\t', private_key)
示例#11
0
def generateEncryptingKey(size=DEFAULT_AES_KEY_SIZE):
    if size not in _AES_POSSIBLE_SIZES:
        raise ValueError('Only possible key sizes are %s.' %
                         ', '.join(_AES_POSSIBLE_SIZES))

    return Random.get_random_bytes(size // 8)
示例#12
0
#!/usr/bin/python3

import argparse

import Cryptodome.Cipher.DES3 as DES3
import Cryptodome.Random as Random

#data = b'This is the first message that I have encrypted using PyCryptodome!!'
data = Random.get_random_bytes(16777216)
while True:
    try:
        key = DES3.adjust_key_parity(Random.get_random_bytes(24))
        break
    except ValueError:
        pass
nonce = Random.get_random_bytes(16)


def run_3DES(num):
    for i in list(range(num)):
        cipher = DES3.new(key, DES3.MODE_EAX, nonce)
        ciphertext = cipher.encrypt(data)
    return


def main():
    num = 1

    parser = argparse.ArgumentParser()

    parser.add_argument("--num",
示例#13
0
def get_random_str(length):
    return Random.get_random_bytes(length).hex()[:length]
示例#14
0
 def __init__(self, admin):
     self.aesEcb = AES.new(Random.get_random_bytes(AES.block_size),
                           AES.MODE_ECB)
     self.userIdDict = {admin: 10}
     self.adminEmail = admin
示例#15
0
#!/usr/bin/python3

import Cryptodome.Cipher.AES as AES
import Cryptodome.Cipher.DES as DES
import Cryptodome.Cipher.DES3 as DES3
import Cryptodome.Cipher.Blowfish as Blowfish
import Cryptodome.Random as Random

import Crypto.Cipher.XOR as XOR

#data = b'This is the first message that I have encrypted using PyCryptodome!!'
data = Random.get_random_bytes(4194304)


def to_hex(byte_string):
    return ":".join("{:02x}".format(c) for c in byte_string)


def run_AES256():
    key = Random.get_random_bytes(32)
    nonce = Random.get_random_bytes(16)

    print("=================")
    print("Encrypting with AES-256")
    print("Key: ", to_hex(key))
    print("Nonce: ", to_hex(nonce))

    cipher = AES.new(key, AES.MODE_EAX, nonce)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    print("MAC: ", to_hex(tag))
    #print("Cleartext: ", to_hex(data))
示例#16
0
    result = ecb_encode(text, key)
    return (result)


def bs(result):
    length = len(result)
    a = 1
    l = length
    while (l <= length):
        d = "A" * a
        l = len(encryption_oracle(d))
        a = a + 1
    return (l - length)


def create_account():
    result = profile_for("*****@*****.**")
    BS = bs(result)
    b1 = BS - len("email=")
    b2 = BS - len("&uid=10&role=")
    email = "A" * (b1 + b2)
    re = profile_for(email)[0:2 * BS]
    admin = "A" * b1 + pad(bytearray("admin", 'utf-8'), BS).decode('utf-8')
    ra = profile_for(admin)[BS:2 * BS]
    tada = re + ra
    return (tada)


key = Random.get_random_bytes(16)
print(ecb_decode(create_account(), key))
示例#17
0
def get_random_bytes(length: int) -> bytes:
    return Random.get_random_bytes(length)
示例#18
0
def get_random_hex_str(length: int) -> str:
    return Random.get_random_bytes(length).hex()[:length]
示例#19
0
 def runTest(self):
     """Cryptodome.Random.new()"""
     # Import the Random module and try to use it
     from Cryptodome import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Cryptodome.Random import random
     x = random.getrandbits(16*8)
     y = random.getrandbits(16*8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x>y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1,10):
         x = random.randrange(start,stop,step)
         y = random.randrange(start,stop,step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1,2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start,stop)
     y = random.randint(start,stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1,1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = range(10000)
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
     self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = range(500)
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
        self.assertEqual(seq[i] in x, True)
        self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "11")
     self.assertRaises(TypeError, random.shuffle, (1,2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
         # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1,2,3), 1)
     self.assertEqual(z[0] in (1,2,3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(range(3), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
             z = random.sample(b("123"), 1)
             self.assertEqual(z[0] in b("123"), True)
             z = random.sample(bytearray(b("123")), 1)
             self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
示例#20
0
    if (pos == -1): return False
    return True


def bs(result):
    length = len(result)
    a = 1
    l = length
    while (l <= length):
        d = "A" * a
        l = len(func1(d))
        a = a + 1
    return (l - length)


def brk():
    result = func1("")
    BS = bs(result)
    pre = 32
    inp = "A" * ((pre % BS) + BS) + "AadminAtrue"
    result1 = func1(inp)
    result1[pre] = result1[pre] ^ ord("A") ^ ord(";")
    result1[pre + 6] = result1[pre + 6] ^ ord("A") ^ ord("=")
    print(func2(result1))


BS = 16
key = Random.get_random_bytes(16)
IV = Random.get_random_bytes(BS)
brk()
示例#21
0
 def __init__(self, key=None, iv=None):
     self.key = key if key else Random.get_random_bytes(AES.block_size)
     self.iv = iv if iv else Random.get_random_bytes(AES.block_size)
     self.ecb = AES.new(self.key, AES.MODE_ECB)
示例#22
0
 def generate_key():
     key = Random.get_random_bytes(32)
     return key
示例#23
0
def generate_session_key(length):
    return Random.get_random_bytes(length)
示例#24
0
def safe_keygen():
    return Random.get_random_bytes(16)
示例#25
0
    def enc_setup(self, msg, auth_data, key=None, **kwargs):

        encrypted_key = ""
        self.msg = msg
        self.auth_data = auth_data

        # Generate the input parameters
        try:
            apu = b64d(kwargs["apu"])
        except KeyError:
            apu = Random.get_random_bytes(16)
        try:
            apv = b64d(kwargs["apv"])
        except KeyError:
            apv = Random.get_random_bytes(16)

        # Handle Local Key and Ephemeral Public Key
        if not key:
            raise Exception("EC Key Required for ECDH-ES JWE Encrpytion Setup")

        # Generate an ephemeral key pair if none is given
        curve = NISTEllipticCurve.by_name(key.crv)
        if "epk" in kwargs:
            epk = kwargs["epk"] if isinstance(kwargs["epk"], ECKey) else ECKey(kwargs["epk"])
        else:
            raise Exception(
                "Ephemeral Public Key (EPK) Required for ECDH-ES JWE "
                "Encryption Setup")

        params = {
            "apu": b64e(apu),
            "apv": b64e(apv),
            "epk": epk.serialize(False)
        }

        cek = iv = None
        if 'cek' in kwargs and kwargs['cek']:
            cek = kwargs['cek']
        if 'iv' in kwargs and kwargs['iv']:
            iv = kwargs['iv']

        cek, iv = self._generate_key_and_iv(self.enc, cek=cek, iv=iv)

        if self.alg == "ECDH-ES":
            try:
                dk_len = KEYLEN[self.enc]
            except KeyError:
                raise Exception(
                    "Unknown key length for algorithm %s" % self.enc)

            cek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
                                  str(self.enc).encode(), dk_len)
        elif self.alg in ["ECDH-ES+A128KW", "ECDH-ES+A192KW", "ECDH-ES+A256KW"]:
            _pre, _post = self.alg.split("+")
            klen = int(_post[1:4])
            kek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
                                  str(_post).encode(), klen)
            encrypted_key = aes_wrap_key(kek, cek)
        else:
            raise Exception("Unsupported algorithm %s" % self.alg)

        return cek, encrypted_key, iv, params, epk
 def __init__(self, unknownText):
     self.key = Random.get_random_bytes(16)
     self.secret = unknownText
     self.aesECB = AES.new(self.key, AES.MODE_ECB)
示例#27
0
from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding
from Cryptodome import Random
from base64 import b64encode, b64decode

ks = AES.key_size[0]  # 16 bytes
key = Random.get_random_bytes(ks)
iv = Random.get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
with open('flag', 'rb') as f:
    flag = f.read().strip()
flag = Padding.pad(flag, ks, style='pkcs7')
flag_enc = b64encode(iv + cipher.encrypt(flag)).decode('ASCII')
print(flag_enc)
while True:
    query = bytes(input('>>'), 'ASCII')
    query = b64decode(query)
    cipher = AES.new(key, AES.MODE_CBC, iv=query[:16])
    flag_dec = cipher.decrypt(query[16:])
    try:
        Padding.unpad(flag_dec, ks, style='pkcs7')
        print('Correct Padding!')
    except ValueError:
        print('Error Padding!')
示例#28
0
def get_random_bytes(length):
    return Random.get_random_bytes(length)
示例#29
0
 def generate_encrypted_data(self):
     #generating keys/randomness
     generated_keyslots = [None, None, None, None]
     generated_keyslots_keys_from_master = [None, None, None, None]
     generated_final_hmac_key = Random.get_random_bytes(32)
     cipher_slots = [None, None, None, None]
     calculated_hmac1 = [None, None, None, None]
     calculated_hmac2 = [None, None, None, None]
     generated_encrypted_file = bytearray()
     #WRITING SALT TO FILE, INIT CIPHERS
     for i in range(0, 4):
         if self.files_ok[i] == True:
             generated_keyslots[i] = generate_keyslot(self.password_list[i])
             generated_keyslots_keys_from_master[
                 i] = generate_keys_from_master(generated_keyslots[i][1])
             generated_encrypted_file.extend(generated_keyslots[i][0])
             cipher_slots[i] = AES256_CTR(
                 generated_keyslots_keys_from_master[i]
                 [0])  #using first key
         else:
             generated_encrypted_file.extend(Random.get_random_bytes(64))
     #WRITING FINAL SHARED HMAC KEY
     for i in range(0, 4):
         if self.files_ok[i] == True:
             current_hmac_encrypted_key = do_xor_on_bytes(
                 generated_final_hmac_key,
                 generated_keyslots_keys_from_master[i][3])
             generated_encrypted_file.extend(current_hmac_encrypted_key)
         else:
             generated_encrypted_file.extend(Random.get_random_bytes(32))
     #WRITING LENGTHS
     for i in range(0, 4):
         if self.files_ok[i] == True:
             encrypted_init_length = cipher_slots[i].encrypt(
                 self.inner_lengths[i][0].to_bytes(8, byteorder='little'))
             encrypted_end_length = cipher_slots[i].encrypt(
                 self.inner_lengths[i][1].to_bytes(8, byteorder='little'))
             generated_encrypted_file.extend(encrypted_init_length)
             generated_encrypted_file.extend(encrypted_end_length)
         else:
             generated_encrypted_file.extend(Random.get_random_bytes(16))
     #CALCULATING HMAC1
     for i in range(0, 4):
         if self.files_ok[i] == True:
             #using second key
             calculated_hmac1[i] = calculate_hmac1_hmac2(
                 generated_encrypted_file,
                 generated_keyslots_keys_from_master[i][1])
     #writing HMAC1
     for i in range(0, 4):
         if self.files_ok[i] == True:
             generated_encrypted_file.extend(calculated_hmac1[i])
         else:
             generated_encrypted_file.extend(Random.get_random_bytes(64))
     #writing P1, EF1, P2, EF2, P3, EF3, P4, EF4
     for i in range(0, 4):
         generated_encrypted_file.extend(
             Random.get_random_bytes(self.padding_sizes[i]))
         if self.files_ok[i] == True:
             generated_encrypted_file.extend(cipher_slots[i].encrypt(
                 self.files_read[i]))
         else:
             pass
     #WRITING P5
     generated_encrypted_file.extend(
         Random.get_random_bytes(self.padding_sizes[4]))
     #CALCULATING HMAC2
     for i in range(0, 4):
         if self.files_ok[i] == True:
             #using third key
             calculated_hmac2[i] = calculate_hmac1_hmac2(
                 generated_encrypted_file,
                 generated_keyslots_keys_from_master[i][2])
     #writing HMAC2
     for i in range(0, 4):
         if self.files_ok[i] == True:
             generated_encrypted_file.extend(calculated_hmac2[i])
         else:
             generated_encrypted_file.extend(Random.get_random_bytes(64))
     #calculating FINAL HMAC
     final_hmac = calculate_hmac1_hmac2(generated_encrypted_file,
                                        generated_final_hmac_key)
     #writing final HMAC
     generated_encrypted_file.extend(final_hmac)
     # ~ print("WRITTEN FINAL HMAC:", final_hmac)
     # ~ print("KEYS:",generated_keyslots)
     # ~ print("KEYS FROM MASTER")
     # ~ print(generated_keyslots_keys_from_master)
     # ~ print("FILE LENGTH:", len(generated_encrypted_file))
     return generated_encrypted_file
示例#30
0
#!/usr/bin/python3

import argparse

import Cryptodome.Cipher.AES as AES
import Cryptodome.Random as Random

data = Random.get_random_bytes(67108864)
key = Random.get_random_bytes(32)
nonce = Random.get_random_bytes(16)


def run_AES256(num):
    for i in list(range(num)):
        cipher = AES.new(key, AES.MODE_EAX, nonce)
        ciphertext, tag = cipher.encrypt_and_digest(data)
    return


def main():
    num = 1

    parser = argparse.ArgumentParser()

    parser.add_argument("--num",
                        "-n",
                        help="set number of reps for encryption")

    args = parser.parse_args()

    if args.num:
示例#31
0
 def __init__(self, unknownText):
     self.pad = Random.get_random_bytes(random.randint(1, 16))
     self.key = Random.get_random_bytes(AES.block_size)
     self.secret = unknownText
     self.aesECB = AES.new(self.key, AES.MODE_ECB)
示例#32
0
    def enc_setup(self, msg, auth_data, key=None, **kwargs):

        encrypted_key = ""
        self.msg = msg
        self.auth_data = auth_data

        # Generate the input parameters
        try:
            apu = b64d(kwargs["apu"])
        except KeyError:
            apu = Random.get_random_bytes(16)
        try:
            apv = b64d(kwargs["apv"])
        except KeyError:
            apv = Random.get_random_bytes(16)

        # Handle Local Key and Ephemeral Public Key
        if not key:
            raise Exception("EC Key Required for ECDH-ES JWE Encrpytion Setup")

        # Generate an ephemeral key pair if none is given
        curve = NISTEllipticCurve.by_name(key.crv)
        if "epk" in kwargs:
            epk = kwargs["epk"] if isinstance(kwargs["epk"], ECKey) else ECKey(
                kwargs["epk"])
        else:
            epk = ECKey().load_key(key=NISTEllipticCurve.by_name(key.crv))

        params = {
            "apu": b64e(apu),
            "apv": b64e(apv),
            "epk": epk.serialize(False)
        }

        cek = iv = None
        if 'cek' in kwargs and kwargs['cek']:
            cek = kwargs['cek']
        if 'iv' in kwargs and kwargs['iv']:
            iv = kwargs['iv']

        cek, iv = self._generate_key_and_iv(self.enc, cek=cek, iv=iv)

        if self.alg == "ECDH-ES":
            try:
                dk_len = KEYLEN[self.enc]
            except KeyError:
                raise Exception("Unknown key length for algorithm %s" %
                                self.enc)

            cek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
                                  str(self.enc).encode(), dk_len)
        elif self.alg in [
                "ECDH-ES+A128KW", "ECDH-ES+A192KW", "ECDH-ES+A256KW"
        ]:
            _pre, _post = self.alg.split("+")
            klen = int(_post[1:4])
            kek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
                                  str(_post).encode(), klen)
            encrypted_key = aes_wrap_key(kek, cek)
        else:
            raise Exception("Unsupported algorithm %s" % self.alg)

        return cek, encrypted_key, iv, params, epk
示例#33
0
#!/usr/bin/python3

import argparse

import Cryptodome.Cipher.Blowfish as Blowfish
import Cryptodome.Random as Random

#data = b'This is the first message that I have encrypted using PyCryptodome!!'
data = Random.get_random_bytes(16777216)
key = Random.get_random_bytes(16)
nonce = Random.get_random_bytes(16)


def run_Blowfish(num):
    for i in list(range(num)):
        cipher = Blowfish.new(key, Blowfish.MODE_EAX, nonce)
        ciphertext = cipher.encrypt(data)
    return


def main():
    num = 1

    parser = argparse.ArgumentParser()

    parser.add_argument("--num",
                        "-n",
                        help="set number of reps for encryption")

    args = parser.parse_args()
示例#34
0
    def save(self, filepath = None, password = None, keyfile = None):
        """This method saves the database.

        It's possible to parse a data path to an alternative file.

        """
        
        if (password is None and keyfile is not None and keyfile != "" and
            type(keyfile) is str):
            self.keyfile = keyfile
        elif (keyfile is None and password is not None and password != "" and
              type(password is str)):
            self.password = password
        elif (keyfile is not None and password is not None and
              keyfile != "" and password != "" and type(keyfile) is str and
              type(password) is str):
            self.keyfile = keyfile
            self.password = password

        if self.read_only:
            raise KPError("The database has been opened read-only.")
        elif ((self.password is None and self.keyfile is None) or 
              (filepath is None and self.filepath is None) or 
              (keyfile == "" and password == "")):
            raise KPError("Need a password/keyfile and a filepath to save the "
                          "file.")
        elif ((type(self.filepath) is not str and self.filepath is not None) or
              (type(self.password) is not str and self.password is not None) or
              (type(self.keyfile) is not str and self.keyfile is not None)):
            raise KPError("filepath, password and keyfile  must be strings.")
        elif self._num_groups == 0:
            raise KPError("Need at least one group!")
        
        content = bytearray()

        # First, read out all groups
        for i in self.groups:
            # Get the packed bytes
            # j stands for a possible field type
            for j in range(1, 10):
                ret_save = self._save_group_field(j, i)
                # The field type and the size is always in front of the data
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            # End of field
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0) 

        # Same with entries
        for i in self.entries:
            for j in range(1, 15):
                ret_save = self._save_entry_field(j, i)
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0)

        # Generate new seed and new vector; calculate the new hash
        Random.atfork()
        self._final_randomseed = Random.get_random_bytes(16)
        self._enc_iv = Random.get_random_bytes(16)
        sha_obj = SHA256.new()
        sha_obj.update(bytes(content))
        self._contents_hash = sha_obj.digest()
        del sha_obj

        # Pack the header
        header = bytearray()
        header += struct.pack('<I', 0x9AA2D903)
        header += struct.pack('<I', 0xB54BFB65)
        header += struct.pack('<I', self._enc_flag)
        header += struct.pack('<I', self._version)
        header += struct.pack('<16s', self._final_randomseed)
        header += struct.pack('<16s', self._enc_iv)
        header += struct.pack('<I', self._num_groups)
        header += struct.pack('<I', self._num_entries)
        header += struct.pack('<32s', self._contents_hash)
        header += struct.pack('<32s', self._transf_randomseed)
        if self._key_transf_rounds < 150000:
            self._key_transf_rounds = 150000
        header += struct.pack('<I', self._key_transf_rounds)

        # Finally encrypt everything...
        if self.password is None:
            masterkey = self._get_filekey()
        elif self.password is not None and self.keyfile is not None:
            passwordkey = self._get_passwordkey()
            filekey = self._get_filekey()
            sha = SHA256.new()
            sha.update(passwordkey+filekey)
            masterkey = sha.digest()
        else:
            masterkey = self._get_passwordkey()
        final_key = self._transform_key(masterkey)
        encrypted_content = self._cbc_encrypt(content, final_key)
        del content
        del masterkey
        del final_key
        
        # ...and write it out
        if filepath is not None:
            try:
                handler = open(filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(filepath))
            if self.filepath is None:
                self.filepath = filepath
        elif filepath is None and self.filepath is not None:
            try:
                handler = open(self.filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(self.filepath))
        else:
            raise KPError("Need a filepath.")

        try:
            handler.write(header+encrypted_content)
        except IOError:
            raise KPError("Can't write to file.")
        finally:
            handler.close()
        
        if not path.isfile(self.filepath+".lock"):
            try:
                lock = open(self.filepath+".lock", "w")
                lock.write('')
            except IOError:
                raise KPError("Can't create lock-file {0}".format(self.filepath
                                                                  +".lock"))
            else:
                lock.close()
        return True
示例#35
0
 def generate_client_initialization_vector():
     # return bytearray(16)
     # return os.urandom(16)
     return Random.get_random_bytes(16)
示例#36
0
 def runTest(self):
     """Cryptodome.Random.new()"""
     # Import the Random module and try to use it
     from Cryptodome import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Cryptodome.Random import random
     x = random.getrandbits(16 * 8)
     y = random.getrandbits(16 * 8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x > y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1, 10):
         x = random.randrange(start, stop, step)
         y = random.randrange(start, stop, step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1, 2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start, stop)
     y = random.randint(start, stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1, 1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = range(10000)
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1, 2, 3)) in (1, 2, 3), True)
     self.assertEqual(random.choice([1, 2, 3]) in [1, 2, 3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(
             random.choice(bytearray(b('123'))) in bytearray(b('123')),
             True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = range(500)
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
         self.assertEqual(seq[i] in x, True)
         self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "11")
     self.assertRaises(TypeError, random.shuffle, (1, 2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
     # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
         self.assertEqual(x[i] in seq, True)
         self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1, 2, 3), 1)
     self.assertEqual(z[0] in (1, 2, 3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(range(3), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
         z = random.sample(b("123"), 1)
         self.assertEqual(z[0] in b("123"), True)
         z = random.sample(bytearray(b("123")), 1)
         self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
示例#37
0
def generate_random(size: int):
    return Random.get_random_bytes(size)