def encrypt_file(inkey, in_filename, out_filename, chunksize=64 * 1024): key = fixkey(inkey) if not out_filename: out_filename = in_filename + '.enc' iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(8)) encryptor = CAST.new(key, CAST.MODE_CBC, iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk)) infile.close() outfile.close()
def encrypt(self, msg, password): salt = os.urandom(8) password = blake2b(password.encode("ascii"), digest_size=8).digest() crypter = CAST.new(password, mode=self.MODE, IV=salt) return binascii.b2a_base64(salt).decode( "utf-8")[:-1], binascii.b2a_base64( crypter.encrypt(self.pad(msg, 8))).decode("utf-8")[:-1]
def __init__(self, keylen, time_str, state, algorythm): if keylen != 16 and keylen != 24 and keylen != 32: keylen = 16 # Either keying 1 or 2, resp. self.IV = Random.new().read(state) #Init vector self.key = Random.new().read(keylen) self.__state = Random.new().read(state) self.__time_format = time_str if algorythm == 'DES': self.cipher = DES3.new(self.key, DES3.MODE_CBC, self.IV) if algorythm == 'AES': self.cipher = AES.new(self.key, AES.MODE_CBC, self.IV) if algorythm == 'CAST': self.cipher = CAST.new(self.key, CAST.MODE_CBC, self.IV) if algorythm == 'BLOWFISH': self.cipher = Blowfish.new(self.key, Blowfish.MODE_CBC, self.IV) if algorythm == 'Twofish': self.cipher = Twofish(self.key) if algorythm == "RC2": self.cipher = ARC2.new(self.key, ARC2.MODE_CBC, self.IV) if algorythm == "IDEA": self.cipher = IDEA(self.key) if algorythm == "RC5": self.cipher = RC5(self.key, BLOCKSIZE, ROUNDS) if algorythm == "GOST28147": self.IV = Random.new().read(8) self.cipher = "gost"
def runTest(self): # Encrypt/Decrypt data and test output parameter cipher = CAST.new(b'4'*16, CAST.MODE_ECB) pt = b'5' * 16 ct = cipher.encrypt(pt) output = bytearray(16) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None) import sys if sys.version[:3] != '2.6': output = memoryview(bytearray(16)) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16) shorter_output = bytearray(7) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-e", "--encrypt", help="encrypt carbon file", required=False) parser.add_argument("-d", "--decrypt", help="decrypt carbon file", required=False) try: args = parser.parse_args() except IOError as e: parser.error(e) return 0 if len(sys.argv) != 3: parser.print_help() return 0 key = "\x12\x34\x56\x78\x9A\xBC\xDE\xF0\xFE\xFC\xBA\x98\x76\x54\x32\x10" iv = "\x12\x34\x56\x78\x9A\xBC\xDE\xF0" cipher = CAST.new(key, CAST.MODE_OFB, iv) if args.encrypt: plaintext = open(args.encrypt, "rb").read() while len(plaintext) % 8 != 0: plaintext += "\x00" data = cipher.encrypt(plaintext) open(args.encrypt + "_encrypted", "wb").write(data) else: ciphertext = open(args.decrypt, "rb").read() while len(ciphertext) % 8 != 0: ciphertext += "\x00" data = cipher.decrypt(ciphertext) open(args.decrypt + "_decrypted", "wb").write(data)
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-e", "--encrypt", help="encrypt carbon file", required=False) parser.add_argument("-d", "--decrypt", help="decrypt carbon file", required=False) try: args = parser.parse_args() except IOError as e: parser.error(e) return 0 if len(sys.argv) != 3: parser.print_help() return 0 key = b"\x12\x34\x56\x78\x9A\xBC\xDE\xF0\xFE\xFC\xBA\x98\x76\x54\x32\x10" iv = b"\x12\x34\x56\x78\x9A\xBC\xDE\xF0" cipher = CAST.new(key, CAST.MODE_OFB, iv) if args.encrypt: plaintext = open(args.encrypt, "rb").read() while len(plaintext) % 8 != 0: plaintext += b"\x00" data = cipher.encrypt(plaintext) open(args.encrypt + "_encrypted", "wb").write(data) else: ciphertext = open(args.decrypt, "rb").read() while len(ciphertext) % 8 != 0: ciphertext += b"\x00" data = cipher.decrypt(ciphertext) open(args.decrypt + "_decrypted", "wb").write(data)
def _getcipher_real(self, key, algo): """ do the real job of decrypting using functions form PyCrypto """ if (algo == "AES"): key = self._padkey(key, [16, 24, 32]) cipher = cAES.new(key, cAES.MODE_ECB) elif (algo == 'ARC2'): cipher = cARC2.new(key, cARC2.MODE_ECB) elif (algo == 'ARC4'): raise CryptoUnsupportedException("ARC4 is currently unsupported") elif (algo == 'Blowfish'): cipher = cBlowfish.new(key, cBlowfish.MODE_ECB) elif (algo == 'CAST'): cipher = cCAST.new(key, cCAST.MODE_ECB) elif (algo == 'DES'): self._padkey(key, [8]) cipher = cDES.new(key, cDES.MODE_ECB) elif (algo == 'DES3'): key = self._padkey(key, [16, 24]) cipher = cDES3.new(key, cDES3.MODE_ECB) elif (algo == 'XOR'): raise CryptoUnsupportedException("XOR is currently unsupported") else: raise CryptoException("Invalid algorithm specified") return cipher
def runTest(self): # Encrypt/Decrypt data and test output parameter cipher = CAST.new(b'4'*16, CAST.MODE_ECB) pt = b'5' * 16 ct = cipher.encrypt(pt) output = bytearray(16) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None) output = memoryview(bytearray(16)) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16) shorter_output = bytearray(7) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def decrypt_file(input_filename, output_filename, authenticity_key, cipher_key): encrypted = open(input_filename, 'rb').read() print "Encrypted: " + encrypted length = len(encrypted) # mac is 16 bytes at end encrypted_before_MAC = encrypted[:length-16] print "Before MAC: " + encrypted_before_MAC orig_MAC = encrypted[length-16:] print "Old MAC: " + orig_MAC computed_MAC = hmac.new(authenticity_key, encrypted_before_MAC).digest() print "New MAC: " + computed_MAC if hmac.compare_digest(orig_MAC, computed_MAC): hex_length = encrypted[:9] cipher_length = int(hex_length, 16)#some function from hex to int print cipher_length iv = encrypted[9: 17] cipher_text = encrypted[17:length-20] #-cipher.length] obj=CAST.new(cipher_key, CAST.MODE_CBC, IV=iv) f = open(output_filename, 'wb') temp = obj.decrypt(cipher_text) print temp f.write(temp)
def _getcipher_real(self, key, algo): """ do the real job of decrypting using functions form PyCrypto """ if (algo == "AES"): key = hashlib.sha256(key) cipher = cAES.new(key.digest(), cAES.MODE_ECB) elif (algo == 'ARC2'): cipher = cARC2.new(key, cARC2.MODE_ECB) elif (algo == 'ARC4'): raise CryptoUnsupportedException("ARC4 is currently unsupported") elif (algo == 'Blowfish'): cipher = cBlowfish.new(key, cBlowfish.MODE_ECB) elif (algo == 'CAST'): cipher = cCAST.new(key, cCAST.MODE_ECB) elif (algo == 'DES'): if len(key) != 8: raise Exception("DES Encrypted keys must be 8 characters " "long!") cipher = cDES.new(key, cDES.MODE_ECB) elif (algo == 'DES3'): key = hashlib.sha224(key) cipher = cDES3.new(key.digest()[:24], cDES3.MODE_ECB) elif (algo == 'XOR'): raise CryptoUnsupportedException("XOR is currently unsupported") else: raise CryptoException("Invalid algorithm specified") return cipher
def encrypt_file(inkey, in_filename, out_filename, chunksize=64*1024): key = fixkey(inkey) if not out_filename: out_filename = in_filename + '.enc' iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(8)) encryptor = CAST.new(key, CAST.MODE_CBC, iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk)) infile.close() outfile.close()
def decrypt(self, keys, output_dir): if not self.infile: raise DecryptBeforeLoading # if there's a pubkey wrapper, decrypt that first if bool(ord(self.options) & self.OPTIONS['pubkey']): print strings._('scfile_decrypting_pubkey') common.gpg.pubkey_decrypt(self.ciphertext_filename) # delete the .gpg file os.remove(self.ciphertext_filename) self.ciphertext_filename = self.ciphertext_filename.rstrip('.gpg') # reverse the order of ciphers list reversed_ciphers = common.ciphers[:] reversed_ciphers.reverse() # decrypt all the layers of symmetric encryption ciphertext = open(self.ciphertext_filename, 'r').read() for cipher in reversed_ciphers: try: print strings._('scfile_decrypting_symmetric').format(cipher) if cipher == 'aes256': bs = AES.block_size eiv = ciphertext[:bs] ciphertext = ciphertext[bs:] cipher = AES.new(keys[cipher], AES.MODE_CFB, eiv) if cipher == 'blowfish': bs = Blowfish.block_size eiv = ciphertext[:bs] ciphertext = ciphertext[bs:] cipher = Blowfish.new(keys[cipher], Blowfish.MODE_CBC, eiv) if cipher == 'cast5': bs = CAST.block_size eiv = ciphertext[:bs+2] ciphertext = ciphertext[bs+2:] cipher = CAST.new(keys[cipher], CAST.MODE_OPENPGP, eiv) plaintext = cipher.decrypt(ciphertext) except ValueError: raise InvalidDecryptionPassphrase ciphertext = plaintext # delete the .cast5.blowfish.aes256 file os.unlink(self.ciphertext_filename) # write archive to disk archive_filename = self.ciphertext_filename.rstrip('.cast5.blowfish.aes256') open(archive_filename, 'w').write(plaintext) # extract print strings._('scfile_extracting') if not tarfile.is_tarfile(archive_filename): raise InvalidArchive tar = tarfile.open(archive_filename, 'r:gz') names = tar.getnames() tar.extractall(output_dir)
def pycrypto_tests(): # https://pycrypto.readthedocs.io/en/latest/ from Crypto.Cipher import DES, CAST, DES3, ARC2, Blowfish, AES, PKCS1_OAEP, PKCS1_v1_5 DES.new(key, DES.MODE_ECB) # Noncompliant DES.new(mode=DES.MODE_ECB, key=key) # Noncompliant DES.new(key, DES.MODE_CBC, IV=iv) # Noncompliant DES.new(key, DES.MODE_CFB, IV=iv) # Compliant DES.new(key, DES.MODE_OFB, IV=iv) # Compliant DES.new(key, DES.MODE_CTR, IV=iv, counter=ctr) # Compliant CAST.new(key, CAST.MODE_ECB) # Noncompliant DES3.new(key, DES3.MODE_ECB) # Noncompliant ARC2.new(key, ARC2.MODE_CBC, IV=iv) # Noncompliant Blowfish.new(key, Blowfish.MODE_ECB) # Noncompliant AES.new(key, AES.MODE_CBC, IV=iv) # Noncompliant PKCS1_OAEP.new(key) # Compliant PKCS1_v1_5.new(key) # Noncompliant
def Encrypt(self, digestA, pbk): cryp = ARC4.new(digestA) data = ZipInputStream(self.content, True).compress() data = cryp.encrypt(data) iv = Random.new().read(CAST.block_size) cipher = CAST.new(pbk, CAST.MODE_OPENPGP, iv) self.content = cipher.encrypt(data) return
def decryption(cipher_text): start = datetime.now() decryption_suite = CAST.new(key, CAST.MODE_CFB, iv) plain_text = decryption_suite.decrypt(cipher_text) end = datetime.now() total = end - start total = total.total_seconds() print("Decryption time:", total) return plain_text, total
def CryptionMessage(message): """ 暗号化できる文字数は8の倍数です """ crypto_object = CAST.new(CRYPTO_KEY) crypto_message = crypto_object.encrypt(message) en_cr_message = base64.b16encode(crypto_message) return en_cr_message
def encryption(message): start = datetime.now() encryption_suite = CAST.new(key, CAST.MODE_CFB, iv) cipher_text = encryption_suite.encrypt(message) end = datetime.now() total = end - start total = total.total_seconds() print("Encryption time:", total) return cipher_text, total
def Decrypt(self, digestA, pbk): cryp = ARC4.new(digestA) eiv = self.content[:CAST.block_size+2] ciphertext = self.content[CAST.block_size+2:] cipher = CAST.new(pbk, CAST.MODE_OPENPGP, eiv) data = cipher.decrypt(ciphertext) data = cryp.decrypt(data) data = ZipInputStream(StringIO.StringIO(data)).read() self.content = data return
def dec_cast(string_to_decrypt, key): try: hashed_key = HachageHelper.hash('md5', key) cipher = CAST.new(hashed_key[:16]) encrypted_msg = base64.b64decode(string_to_decrypt.encode()) decrypted_msg = cipher.decrypt(encrypted_msg) return decrypted_msg.decode().rstrip(padding_character) except: return "Une erreur s'est produite, veuillez vérifier vos entrées"
def pyCrypto(): import Crypto from Crypto.Cipher import AES, DES, DES3, ARC2, ARC4, Blowfish, CAST, PKCS1_v1_5, PKCS1_OAEP, XOR from Crypto.PublicKey import ElGamal Crypto.Cipher.AES.new() # Noncompliant Crypto.Other.AES.new() # OK AES.new(key=key) # Noncompliant DES.new(key=key) # Noncompliant DES3.new(key=key) # Noncompliant ARC2.new(key=key) # Noncompliant ARC4.new(key=key) # Noncompliant Blowfish.new(key=key) # Noncompliant CAST.new(key=key) # Noncompliant PKCS1_v1_5.new(key=key) # Noncompliant PKCS1_OAEP.new(key=key) # Noncompliant XOR.new(key=key) # Noncompliant ElGamal.generate(key_size) # Noncompliant
def pyCrypto(): import Cryptodome from Cryptodome.Cipher import AES, ChaCha20, DES, DES3, ARC2, ARC4, Blowfish, CAST, PKCS1_v1_5, PKCS1_OAEP, ChaCha20_Poly1305, Salsa20 from Cryptodome.PublicKey import ElGamal Cryptodome.Cipher.AES.new() # Noncompliant Cryptodome.Other.AES.new() # OK AES.new(key=key) # Noncompliant ChaCha20.new(key=key) # Noncompliant DES.new(key=key) # Noncompliant DES3.new(key=key) # Noncompliant ARC2.new(key=key) # Noncompliant ARC4.new(key=key) # Noncompliant Blowfish.new(key=key) # Noncompliant CAST.new(key=key) # Noncompliant PKCS1_v1_5.new(key=key) # Noncompliant PKCS1_OAEP.new(key=key) # Noncompliant ChaCha20_Poly1305.new(key=key) # Noncompliant Salsa20.new(key=key) # Noncompliant ElGamal.generate(key_size) # Noncompliant
def enc_cast(string_to_encrypt, key): try: hashed_key = HachageHelper.hash('md5', key) # CAST key must be at least 5 bytes and no more than 16 bytes long cipher = CAST.new(hashed_key[:16]) padded_private_msg = string_to_encrypt + (padding_character * ( (8 - len(string_to_encrypt)) % 8)) encrypted_msg = cipher.encrypt(padded_private_msg) encoded_encrypted_msg = base64.b64encode(encrypted_msg) return encoded_encrypted_msg.decode() except: return "Une erreur s'est produite, veuillez vérifier vos entrées"
def set_password(self, password, pubkey, privkey): self.privkey_1 = privkey self.pubkey_1 = pubkey self.salt = secrets.token_hex(8) self.password_hash = bcrypt.generate_password_hash( password + self.salt).decode("ascii") cipher = CAST.new(password.encode("utf8"), CAST.MODE_ECB) pubkey = pubkey + "0000000000000000000000" privkey = privkey + "00000000000000" self.pubkey = cipher.encrypt(pubkey.encode("utf8")) self.privkey = cipher.encrypt(privkey.encode("utf8")) db.session.add(self) db.session.commit()
def decrypt_file(key, in_filename,out_filename, chunksize=24*1024): key= fixkey(inkey) if not out_filename: out_filename= in_filename with open(in_filename, 'rb') as infile: origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] iv = infile.read(8) decryptor = CAST.new(key, CAST.MODE_CBC, iv) with open(out_filename, 'wb') as outfile: while True: chunk = infile.read(chunksize) if len(chunk) == 0: break outfile.write(decryptor.decrypt(chunk)) outfile.truncate(origsize)
def decrypt_file(key, in_filename, out_filename, chunksize=24 * 1024): key = fixkey(inkey) if not out_filename: out_filename = in_filename with open(in_filename, 'rb') as infile: origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] iv = infile.read(8) decryptor = CAST.new(key, CAST.MODE_CBC, iv) with open(out_filename, 'wb') as outfile: while True: chunk = infile.read(chunksize) if len(chunk) == 0: break outfile.write(decryptor.decrypt(chunk)) outfile.truncate(origsize)
def encrypt(plaintext, iv, cipher): #最初加密时的加密函数 key = ENCKEY key = key.encode('utf-8') if cipher.lower() == "des": if len(key) != 8: print("[-] DES 密钥长度为8位!") return False o = DES.new(key, DES.MODE_CBC, iv) elif cipher.lower() == "aes": if len(key) != 16 and len(key) != 24 and len(key) != 32: print("[-] AES 密钥长度为16/24/32位!") return False o = AES.new(key, AES.MODE_CBC, iv) elif cipher.lower() == "des3": if len(key) != 16: print("[-] DES3 密钥长度为16位!") return False o = DES3.new(key, DES3.MODE_CBC, iv) elif cipher.lower() == "blowfish": o = Blowfish.new(key, Blowfish.MODE_CBC, iv) elif cipher.lower() == "cast": o = CAST.new(key, CAST.MODE_CBC, iv) elif cipher.lower() == "arc2": o = ARC2.new(key, ARC2.MODE_CBC, iv) else: return False plaintext = add_PKCS7_padding(plaintext, len(iv)) return o.encrypt(plaintext)
def encrypt_file(input_filename, output_filename): # hard coded private key from os.urandom for this iteration cipher_key = '\xc7\xdfK\xb2\xb1^S\xb9' #CBC, or cipher block chaining, hides large scale patterns, bc depends on previous blocks, not just block encrypted #since CBC depends on previous chunk, needs IV, or initialization vector, for first chunk iv = os.urandom(8) obj=CAST.new(cipher_key, CAST.MODE_CBC, IV=iv) plain = open(input_filename, 'rb').read() rev_mod = 8 - (len(plain) % 8) padding_len = 0 if (rev_mod == 8) else rev_mod padded_plain = plain + chr(padding_len) * padding_len ciph=obj.encrypt(padded_plain) # checksum for authentication, hard coded from os.urandom authencity_key = '\xbd\xd4q7@W\xa3\xbd' h = hmac.new(authencity_key, ciph) plain_len = struct.pack('!Q', len(plain)) f = open(output_filename, 'wb') # encrypted file: length + cipher text (+ padding) + MAC (message authentication code) h.update(plain_len) f.write(plain_len) h.update(iv) f.write(iv) h.update(ciph) f.write(ciph) f.write(h.digest()) print "Old MAC: " + h.digest() f.close()
def decrypt(ciphertext, iv, cipher): #加密过程中的解密函数 # 我们只需要填充错误本身,而不是key # 在真正的攻击中,可以触发解密程序 key = ENCKEY key = key.encode('utf-8') if cipher.lower() == "des": o = DES.new(key, DES.MODE_CBC, iv) elif cipher.lower() == "aes": o = AES.new(key, AES.MODE_CBC, iv) elif cipher.lower() == "des3": o = DES3.new(key, DES3.MODE_CBC, iv) elif cipher.lower() == "blowfish": o = Blowfish.new(key, Blowfish.MODE_CBC, iv) elif cipher.lower() == "cast": o = CAST.new(key, CAST.MODE_CBC, iv) elif cipher.lower() == "arc2": o = ARC2.new(key, ARC2.MODE_CBC, iv) else: return False if len(iv) % 8 != 0: return False if len(ciphertext) % 8 != 0: return False return o.decrypt(ciphertext)
''' Copyright (c) 2014 blu3b0lt CAST implementation ''' from Crypto.Cipher import CAST from Crypto import Random key = b'Key is 5 to 16' iv = Random.new().read(CAST.block_size) cipher = CAST.new(key, CAST.MODE_OPENPGP, iv) plaintext = raw_input("Enter Text to be Encrypted: ") msg = cipher.encrypt(plaintext) print "Encrypted text is: " print msg eiv = msg[:CAST.block_size+2] ciphertext = msg[CAST.block_size+2:] cipher = CAST.new(key, CAST.MODE_OPENPGP, eiv) print "Decrypted text is: " print cipher.decrypt(ciphertext)
def setup(self): self.cipher = CAST.new(self.key, CAST.MODE_CFB, iv=self.iv, segment_size=64)
def DecryptionMessage(message): crypto_object = CAST.new(CRYPTO_KEY) de_message = base64.b16decode(message) decrypto_message = crypto_object.decrypt(de_message) return decrypto_message
) # Write the iv to the output file (will be required for decryption) file_out.write( ciphered_data ) # Write the varying length cipher text to the file (this is the encrypted data) file_out.close() # source: https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html # source: https://pycryptodome.readthedocs.io/en/latest/src/cipher/aes.html # source: https://nitratine.net/blog/post/python-encryption-and-decryption-with-pycryptodome/ # Method 2: Encrypting using CAST Mode: from Crypto.Cipher import CAST output_file = 'R#_CAST.bin' data = content key = b'!SQS5342_LBO@S_B' cipher = CAST.new(key, CAST.MODE_OPENPGP) plaintext = content msg = cipher.encrypt(plaintext) file_out = open(output_file, "wb") # Open file to write bytes #file_out.write(cipher.iv) # Write the iv to the output file (will be required for decryption) file_out.write( ciphered_data ) # Write the varying length cipher text to the file (this is the encrypted data) file_out.close() # source: https://pycryptodome.readthedocs.io/en/latest/src/cipher/cast.html ################################ ### PART 3 - DATA DECRYPTION ### ################################
def __getKeyObject(key, iv): global MODE cipher = CAST.new(key, MODE, iv) return cipher
def decrypt(self, enc): iv = enc[:CAST.block_size] cipher = CAST.new(self.key, CAST.MODE_CBC, iv) return Enclibv1_unpad(cipher.decrypt(enc[CAST.block_size:]), self.bs)
def decrypt_castcbc(enc, pwd, salt, keylen): key = hashlib.pbkdf2_hmac("SHA1", pwd.encode('utf-8'), salt.encode('utf-8'), 1024, keylen) iv = b"\x00\x00\x00\x00\x00\x00\x00\x00" cipher = CAST.new(key, CAST.MODE_CBC, iv) return cipher.decrypt(enc)
def cipher(self, key): return CAST.new(key, IV="\0\0\0\0\0\0\0\0", mode=CAST.MODE_CBC)
def encrypt(self, string, isfile=False, addmeta=False): ''' If key is setted up the method will encrypt the string with a path compliant result ''' # If we got an encryption key if self.__key: # Start ciphering system if self.__algorithm == 'AESCFB': cipher = AES.new(self.__key, AES.MODE_CFB) elif self.__algorithm == 'AESECB': cipher = AES.new(self.__key, AES.MODE_ECB) elif self.__algorithm == 'ARC2CFB': cipher = ARC2.new(self.__key, ARC2.MODE_CFB) elif self.__algorithm == 'ARC2ECB': cipher = ARC2.new(self.__key, ARC2.MODE_ECB) elif self.__algorithm == 'BlowfishCFB': cipher = Blowfish.new(self.__key, Blowfish.MODE_CFB) elif self.__algorithm == 'BlowfishECB': cipher = Blowfish.new(self.__key, Blowfish.MODE_ECB) elif self.__algorithm == 'CASTCFB': cipher = CAST.new(self.__key, CAST.MODE_CFB) elif self.__algorithm == 'CASTECB': cipher = CAST.new(self.__key, CAST.MODE_ECB) elif self.__algorithm == 'DESCFB': cipher = DES.new(self.__key, DES.MODE_CFB) elif self.__algorithm == 'DESECB': cipher = DES.new(self.__key, DES.MODE_ECB) else: raise IOError, "Specified encryption algorithm is unkown: %s" % ( self.__algorithm) # Add padding to the string if required if self.padding: (string, padder) = self.pad(string) else: padder = '' # Encrypt the string encoded = cipher.encrypt(string) # Security check if len(encoded) != len(string): self.error( "Encrypt => Normal and decoded string are different size: %s -> %s\n" % (len(encoded), len(string))) # Check if is a file if isfile: # Metadata if not addmeta: b64corrected = encoded else: b64corrected = encoded + padder else: # Encode the result b64encoded = base64.b64encode(encoded) # Correct the result to be path compliant b64corrected = b64encoded.replace("/", "_") else: # Nothing to do b64corrected = string # Return the result return b64corrected
def decrypt(self, b64corrected, isfile=False, removemeta=False): ''' If key is setted up the method will decrypt the string from a path compliant encrypted string ''' # If we got an encryption key if self.__key: # Start ciphering system if self.__algorithm == 'AESCFB': cipher = AES.new(self.__key, AES.MODE_CFB) elif self.__algorithm == 'AESECB': cipher = AES.new(self.__key, AES.MODE_ECB) elif self.__algorithm == 'ARC2CFB': cipher = ARC2.new(self.__key, ARC2.MODE_CFB) elif self.__algorithm == 'ARC2ECB': cipher = ARC2.new(self.__key, ARC2.MODE_ECB) elif self.__algorithm == 'BlowfishCFB': cipher = Blowfish.new(self.__key, Blowfish.MODE_CFB) elif self.__algorithm == 'BlowfishECB': cipher = Blowfish.new(self.__key, Blowfish.MODE_ECB) elif self.__algorithm == 'CASTCFB': cipher = CAST.new(self.__key, CAST.MODE_CFB) elif self.__algorithm == 'CASTECB': cipher = CAST.new(self.__key, CAST.MODE_ECB) elif self.__algorithm == 'DESCFB': cipher = DES.new(self.__key, DES.MODE_CFB) elif self.__algorithm == 'DESECB': cipher = DES.new(self.__key, DES.MODE_ECB) else: raise IOError, "Specified decrypting algorithm is unkown: %s" % ( self.__algorithm) # If is a file if isfile: # And we have to use padding if self.padding: # Remove metatada if not removemeta: encoded = b64corrected else: encoded = b64corrected[:-1] else: # No padder was used encoded = b64corrected else: # Revert the path compliant correction b64encoded = b64corrected.replace("_", "/") # Decode the result encoded = base64.b64decode(b64encoded) # Decrypt the encoded string string = cipher.decrypt(encoded) # Security check if len(encoded) != len(string): self.error( "Decrypt => Normal and encoded string are different size: %s -> %s\n" % (len(encoded), len(string))) # Unpad the string if self.padding: try: string = self.unpad(string) except Exception, e: self.error("Unpad error: %s - String:%s - Encoded:%s\n" % (e, string, b64corrected)) raise
def encrypt(self, txt, pre, enc, post, pwd, tags=True): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for encryption: "%s" !' % str(type(txt))) # # Scramble operation. if not pre or pre == 'N' or pre == 'None': pass elif pre == 'ZLIB' or pre == SCRAMBLE_D['ZLIB']: txt = zlib.compress(txt) elif pre == 'BZ2' or pre == SCRAMBLE_D['BZ2']: txt = bz2.compress(txt) elif pre == 'ROT13' or pre == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % pre) # # Check RSA key path. if enc in ['RSA', 'RSA'] and not os.path.exists(self.rsa_path): print('RSA encryption must specify a valid path !') self.__error(2, pre, enc, post, field='L') return # pwd = self._fix_password(pwd, enc) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish encryption for RSA. o = Blowfish.new(pwd, Blowfish.MODE_CFB) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid encryption mode "%s" !' % enc) # # Encryption operation. if o: pad_len = 16 - (len(txt) % 16) padding = (chr(pad_len) * pad_len) txt = o.encrypt(txt + padding) # # Codec operation. if post == 'Base64 Codec' or post == ENCODE_D['Base64 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_base64(txt).decode()) else: txt = ba.b2a_base64(txt).decode() elif post == 'Base32 Codec' or post == ENCODE_D['Base32 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), base64.b32encode(txt).decode()) else: txt = base64.b32encode(txt).decode() elif post == 'HEX Codec' or post == ENCODE_D['HEX Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_hex(txt).decode()) else: txt = ba.b2a_hex(txt).decode() elif post == 'Quopri Codec' or post == ENCODE_D['Quopri Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), \ ba.b2a_qp(txt, quotetabs=True, header=True).decode()) else: txt = ba.b2a_qp(txt, quotetabs=True, header=True).decode() elif post == 'Json' or post == ENCODE_D['Json']: if tags: # Format : {"pre": "AAA", "enc": "BBB", "post": "CCC", "data": "Blah blah blah"} txt = '{"pre": "%s", "enc": "%s", "post": "%s", "data": "%s"}' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = json.dumps( {'data': ba.b2a_base64(txt).rstrip().decode()}) elif post == 'XML': if tags: # Format : <root><pre>AAA</pre> <enc>BBB</enc> <post>CCC</post> <data>Blah blah blah</data></root> txt = '<root>\n<pre>%s</pre><enc>%s</enc><post>%s</post>\n<data>%s</data>\n</root>' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = '<root>\n<data>%s</data>\n</root>' % ba.b2a_base64( txt).rstrip().decode() else: raise Exception('Invalid codec "%s" !' % post) # # The final text must be String, to be used in GUI return txt
def setup(self): from Crypto.Cipher import CAST self.cipher = CAST.new(self.key, CAST.MODE_CFB, iv=self.iv, segment_size=64)
def decrypt(self, txt, pre, enc, post, pwd): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for decryption: "%s" !' % str(type(txt))) # if not (pre and enc and post): self.guess_pre_enc_post(txt) pre = self.pre enc = self.enc post = self.post if '{' in txt and '}' in txt and '"data":' in txt: temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp elif '<data>' in txt and '</data>' in txt: txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) else: # If Json. if '{' in txt and '}' in txt and '"data":' in txt: pre = 'Json' temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp # If XML. elif '<data>' in txt and '</data>' in txt: pre = 'XML' txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) # # Check RSA key path. if enc == 'RSA' and not os.path.exists(self.rsa_path): print('RSA decryption must specify a valid path !') self.__error(2, pre, enc, post) return # # Adapting password for encryption. pwd = self._fix_password(pwd, enc) # # Codec operation. if not pre: self.__error(1, 'None', enc, post) return elif pre == 'Base64 Codec' or pre == ENCODE_D['Base64 Codec']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return elif pre == 'Base32 Codec' or pre == ENCODE_D['Base32 Codec']: try: txt = base64.b32decode(txt) except: self.__error(1, pre, enc, post) return elif pre == 'HEX Codec' or pre == ENCODE_D['HEX Codec']: try: txt = ba.a2b_hex(txt) except: self.__error(1, pre, enc, post) return elif pre == 'Quopri Codec' or pre == ENCODE_D['Quopri Codec']: try: txt = ba.a2b_qp(txt, header=True) except: self.__error(1, pre, enc, post) return elif pre == 'Json' or pre == ENCODE_D['Json']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return elif pre == 'XML': try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return else: raise Exception('Invalid codec "%s" !' % pre) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish decryption for RSA. o = Blowfish.new(pwd, mode=3, segment_size=16) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid decrypt "%s" !' % enc) # # Decryption operation. if o: try: temp = o.decrypt(txt) pad_len = ord(temp[-1]) txt = temp[:-pad_len] del temp except: self.__error(2, pre, enc, post) return # # Un-scramble operation. if not post or post == 'N' or post == 'None': pass elif post == 'ZLIB' or post == SCRAMBLE_D['ZLIB']: try: txt = zlib.decompress(txt) except: self.__error(3, pre, enc, post) return elif post == 'BZ2' or post == SCRAMBLE_D['BZ2']: try: txt = bz2.decompress(txt) except: self.__error(3, pre, enc, post) return elif post == 'ROT13' or post == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % post) # return txt
def decrypt(self, txt, pre, enc, post, pwd): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for decryption: "%s" !' % str(type(txt))) # if not (pre and enc and post): self.guess_pre_enc_post(txt) pre = self.pre enc = self.enc post = self.post if '{' in txt and '}' in txt and '"data":' in txt: temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp elif '<data>' in txt and '</data>' in txt: txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) else: # If Json. if '{' in txt and '}' in txt and '"data":' in txt: pre = 'Json' temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp # If XML. elif '<data>' in txt and '</data>' in txt: pre = 'XML' txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) # # Check RSA key path. if enc == 'RSA' and not os.path.exists(self.rsa_path): print('RSA decryption must specify a valid path !') self.__error(2, pre, enc, post) return # # Adapting password for encryption. pwd = self._fix_password(pwd, enc) # # Codec operation. if not pre: self.__error(1, 'None', enc, post) ; return elif pre == 'Base64 Codec' or pre == ENCODE_D['Base64 Codec']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) ; return elif pre == 'Base32 Codec' or pre == ENCODE_D['Base32 Codec']: try: txt = base64.b32decode(txt) except: self.__error(1, pre, enc, post) ; return elif pre == 'HEX Codec' or pre == ENCODE_D['HEX Codec']: try: txt = ba.a2b_hex(txt) except: self.__error(1, pre, enc, post) ; return elif pre == 'Quopri Codec' or pre == ENCODE_D['Quopri Codec']: try: txt = ba.a2b_qp(txt, header=True) except: self.__error(1, pre, enc, post) ; return elif pre == 'Json' or pre == ENCODE_D['Json']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) ; return elif pre == 'XML': try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) ; return else: raise Exception('Invalid codec "%s" !' % pre) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish decryption for RSA. o = Blowfish.new(pwd, mode=3, segment_size=16) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid decrypt "%s" !' % enc) # # Decryption operation. if o: try: temp = o.decrypt(txt) pad_len = ord(temp[-1]) txt = temp[:-pad_len] del temp except: self.__error(2, pre, enc, post) ; return # # Un-scramble operation. if not post or post == 'N' or post == 'None': pass elif post == 'ZLIB' or post == SCRAMBLE_D['ZLIB']: try: txt = zlib.decompress(txt) except: self.__error(3, pre, enc, post) ; return elif post == 'BZ2' or post == SCRAMBLE_D['BZ2']: try: txt = bz2.decompress(txt) except: self.__error(3, pre, enc, post) ; return elif post == 'ROT13' or post == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % post) # return txt
cipher = AES.new(key, AES.MODE_CBC, iv16) enctext = cipher.encrypt(message) enc_run = ['encrypt'] enc_trial = Timer("cipher.encrypt(message)", setup) enc_run.append(enc_trial.repeat(RUN_COUNT, 1)) algo_run.append(enc_run) dec_run = ['decrypt'] dec_trial = Timer("cipher.decrypt(enctext)", setup) dec_run.append(dec_trial.repeat(RUN_COUNT, 1)) algo_run.append(dec_run) set_run.append(algo_run) # Create cipher, create cipher text for decryption, time operations, update # result with each new operation algo_run = ['CAST'] cipher = CAST.new(key, CAST.MODE_CBC, iv8) enctext = cipher.encrypt(message) enc_run = ['encrypt'] enc_trial = Timer("cipher.encrypt(message)", setup) enc_run.append(enc_trial.repeat(RUN_COUNT, 1)) algo_run.append(enc_run) dec_run = ['decrypt'] dec_trial = Timer("cipher.decrypt(enctext)", setup) dec_run.append(dec_trial.repeat(RUN_COUNT, 1)) algo_run.append(dec_run) set_run.append(algo_run) lib_run.append(set_run) # BEGIN STREAM CIPHER OPERATIONS
def cast_decrypt_transform(data, key, mode, iv): cast = CAST.new(key, mode, iv) return cast.decrypt(data)
def decrypt_castecb(enc, pwd, salt, keylen): key = hashlib.pbkdf2_hmac("SHA1", pwd.encode('utf-8'), salt.encode('utf-8'), 1024, keylen) cipher = CAST.new(key, CAST.MODE_ECB) return cipher.decrypt(enc)
def encrypt(self, txt, pre, enc, post, pwd, tags=True): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for encryption: "%s" !' % str(type(txt))) # # Scramble operation. if not pre or pre == 'N' or pre == 'None': pass elif pre == 'ZLIB' or pre == SCRAMBLE_D['ZLIB']: txt = zlib.compress(txt) elif pre == 'BZ2' or pre == SCRAMBLE_D['BZ2']: txt = bz2.compress(txt) elif pre == 'ROT13' or pre == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % pre) # # Check RSA key path. if enc in ['RSA', 'RSA'] and not os.path.exists(self.rsa_path): print('RSA encryption must specify a valid path !') self.__error(2, pre, enc, post, field='L') return # pwd = self._fix_password(pwd, enc) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish encryption for RSA. o = Blowfish.new(pwd, Blowfish.MODE_CFB) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid encryption mode "%s" !' % enc) # # Encryption operation. if o: pad_len = 16 - (len(txt) % 16) padding = (chr(pad_len) * pad_len) txt = o.encrypt(txt + padding) # # Codec operation. if post == 'Base64 Codec' or post == ENCODE_D['Base64 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_base64(txt).decode()) else: txt = ba.b2a_base64(txt).decode() elif post == 'Base32 Codec' or post == ENCODE_D['Base32 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), base64.b32encode(txt).decode()) else: txt = base64.b32encode(txt).decode() elif post == 'HEX Codec'or post == ENCODE_D['HEX Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_hex(txt).decode()) else: txt = ba.b2a_hex(txt).decode() elif post == 'Quopri Codec' or post == ENCODE_D['Quopri Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), \ ba.b2a_qp(txt, quotetabs=True, header=True).decode()) else: txt = ba.b2a_qp(txt, quotetabs=True, header=True).decode() elif post == 'Json' or post == ENCODE_D['Json']: if tags: # Format : {"pre": "AAA", "enc": "BBB", "post": "CCC", "data": "Blah blah blah"} txt = '{"pre": "%s", "enc": "%s", "post": "%s", "data": "%s"}' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = json.dumps({'data':ba.b2a_base64(txt).rstrip().decode()}) elif post == 'XML': if tags: # Format : <root><pre>AAA</pre> <enc>BBB</enc> <post>CCC</post> <data>Blah blah blah</data></root> txt = '<root>\n<pre>%s</pre><enc>%s</enc><post>%s</post>\n<data>%s</data>\n</root>' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = '<root>\n<data>%s</data>\n</root>' % ba.b2a_base64(txt).rstrip().decode() else: raise Exception('Invalid codec "%s" !' % post) # # The final text must be String, to be used in GUI return txt
def encrypt(self, raw): raw=Enclibv1_pad(raw, self.bs) iv = Enclibv1_strong_random(CAST.block_size) cipher = CAST.new(self.key, CAST.MODE_CBC, iv) return iv + cipher.encrypt(raw)
def decrypt(self, content, salt, password): salt = binascii.a2b_base64(salt) content = binascii.a2b_base64(content) password = blake2b(password.encode("ascii"), digest_size=8).digest() crypter = CAST.new(password, mode=self.MODE, IV=salt) return crypter.decrypt(content).decode("utf-8")
def lock(self, output_filename, filenames, passphrase, pubkey=None): timer = helpers.Timer() # random salt salt = Random.new().read(16) # compress files into archive timer.start() archive_filename = os.path.join(self.tmp_dir, 'archive.tar.gz') helpers.compress(filenames, archive_filename) print strings._('time_compression').format(timer.stop()) # derive keys from passphrase timer.start() keys = self.stretch_passphrase(passphrase, salt) print strings._('time_stretching').format(timer.stop()) # encrypt with symmetric ciphers timer.start() sys.stdout.write(strings._('encrypt_encrypting_cipher')) sys.stdout.flush() plaintext = open(archive_filename, 'r').read() os.unlink(archive_filename) for cipher in common.ciphers: sys.stdout.write(' {0}'.format(cipher)) sys.stdout.flush() if cipher == 'aes256': # https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html iv = Random.new().read(AES.block_size) cipher = AES.new(keys[cipher], AES.MODE_CFB, iv) ciphertext = iv + cipher.encrypt(plaintext) elif cipher == 'blowfish': # https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.Blowfish-module.html bs = Blowfish.block_size iv = Random.new().read(bs) cipher = Blowfish.new(keys[cipher], Blowfish.MODE_CBC, iv) plen = bs - divmod(len(plaintext),bs)[1] padding = [plen]*plen padding = pack('b'*plen, *padding) ciphertext = iv + cipher.encrypt(plaintext + padding) elif cipher == 'cast5': # https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.CAST-module.html iv = Random.new().read(CAST.block_size) cipher = CAST.new(keys[cipher], CAST.MODE_OPENPGP, iv) ciphertext = cipher.encrypt(plaintext) # today's plaintext is yesterday's ciphertext plaintext = ciphertext sys.stdout.write('\n') # save the new super-enciphered ciphertext current_filename = '{0}.cast5.blowfish.aes256'.format(archive_filename) open(current_filename, 'w').write(plaintext) # encrypt with pubkey if pubkey: common.gpg.pubkey_encrypt(current_filename, pubkey) os.remove(current_filename) current_filename += '.gpg' # write the output file self.save(salt, current_filename, output_filename, bool(pubkey)) print strings._('time_encryption').format(timer.stop()) print strings._('encrypt_encrypted_to').format(output_filename)
def pycrypto_cast(keysize=32, data_size=1024, mode_str="", mode=CAST.MODE_CBC): plaintext = get_random_bytes(data_size * 1024) key = get_random_bytes(keysize) cipher = CAST.new(key, mode) _ = cipher.encrypt(plaintext)