Example #1
0
def chunk_read(response, outfname, intitlekey, first_iv, chunk_size=0x200000, report_hook=None):
    fh = open(outfname,'wb')
    total_size = int(response.getheader('Content-Length'))
    total_size = int(total_size)
    bytes_so_far = 0
    data = []
    first_chunk_read = 0

    while 1:
        if report_hook:
            report_hook(bytes_so_far, chunk_size, total_size)

        chunk = response.read(chunk_size)
        bytes_so_far += len(chunk)

        if not chunk:
             break

        # IV of first chunk should be the Content ID + 28 0s like with the entire file, but each subsequent chunk should be the last 16 bytes of the previous still ciphered chunk
        if first_chunk_read == 0:
            decryptor = AES.new(intitlekey, AES.MODE_CBC, unhexlify(first_iv))
            first_chunk_read = 1
        else:
            decryptor = AES.new(intitlekey, AES.MODE_CBC, prev_chunk[(0x200000 - 16):0x200000])

        dec_chunk = decryptor.decrypt(chunk)
        prev_chunk = chunk

        fh.write(dec_chunk)

    fh.close()
Example #2
0
    def test_nonce_parameter(self):
        # Nonce parameter becomes nonce attribute
        cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertEqual(cipher1.nonce, self.nonce_64)

        counter = Counter.new(64, prefix=self.nonce_64, initial_value=0)
        cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Nonce is implicitly created (for AES) when no parameters are passed
        nonce1 = AES.new(self.key_128, AES.MODE_CTR).nonce
        nonce2 = AES.new(self.key_128, AES.MODE_CTR).nonce
        self.assertNotEqual(nonce1, nonce2)
        self.assertEqual(len(nonce1), 8)

        # Nonce can be zero-length
        cipher = AES.new(self.key_128, AES.MODE_CTR, nonce=b"")
        self.assertEqual(b"", cipher.nonce)
        cipher.encrypt(b'0'*300)

        # Nonce and Counter are mutually exclusive
        self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR,
                          counter=self.ctr_128, nonce=self.nonce_64)
def ReadZipFile(filename):

    """
    从storage中读取数据,还原到kvdb中
    参数 filename 要还原数据的文件名
    """
    bucket = Bucket('backup')
    # print(filename)
    CryptData = bucket.get_object_contents(filename)
    # print(CryptData)
    # -FileBuffer.close()
    key = config.keyDataBackUp
    cipher = AES.new(key, AES.MODE_ECB)
    iv = cipher.decrypt(CryptData[:16])
    # print(str(iv))
    cipher = AES.new(key, AES.MODE_CBC, iv)
    bytebuffer = cipher.decrypt(CryptData[16:])
    lendata = ord(bytebuffer[-1])
    FileBuffer = io.BytesIO(bytebuffer[:-lendata])
    zfile = zipfile.ZipFile(FileBuffer,mode='r')
    namelist = zfile.namelist()
    for name in namelist:
        bytedata = zfile.read(name)
        kv.set(name,bytedata.decode("utf-8"))
        
    return u"数据已还原"
Example #4
0
    def test_valid_init_verify(self):
        # Verify path INIT->VERIFY
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        mac = cipher.digest()

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        cipher.verify(mac)
Example #5
0
 def test_unknown_parameters(self):
     self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR,
                       7, counter=self.ctr_128)
     self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR,
                       counter=self.ctr_128, unknown=7)
     # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
     AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128, use_aesni=False)
Example #6
0
    def decryptFile(self, content):

        from Crypto.Cipher import AES

        Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000')

        IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
        IV_Cipher = AES.new(Key, AES.MODE_ECB)
        IV = IV_Cipher.encrypt(IV)

        obj = AES.new(Key, AES.MODE_CFB, IV)

        data = content

        if re.search(r"<title>404 - Not Found</title>", data) is None:
            data = binascii.unhexlify(''.join(data.split()))
            data = data.split("\xda") 

            links = []
            for link in data:
                if link == '': continue
                link = base64.b64decode(link + "\xda")
                link = obj.decrypt(link)
                decryptedUrl = link.replace('CCF: ', '')
                links.append(decryptedUrl)

            self.log.debug("%s: adding rsdf-package with %d links" % (self.__name__, len(links)))
            return links
Example #7
0
    def test_data_must_be_bytes(self):
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.encrypt, 'test1234567890-*')

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.decrypt_and_verify,
                          'test1234567890-*', b("xxxx"))
Example #8
0
    def test_aes_256_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )

        ciphertext = (
            "dc7e84bfda79164b7ecd8486985d3860"
            + "39ffed143b28b1c832113c6331e5407b"
            + "df10132415e54b92a13ed0a8267ae2f9"
            + "75a385741ab9cef82031623d55b1e471"
        )
        key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #9
0
 def test_unknown_parameters(self):
     self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                       self.iv_128, 7)
     self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                       iv=self.iv_128, unknown=7)
     # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
     AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False)
Example #10
0
    def test_aes_128_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "3b3fd92eb72dad20333449f8e83cfb4a"
            + "c8a64537a0b3a93fcde3cdad9f1ce58b"
            + "26751f67a3cbb140b1808cf187a4f4df"
            + "c04b05357c5d1c0eeac4c66f9ff7f2e6"
        )
        key = "2b7e151628aed2a6abf7158809cf4f3c"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #11
0
    def test_aes_192_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "cdc80d6fddf18cab34c25909c99a4174"
            + "67ce7f7f81173621961a2b70171d3d7a"
            + "2e1e8a1dd59b88b1c8e60fed1efac4c9"
            + "c05f9f9ca9834fa042ae8fba584b09ff"
        )
        key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #12
0
def AESDecrypt(filename, key, output):
    def getlocation():

        html = urllib.urlopen("http://geoiptool.com").read()

        lat = float(re.search(r"lat: [0-9]*\.[0-9]*", html).group()[5:])
        lng = float(re.search(r"lng: [0-9]*\.[0-9]*", html).group()[5:])
        return lat, lng

    f = open(filename, "r")
    cip = f.read().split("\n")
    eLat = cip[0]
    eLon = cip[1]

    f.close()

    obj1 = AES.new("This is coordina", AES.MODE_CFB, "Luckyson Khaidem")
    latitude = float(obj1.decrypt(eLat))
    longitude = float(obj1.decrypt(eLon))
    try:
        lat, lng = getlocation()
    except:
        return -1
    if abs(latitude - lat) >= 0.9999 or abs(longitude - lng) >= 0.9999:
        print "Cannot Decrypt. Location Invalid."
        return -2
    ciphertext = cip[2]
    for i in range(3, len(cip)):
        ciphertext = ciphertext + "\n" + cip[i]

    o = open(output, "w")
    obj = AES.new(key, AES.MODE_CFB, "Luckyson Khaidem")
    message = obj.decrypt(ciphertext)
    o.write(message)
    o.close()
Example #13
0
def decipher(ciphermsg, keytext, mode):
    hexIv=ciphermsg[:32]
    iv=hexIv.decode('hex')
    realCiphermsg=ciphermsg[32:].decode('hex')
    key=keytext.decode('hex')

    if mode==AES.MODE_CBC:
        aesObj=AES.new(key, mode, iv)
    elif mode==AES.MODE_CTR:
        first_value=int(hexIv, base=16)
        ctrObj=Counter.new(128,initial_value=first_value)
        aesObj=AES.new(key, mode, counter=ctrObj)
    else:
        print 'Invalid encryption mode specified!'
        os.exit(1)

    plainmsg=aesObj.decrypt(realCiphermsg)

    if mode==AES.MODE_CBC:                        # CBC padding handling
        lastValue=ord(plainmsg[-1])
        if lastValue >=1 or lastValue <=16:       #PKCS5 padding scheme
            paddingLength=lastValue
            plainmsg=plainmsg[:-paddingLength]

    print 'Msg deciphered: ' + plainmsg
def test_aes_encryption():
    secret = {"secret": "This is a secret!"}
    secret_data = json.dumps(secret)

    aes_key = "This is a key123"  # 128bit key

    # Generate initialization vector for AES
    iv = Random.new().read(AES.block_size)
    assert len(iv) == AES.block_size

    # Initialize AES cipher
    cipher = AES.new(aes_key, AES.MODE_CFB, iv)

    # Prepare a packed string containing IV + crypto text
    packed = iv + cipher.encrypt(secret_data.encode("utf-8"))

    del iv, cipher

    # ---------- time to get the message back! ----------

    iv = packed[: AES.block_size]
    msg = packed[AES.block_size :]

    cypher = AES.new(aes_key, AES.MODE_CFB, iv)

    decrypted = cypher.decrypt(msg)
    assert decrypted == secret_data

    loaded = json.loads(decrypted)
    assert loaded == secret
Example #15
0
    def test_aes_192(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'
        ciphertext =    'cdc80d6fddf18cab34c25909c99a4174' +\
                        'fcc28b8d4c63837c09e81700c1100401' +\
                        '8d9a9aeac0f6596f559c6d4daf59a5f2' +\
                        '6d9f200857ca6c3e9cac524bd9acc92a'
        key =           '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
Example #16
0
    def decrypt(self, pyfile):
    
        from Crypto.Cipher import AES

        infile = pyfile.url.replace("\n", "")
        Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000')

        IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
        IV_Cipher = AES.new(Key, AES.MODE_ECB)
        IV = IV_Cipher.encrypt(IV)

        obj = AES.new(Key, AES.MODE_CFB, IV)

        rsdf = open(infile, 'r')

        data = rsdf.read()
        rsdf.close()

        if re.search(r"<title>404 - Not Found</title>", data) is None:
            data = binascii.unhexlify(''.join(data.split()))
            data = data.splitlines()

            links = []
            for link in data:
                link = base64.b64decode(link)
                link = obj.decrypt(link)
                decryptedUrl = link.replace('CCF: ', '')
                links.append(decryptedUrl)

            self.log.debug("%s: adding package %s with %d links" % (self.__name__,pyfile.package().name,len(links)))
            self.packages.append((pyfile.package().name, links))        
Example #17
0
    def test_aes_256(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'
        ciphertext =    'dc7e84bfda79164b7ecd8486985d3860' +\
                        '4febdc6740d20b3ac88f6ad82a4fb08d' +\
                        '71ab47a086e86eedf39d1c5bba97c408' +\
                        '0126141d67f37be8538f5a8be740e484'
        key =           '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
Example #18
0
    def decrypt(self, buff):
        """
        Return a decrypted copy of the given PSP save file data.

        Arguments:
        buff -- Data read from an encrypted PSP save file

        """
        xor_key = bytearray(buff[:16])
        for i in range(16):
            xor_key[i] ^= self._cipher2[i] ^ self._key[i]
        aes = AES.new(self._cipher3, AES.MODE_CBC, b'\x00' * 16)
        xor_key = bytearray(aes.decrypt(bytes(xor_key))[:12])
        for i in range(12):
            xor_key[i] ^= self._cipher1[i]
        xor_buff = bytearray()
        for i in range(1, len(buff) // 16):
            xor_buff.extend(xor_key)
            xor_buff.extend(array.array('I', [i]).tostring())
        aes = AES.new(self._cipher4, AES.MODE_CBC, b'\x00' * 16)
        xor_buff = bytearray(aes.decrypt(bytes(xor_buff)))
        buff = bytearray(buff[16:])
        for i in range(len(buff)):
            buff[i] ^= xor_buff[i]
        return bytes(buff)
Example #19
0
    def decrypt_body(self, password, data):
        import time
        key = sha256(password).digest()
        hdr = self.header
        
        then = time.time()
        # sha256 the password, encrypt it upon itself 50000 times, sha256 it again, and sha256 it again concatenated with a random number :|
        cipher = AES.new(hdr['seed_key'], AES.MODE_ECB)
        for x in range(hdr['seed_rot_n']):
            key = cipher.encrypt(key)
        key = sha256(key).digest()
        key = sha256(hdr['seed_rand'] + key).digest()
        cipher = AES.new(key, AES.MODE_CBC, hdr['enc_iv'])
        body = cipher.decrypt(data)

        # remove some padding
        padding = unpack("b", body[-1])[0]
        body = body[:-padding]

        now = time.time()

        print 'spent %.3fms on decryption' % ((now - then) * 1000)
        if sha256(body).digest() != hdr['checksum']:
            raise KdbReaderDecodeFailError()

        return body
Example #20
0
def encrypt(username, password,key,mode):
	""" 
	This functions is used to encrypt passwords.
	"""
	# WE CREATE RANDOM SALT FOR EACH PASSWORD 
	salt_for_passwords = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(5))
	# WE LET THE USER SELECT THE MODE
	# FOR CBC AND CTR MODE WE CREATE IV
	# WE ADD SALT TO THE PASWORD AND ENCRYPT IT
	# WE SAVE USERNAME:PASSWORD:IV:[MODE NUMBER 1 FOR ECB, 2 FOR CBC, 3 FOR CTR]
	if mode == "1":
		mode = AES.MODE_ECB
		aes = AES.new(key, mode)
		encrypted_username = aes.encrypt(username+ "\0"*(32-len(username)))
		encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password)))
		return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+ ":" +" "+":"+ "1"
	elif mode =="2":
		mode = AES.MODE_CBC
		IV = str(Crypto.Random.new().read(IV_SIZE))
		aes = AES.new(key, mode, IV)
		encrypted_username = aes.encrypt(username+ "\0"*(32-len(username)))
		encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password)))
		return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+":"+base64.b64encode(IV)+ ":" + "2"
	elif mode =="3":
		mode = AES.MODE_CTR
		IV = str(Crypto.Random.new().read(IV_SIZE))
		ctr = Crypto.Util.Counter.new(128, initial_value=long(IV.encode("hex"), 16))
		aes = Crypto.Cipher.AES.new(key, mode, counter=ctr)
		encrypted_username = aes.encrypt(username+ "\0"*(32-len(username)))
		encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password)))
		return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+":"+base64.b64encode(IV)+ ":" + "3"
	else:
		print "ERROR: Invalid mode!"
Example #21
0
    def test_hex_mac(self):
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        mac_hex = cipher.hexdigest()
        self.assertEqual(cipher.digest(), unhexlify(mac_hex))

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        cipher.hexverify(mac_hex)
Example #22
0
def decrypt_username(encrypted_record,key,mode):
	""" 
	This functions is used to decrypt usernames.
	"""
	# WE DECRYPT THE PASSWORD ACCORDING TO THE MODE IT WAS SAVED
	# WE RETURN USERNAME:PASSWORD
	# decrypted_pass[5:] IS USED TO RETURN THE PASSWORD ONLY (WITHOUT SALT)
	if mode == "1":
		mode = AES.MODE_ECB
		pair = encrypted_record.split(":")
		aes = AES.new(key, mode)
		decrypted_username = aes.decrypt(base64.b64decode(pair[0]))
		return decrypted_username
	
	elif mode =="2":
		mode = AES.MODE_CBC
		pair = encrypted_record.split(":")
		aes = AES.new(key, mode,base64.b64decode(pair[2]))
		decrypted_username = aes.decrypt(base64.b64decode(pair[0]))
		return decrypted_username

	elif mode =="3":
		mode = AES.MODE_CTR
		pair = encrypted_record.split(":")
		IV = base64.b64decode(pair[2])
		ctr = Crypto.Util.Counter.new(128, initial_value=long(IV.encode("hex"), 16))
		aes = Crypto.Cipher.AES.new(key, mode, counter=ctr)
		decrypted_username = aes.decrypt(base64.b64decode(pair[0]))
		return decrypted_username

	else:
		print ""
Example #23
0
    def test_invalid_multiple_decrypt_and_verify(self):
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        ct, tag = cipher.encrypt_and_digest(self.data_128)

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        cipher.decrypt_and_verify(ct, tag)
        self.assertRaises(TypeError, cipher.decrypt_and_verify, ct, tag)
Example #24
0
 def _get_cipher(self):
     """Return a Pycrypto AES cipher instance.
     `key`, `mode` and depending on mode `iv` must be set.
     """
     if self.mode in (AES.MODE_ECB, AES.MODE_CTR):
         return AES.new(self.key, self.mode)
     return AES.new(self.key, self.mode, self.iv)
Example #25
0
    def test_bytearray(self):
        data = b"1" * 16
        iv = b"\x00" * 6 + b"\xFF\xFF"

        # Encrypt
        cipher1 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=iv)
        ref1 = cipher1.encrypt(data)

        cipher2 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=bytearray(self.nonce_64),
                          initial_value=bytearray(iv))
        ref2 = cipher2.encrypt(bytearray(data))

        self.assertEqual(ref1, ref2)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        # Decrypt
        cipher3 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=iv)
        ref3 = cipher3.decrypt(data)

        cipher4 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=bytearray(self.nonce_64),
                          initial_value=bytearray(iv))
        ref4 = cipher4.decrypt(bytearray(data))

        self.assertEqual(ref3, ref4)
def encrypt_oracle(data):
    """
    随机选择 CBC 模式或者 ECB 模式进行加密, 返回加密所使用的模式以及加密后的结果
    :param data: 待加密明文, "plaintext"
    :return: 模式以及加密结果, ("CBC", b"cipher_text")
    """
    size = 16
    key = generate_random_bytes(size)
    encrypt_mode = random.choice([AES.MODE_CBC, AES.MODE_ECB])  # 随机选择一种加密模式
    mode_dict = {AES.MODE_CBC: "CBC", AES.MODE_ECB: "ECB"}

    data = codecs.encode(data, "ascii")  # 将 str 转成 bytes
    # 对数据进行随机化处理
    data = generate_random_bytes(random.randint(5, 10)) + data + generate_random_bytes(random.randint(5, 10))
    data = pad(data, size)  # 填充操作

    if encrypt_mode == AES.MODE_CBC:
        iv = generate_random_bytes(size)
        encrypt_tool = AES.new(key, AES.MODE_CBC, IV=iv)
    elif encrypt_mode == AES.MODE_ECB:
        encrypt_tool = AES.new(key, AES.MODE_ECB)
    else:
        raise RuntimeError("Encrypt_mode is wrong!")

    after_encrypt_data = encrypt_tool.encrypt(data)

    return mode_dict[encrypt_mode], after_encrypt_data
Example #27
0
	def export_data(self, entrystore, password):
		"Exports data from an entrystore"

		# check and pad password
		if password is None:
			raise base.PasswordError

		password = util.pad_right(password[:32], 32, "\0")

		# generate XML
		data = RevelationXML.export_data(self, entrystore)

		# compress data, and right-pad with the repeated ascii
		# value of the pad length
		data = zlib.compress(data)

		padlen = 16 - (len(data) % 16)
		if padlen == 0:
			padlen = 16

		data += chr(padlen) * padlen

		# generate an initial vector for the CBC encryption
		iv = util.random_string(16)

		# encrypt data
		AES.block_size = 16
		AES.key_size = 32

		data = AES.new(password, AES.MODE_CBC, iv).encrypt(data)

		# encrypt the iv, and prepend it to the data with a header
		data = self.__generate_header() + AES.new(password).encrypt(iv) + data

		return data
Example #28
0
    def test_aes_128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'
        ciphertext =    '3b3fd92eb72dad20333449f8e83cfb4a' +\
                        '7789508d16918f03f53c52dac54ed825' +\
                        '9740051e9c5fecf64344f7a82260edcc' +\
                        '304c6528f659c77866a510d9c1d6ae5e'
        key =           '2b7e151628aed2a6abf7158809cf4f3c'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def WriteZipFile(filename):
    """
    保存所有kvdb数据,压缩成zip然后aes cbc加密
    """
    FileBuffer = io.BytesIO()
    datalist = FindKVDBKeys()
    if datalist:
        zfile = zipfile.ZipFile(FileBuffer,mode='w')
        for data in datalist:
            # bytedata = (data + "tttttttt").encode(encoding="utf-8")
            bytedata = kv.get(str(data))
            if bytedata:
                # print(bytedata)
                zfile.writestr(str(data),bytedata)
        zfile.close() 
        key = config.keyDataBackUp
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(key, AES.MODE_ECB)
        CryptIV = cipher.encrypt(iv)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        bytebuffer = FileBuffer.getvalue()
        lendata = 16 - len(bytebuffer)%16
        bytebuffer = bytebuffer + chr(lendata)*lendata
        #print(bytebuffer)
        CryptData = CryptIV + cipher.encrypt(bytebuffer)
        bucket = Bucket('backup')
        # print(FileBuffer.getvalue())
        bucket.put_object(filename,CryptData)
        FileBuffer.close()
Example #30
0
    def test3(self):

        for keylen, taglen, result in self.tv3:

            key = bchr(0) * (keylen // 8 - 1) + bchr(taglen)
            C = b("")

            for i in range(128):
                S = bchr(0) * i

                N = long_to_bytes(3 * i + 1, 12)
                cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
                cipher.update(S)
                C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()

                N = long_to_bytes(3 * i + 2, 12)
                cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
                C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()

                N = long_to_bytes(3 * i + 3, 12)
                cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
                cipher.update(S)
                C += cipher.encrypt() + cipher.digest()

            N = long_to_bytes(385, 12)
            cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
            cipher.update(C)
            result2 = cipher.encrypt() + cipher.digest()
            self.assertEqual(unhexlify(b(result)), result2)