def runTest(self): # Encrypt/Decrypt data and test output parameter cipher = ARC2.new(b'4'*16, ARC2.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 runTest(self): ARC2.new(b'\x00' * 16, ARC2.MODE_ECB, effective_keylen=40) self.assertRaises(ValueError, ARC2.new, bchr(0) * 4, ARC2.MODE_ECB) self.assertRaises(ValueError, ARC2.new, bchr(0) * 129, ARC2.MODE_ECB) self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB, effective_keylen=39) self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB, effective_keylen=1025)
def runTest(self): ARC2.new(b'\x00' * 16, ARC2.MODE_ECB, effective_keylen=40) self.assertRaises(ValueError, ARC2.new, bchr(0) * 4, ARC2.MODE_ECB) self.assertRaises(ValueError, ARC2.new, bchr(0) * 129, ARC2.MODE_ECB) self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB, effective_keylen=39) self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB, effective_keylen=1025)
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 decrypt(self, timerPrinting=False): """To Give The Order To Decrypt The File""" t = time.time() if self.extension in self.path: with open(self.path, 'rb') as file: file_data = file.read() # #Start CHecking The PlatForm # if platform.system() == "Windows": # self.path = self.path.split("\\")[-1] # elif platform.system() == "Linux": # self.path = self.path.split('/')[-1] # #End Checking Wich Platform # print("Decrypting of "+str(self.path)+"...") ############################################################################ iv = base64.b64decode(file_data)[:8] realData = base64.b64decode(file_data)[8:] d = ARC2.new(self.key, ARC2.MODE_CBC, iv) self.decrypt = d.decrypt(realData) ############################################################################ self.path2 = self.path.replace(self.extension, "") os.remove(self.path) #print('Writing in Your File...') with open(self.path2, "wb") as newfile: newfile.write(self.decrypt) if timerPrinting: print('Done In ' + str(time.time() - t)) else: print("The File is Not Encrypted To Decrypted")
def encrypt(self, timerPrinting=False): """To give the Order To Encrypt The File""" t = time.time() #Check If The File is if self.extension not in self.path: with open(self.path, 'rb') as file: file_data = file.read() # #Start To CHecking The PlatForm # if platform.system() == "Windows": # self.path_dir = self.path.split("\\")[-1] # elif platform.system() == "Linux": # self.path_dir = self.path.split('/')[-1] # #End Checking Wich Platform # print('Encryption of '+self.path_dir+'...') # print('It\'s may take a will') ######################### ARC2 Algorithm ######################### padding = b'}' bs = ARC2.block_size p = lambda s: s + (bs - len(s) % bs) * padding iv = Random.new().read(8) c = ARC2.new(self.key, ARC2.MODE_CBC, iv) self.encrypt = base64.b64encode(iv + c.encrypt(p(file_data))) ################################################################# # print('writing in you file ...') os.remove(self.path) with open(str(self.path) + self.extension, 'wb') as newfile: newfile.write(self.encrypt) if timerPrinting: print('Done In ' + str(time.time() - t)) else: print("The File is already encrypt")
def encrypt(self, key, mode, data, IV): if(mode == 1): obj = ARC2.new(str(key), ARC2.MODE_ECB, str(IV)) return obj.encrypt(data) elif(mode == 2): obj = ARC2.new(str(key), ARC2.MODE_CBC, str(IV)) return obj.encrypt(data) elif(mode == 3): obj = ARC2.new(str(key), ARC2.MODE_CFB, str(IV)) return obj.encrypt(data) elif(mode == 4): obj = ARC2.new(str(key), ARC2.MODE_OFB, str(IV)) return obj.encrypt(data)
def decrypt(inbuf): """ Decrypts sample using RC2 """ # file hash sfx_hash = hashlib.sha256(inbuf).hexdigest() print("[-] INF Hash: {}".format(sfx_hash)) output_file = "{0}_decrypted".format(sfx_hash) # find key m = re.search(r'Keys=([a-zA-Z]+)', inbuf) key = m.group(1) md = hashlib.md5(key) pbekey = md.digest() print("[+] Found key: {}".format(key)) #print("[*] PBE key: {}".format(md.hexdigest().upper())) # find encrypted data m = re.search(r'\[Data\]0x([0-9a-fA-F]+)\[eData\]', inbuf) data = m.group(1).decode('hex') #print("[*] Encrypted header: {}".format(data[0:16].encode('hex').upper())) #create decryptor iv = '\x00' * ARC2.block_size # null iv decrypted = ARC2.new(pbekey, ARC2.MODE_CBC, iv, effective_keylen=128).decrypt(data) #print("[+] Decrypted header: {}".format(decrypted[0:16].encode('hex').upper())) #assert '\x4D\x5A\x90\x00' == decrypted[0:4] # MZ header with open(output_file, 'wb') as f: f.write(decrypted) print('[+] Decrypted payload written to: {}'.format(output_file)) return decrypted
def rc2(): print('Input to RC2:') plain_inputRC2 = shares[2] print(plain_inputRC2) print(len(plain_inputRC2)) plainRC2 = padtext2(plain_inputRC2) print("\nShamir's secret 3 after padding:") print(plainRC2) print(len(plainRC2)) while True: global RC2keyEn RC2keyEn = input('\nEnter a 64 characters RC2 encryption Key:\n') if len(RC2keyEn) < 64: print('Error: Entered Key is not 64 characters!') elif len(RC2keyEn) >= 65: print('Error: Entered Key is not 64 characters!') else: break print('\nEntered RC2 Key:\n' + RC2keyEn) cipherRC2 = ARC2.new(RC2keyEn) global ciphertextRC2 ciphertextRC2 = cipherRC2.encrypt(plainRC2) print("\nShamir's secret 3 after encrypting with RC2:") print(ciphertextRC2) print(len(ciphertextRC2)) global executedRC2 executedRC2 = True
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 _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 decrypt(self, ciphertext): unbased = base64.b64decode(ciphertext) iv = unbased[:self.block_size] encrypted = unbased[self.block_size:] key = self.key.digest() arc2init = ARC2.new(key, ARC2.MODE_CBC, iv) msg = arc2init.decrypt(encrypted) return msg.rstrip(self.padding)
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, msg): key = self.key.digest() k = lambda s: s + (self.block_size - len(s) % self.block_size ) * self.padding iv = Random.new().read(self.block_size) key = self.key.digest() arc2init = ARC2.new(key, ARC2.MODE_CBC, iv) chipher = arc2init.encrypt(k(msg)) return base64.b64encode(iv + chipher)
def decryptAES(file, ciphertext): # print "AES" text = b'' # base64_decoded_text = base64.b64decode(ciphertext) base64_decoded_text =ciphertext.decode('base64') key = "0xccb97558940b82637c8bec3c770f86fa3a391a56" #read salt from file fo = open(file, "rb") salt = readBytes(fo) version = struct.unpack('b', fo.read(1))[0] # read encryptionKey from file if version != -1: encrypt_key = readBytes(fo) if version >=2: encrypt_key = readBytes(fo) # var 'key2key' means RC2 key to AES key print "encrypt_key(%d): %s" % (len(encrypt_key), encrypt_key.encode('hex')) hasher = SHA.new() hasher.update(salt) hasher.update(key) # hasher.update(key) # hasher.update(salt) key2key = hasher.digest() print key2key.encode('hex') for i in range(1, 5): hasher = SHA.new() hasher.update(key2key) key2key = hasher.digest() print key2key.encode('hex') print "key2key len:", len(key2key) print "key2key:", key2key.encode("hex") print encrypt_key[:8].encode('hex') rc2 = ARC2.new(key2key[8:], ARC2.MODE_CBC, key2key[:8]) print encrypt_key[8:].encode('hex') key = rc2.decrypt(encrypt_key) print "key:", key.encode('hex') # iv = ciphertext.index(0, 16) # ciphertext2 = ciphertext.index(16) # # AESCipher = AES.new(key, AES.MODE_CBC, iv) # # text = AESCipher.decrypt(ciphertext2) fo.close() return text
def decrypt(message, Key=b'1a3b4c5e6d7f8g9h0i1j2k3l4m5n6o7p'): if len(message) == 0: return "" else: AESobj = AES.new(Key, AES.MODE_ECB) ARC2obj = ARC2.new(Key + Key) ARC4obj = ARC4.new(Key + Key + Key) m3 = AESobj.decrypt(ARC2obj.decrypt(ARC4obj.decrypt(message))) return m3
def encryption(message): start = datetime.now() cipher = ARC2.new(key, ARC2.MODE_CFB, iv) cipher_text = cipher.encrypt(message) end = datetime.now() total = end - start total = total.total_seconds() print("Encryption time:", total) return cipher_text, total
def decryption(cipher_text): start = datetime.now() cipher = ARC2.new(key, ARC2.MODE_CFB, iv) plain_text = cipher.decrypt(cipher_text) end = datetime.now() total = end - start total = total.total_seconds() print("Decryption time:", total) return plain_text, total
def rc22_func(): from Crypto.Cipher import ARC2 try: hello = input("Secret message :") key = input("Please Enter Key 16 Byte :") cipher = ARC2.new(key.encode(), ARC2.MODE_CFB) a = cipher.iv msg = a + cipher.encrypt(hello.encode()) print("Encrypted :",str(msg)[2:-1]) ciphertext = msg iv = ciphertext[:ARC2.block_size] ciphertext = ciphertext[ARC2.block_size:] cipher = ARC2.new(key.encode(), ARC2.MODE_CFB, iv) text = cipher.decrypt(ciphertext) print("Decrypted :",str(text)[2:-1]) except: print("Wrong Value..!")
def decrypt_file(in_filename, out_filename, chunk_size, key, iv): arc2 = ARC2.new(key, ARC2.MODE_CFB, iv) with open(in_filename, 'r') as in_file: with open(out_filename, 'w') as out_file: while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break out_file.write(arc2.decrypt(chunk))
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 decrypt_file(in_filename, out_filename, chunk_size, key, iv): arc2 = ARC2.new(key, ARC2.MODE_CBC, iv) with open(in_filename, 'r') as in_file: with open(out_filename, 'w') as out_file: while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break out_file.write(arc2.decrypt(chunk))
def ARC2_encrypt(msg, key): padding = " " block_size = ARC2.block_size p = lambda s: s + (block_size - len(s) % block_size) * padding iv = Random.new().read(8) c = ARC2.new(key, ARC2.MODE_CBC, iv) Enc_msg = iv + c.encrypt(p(msg).encode('ascii')) print("Your Encode >>> ", base64.b64encode(Enc_msg).decode('ascii')) print("-" * 80) print("Your Key >>> ", key) print("-" * 80)
def encrypt(plain, key): if isinstance(key, str): key = key.encode() if isinstance(plain, str): plain = plain.encode() iv = ARC2.block_size * b'\x00' cipher = ARC2.new(key, ARC2.MODE_ECB, iv) pad = (8 - divmod(len(plain), 8)[1]) * b'\x00' plain = plain + pad + struct.pack('!Q', len(pad)) crypt = iv + cipher.encrypt(plain) return binascii.hexlify(crypt).decode()
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 encrypt_file(in_filename, out_filename, chunk_size, key, iv): arc2 = ARC2.new(key, ARC2.MODE_CFB, iv) with open(in_filename, 'r') as in_file: with open(out_filename, 'w') as out_file: while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) out_file.write(arc2.encrypt(chunk))
def encrypt_file(in_filename, out_filename, chunk_size, key, iv): arc2 = ARC2.new(key, ARC2.MODE_CFB, iv) with open(in_filename, 'r') as in_file: with open(out_filename, 'w') as out_file: while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) out_file.write(arc2.encrypt(chunk))
def decrypt(crypt, key): if isinstance(key, str): key = key.encode() if isinstance(crypt, str): try: crypt = binascii.unhexlify(crypt.encode()) except ValueError: raise ValueError("Incorrect encoded data: " + crypt) iv = crypt[:ARC2.block_size] crypt = crypt[ARC2.block_size:] cipher = ARC2.new(key, ARC2.MODE_ECB, iv) plain = cipher.decrypt(crypt) pad_len = struct.unpack('!Q', plain[-8:])[0] + 8 plain = plain[:-pad_len] return plain.decode()
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 runTest(self): # Encrypt/Decrypt data and test output parameter cipher = ARC2.new(b'4' * 16, ARC2.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 dcrpt_rc2(): while True: RC2keyDe = input('Enter the 64 characters RC2 decryption Key:\n') if len(RC2keyDe) < 64: print('Error: Entered Key is not 64 characters!\n') elif len(RC2keyDe) >= 65: print('Error: Entered Key is not 64 characters!\n') else: if RC2keyDe == RC2keyEn: cipherRC2 = ARC2.new(RC2keyDe) break else: print('Error: Wrong key was entered. Please try again!\n') plaintextRC2 = cipherRC2.decrypt(ciphertextRC2) stringRC2 = plaintextRC2.replace(b' ', b'') print("Shamir's secret 3 after decrypting RC2:") print(stringRC2) print(len(stringRC2)) global decryptedRC2 decryptedRC2 = True
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)
def descifrar(self, encriptado): code = base64.b64decode(encriptado) iv = code[:8] cifrador = ARC2.new(self.clave, ARC2.MODE_CFB, iv) return unpad(cifrador.decrypt(encriptado[8:]))
def cifrar(self, datos): iv = texto_aleatorio cifrador = ARC2.new(self.clave, ARC2.MODE_CFB, iv)# https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode return cifrador.encrypt(datos)
def decrypt_pbe_with_and_128rc2_CBC(cipher_text, password, salt, count): kdf = PBKDF3(password, salt, count, 16, 8, SHA) cipher = ARC2.new(kdf[0], ARC2.MODE_CBC, kdf[1], effective_keylen=128) secret_key = unpad(cipher.decrypt(cipher_text)) return secret_key
keyspace = (''.join(x).decode('hex') for x in itertools.product(hexchars, repeat=keysize*2)) plain = raw_input("Plaintext> ").decode('hex') cipher = raw_input("Ciphertext> ").decode('hex') pairs = (mitmPair(plain, cipher, key) for key in keyspace) encDict = {} decDict = {} for pair in pairs: encDict[pair[0]] = pair[2] decDict[pair[1]] = pair[2] keyspace = [(encDict[m], decDict[m]) for m in encDict.viewkeys() & decDict.viewkeys()] # while we have not narrowed the key while len(keyspace) != 1: print("Keyspace of {} remaining keys".format(len(keyspace))) plain = raw_input("Plaintext> ").decode('hex') cipher = raw_input("Ciphertext> ").decode('hex') keyspace = [key for key in keyspace if mitmFilter(plain, cipher, key)] key = keyspace[0] print("Found key {}{}".format(key[0].encode('hex'), key[1].encode('hex'))) c1 = ARC2.new(key[0], ARC2.MODE_ECB) c2 = ARC2.new(key[1], ARC2.MODE_ECB) while True: cipher = raw_input("Ciphertext> ").decode('hex') print("Plaintext: {}".format(c1.decrypt(c2.decrypt(cipher))))
msg = cipher.encrypt( plaintext ) print( 'Cifrando con DES' ) print( 'Texto original: {}' .format( plaintext ) ) print( 'key: {}' .format( key_3_Des ) ) print( 'Texto cifrado: {}' .format( msg ) ) #decipher decipher = DES3.new( key=key_3_Des , mode=DES3.MODE_CFB , iv=iv) decrypt_msg = decipher.decrypt( msg ) print( 'Texto decifrado: {} ' .format( decrypt_msg.decode('UTF-8') ) ) #RC2 plaintext = b'Cifrando con RC2' key = get_random_bytes( 16 ) iv = get_random_bytes( 8 ) cipher = ARC2.new( key=key , mode=ARC2.MODE_CFB , iv=iv ) msg = cipher.encrypt( plaintext ) print( 'Cifrando con RC2' ) print( 'Texto original: {}' .format( plaintext ) ) print( 'key: {}' .format( key ) ) print( 'Texto cifrado: {}' .format( msg ) ) decipher = ARC2.new( key=key, mode=ARC2.MODE_CFB , iv=iv ) decrypt_msg = decipher.decrypt( msg ) print( 'Texto decifrado: {} ' .format( decrypt_msg.decode('UTF-8') ) ) #modes of operation while True: try: key = DES3.adjust_key_parity( get_random_bytes(24) ) break
from Cryptodome.Cipher import ARC4 as pycryptodomex_arc4 from Cryptodome.Cipher import Blowfish as pycryptodomex_blowfish from Cryptodome.Cipher import DES as pycryptodomex_des from Cryptodome.Cipher import XOR as pycryptodomex_xor from Crypto.Hash import SHA from Crypto import Random from Crypto.Util import Counter from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers import modes from cryptography.hazmat.backends import default_backend from struct import pack key = b'Sixteen byte key' iv = Random.new().read(pycrypto_arc2.block_size) cipher = pycrypto_arc2.new(key, pycrypto_arc2.MODE_CFB, iv) msg = iv + cipher.encrypt(b'Attack at dawn') cipher = pycryptodomex_arc2.new(key, pycryptodomex_arc2.MODE_CFB, iv) msg = iv + cipher.encrypt(b'Attack at dawn') key = b'Very long and confidential key' nonce = Random.new().read(16) tempkey = SHA.new(key+nonce).digest() cipher = pycrypto_arc4.new(tempkey) msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') cipher = pycryptodomex_arc4.new(tempkey) msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') iv = Random.new().read(bs) key = b'An arbitrarily long key' plaintext = b'docendo discimus '
def rc2_decrypt_transform(data, key, mode, iv): arc2 = ARC2.new(key, mode, iv) return arc2.decrypt(data)
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 rc2_decrypt_transform(data, key, mode, iv): arc2 = ARC2.new(key, mode, iv) return arc2.decrypt(data)
def mitmPair(plain, cipher, key): c = ARC2.new(key, ARC2.MODE_ECB) enc = c.encrypt(plain) dec = c.decrypt(cipher) return (enc, dec, key)
def mitmFilter(plain, cipher, key): enc = ARC2.new(key[0], ARC2.MODE_ECB).encrypt(plain) dec = ARC2.new(key[1], ARC2.MODE_ECB).decrypt(cipher) return enc == dec
from Crypto.Cipher import ARC4 from Crypto.Cipher import Blowfish from Crypto.Cipher import DES from Crypto.Cipher import XOR from Crypto.Hash import SHA from Crypto import Random from Crypto.Util import Counter from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers import modes from cryptography.hazmat.backends import default_backend from struct import pack key = b'Sixteen byte key' iv = Random.new().read(ARC2.block_size) cipher = ARC2.new(key, ARC2.MODE_CFB, iv) msg = iv + cipher.encrypt(b'Attack at dawn') key = b'Very long and confidential key' nonce = Random.new().read(16) tempkey = SHA.new(key+nonce).digest() cipher = ARC4.new(tempkey) msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') bs = Blowfish.block_size key = b'An arbitrarily long key' iv = Random.new().read(bs) cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) plaintext = b'docendo discimus ' plen = bs - divmod(len(plaintext),bs)[1] padding = [plen]*plen
class Crypter(object): """Implements modern authenticated encryption for strings The current version (1) uses HMAC-SHA256 and AES256-CBC using Encrypt-then-MAC. Should be secure >>>2030 according to NIST standards. http://www.keylength.com/ for a summary of algorithms and expected security. The message is padded with null characters. This means that strings with null characters should not use this method unless a different padding scheme is added AES in GCM mode is faster, but the pycrypto implementation is immature. This may be a better choice for future versions. There is currently legacy support for decryption under the old key using ARC2 TODO(devinlundberg): remove legacy ARC2 decryption support """ __metaclass__ = SingletonType # Remove legacy crypter in future. _legacy_crypter = ARC2.new(PinballConfig.SECRET_KEY, ARC2.MODE_ECB) _aes_block_size = 16 _padding_char = '\x00' def _serialize(self, ciphertext, mac, **params): """Creates a serialized crypto object with current version and key""" encoded_params = {k: v.encode('base64') for k, v in params.items()} return json.dumps({ 'version': PinballConfig.CRYPTO_VERSION, 'ciphertext': ciphertext.encode('base64'), 'auth': mac.encode('base64'), 'params': encoded_params }).encode('base64') def _deserialize(self, encoded_ciphertext): """Gets version, ciphertext, auth, and params from serialized object""" try: ciphertext_json = encoded_ciphertext.decode('base64') except binascii.Error: raise CryptoException('Invalid Base64') try: ciphertext_obj = json.loads(ciphertext_json) except ValueError: raise CryptoException('Invalid JSON format') if any(key not in ciphertext_obj for key in ('version', 'ciphertext', 'auth', 'params')): raise CryptoException('Invalid JSON parameters') version = ciphertext_obj['version'] try: ciphertext = ciphertext_obj['ciphertext'].decode('base64') auth = ciphertext_obj['auth'].decode('base64') params = { k: v.decode('base64') for k, v in ciphertext_obj['params'].items() } except binascii.Error: raise CryptoException('Invalid Base64') except AttributeError: raise CryptoException('Unsupported types') return version, ciphertext, auth, params def _cbc_hmac_sha256_decrypt(self, ciphertext, auth, iv): """Authenticated decrypt using AES-CBC and HMAC SHA256 Encrypt-then-MAC""" hmac = HMAC.new(PinballConfig.HMAC_KEY, digestmod=SHA256) hmac.update(ciphertext) hmac.update(iv) if not compare_digest(hmac.hexdigest(), auth): raise CryptoException('Decryption Failed') aes = AES.new(PinballConfig.AES_CBC_KEY, AES.MODE_CBC, iv) return aes.decrypt(ciphertext).rstrip(self._padding_char) def encrypt(self, message): """Encrypts string of any length using the current crypto version Args: message: The string that needs to be encrypted. Returns: A serialized authenticated encrypted object """ iv = ''.join( chr(random.randint(0, 255)) for _ in range(self._aes_block_size)) aes = AES.new(PinballConfig.AES_CBC_KEY, AES.MODE_CBC, iv) hmac = HMAC.new(PinballConfig.HMAC_KEY, digestmod=SHA256) padded_length = (len(message) + self._aes_block_size - len(message) % (self._aes_block_size)) padded_message = message.ljust(padded_length, self._padding_char) ciphertext = aes.encrypt(padded_message) hmac.update(ciphertext) hmac.update(iv) return self._serialize(ciphertext, hmac.hexdigest(), iv=iv) def decrypt(self, encoded_ciphertext): """Deserializes and decrypts a string with the current or legacy algorithms Args: encoded_ciphertext: The string that needs to be decrypted. Returns: The decrypted message. Throws: CryptoException: on failed decryption. """ try: version, ciphertext, auth, params = self._deserialize( encoded_ciphertext) except CryptoException: # This should raise an exception when support for ARC2 ends. return self._legacy_crypter.decrypt(encoded_ciphertext).rstrip('0') if version == 1: if 'iv' not in params: raise CryptoException('Missing IV') return self._cbc_hmac_sha256_decrypt(ciphertext, auth, params['iv']) else: raise CryptoException('Unsupported Crypto Version')
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