def arc4_timer(test_vectors): """Encrypts (Alleged-RC4) each element of test_vector and returns a list of tuples with (encryption time, decryption time) """ timelist = [] for vector in test_vectors: #test_vector elements are of byte type #key generation, we opted for generating our own keys and not using the provided at the test vectors key = secrets.token_bytes(32) #secrets provides the most secure pseudo-random function the os has #print(key) #end of key generation #creating a cipher object cipher = Cipher(algorithms.ARC4(key), mode = None, backend = default_backend()) encryptor = cipher.encryptor() #encryption begins start_e = timer() ciphertext = encryptor.update(vector) + encryptor.finalize() end_e = timer() #encryption ends -this is the fragment we should time for encryption time #print("ciphertext: " + str(ciphertext)) decryptor = cipher.decryptor() #decryption begins start_d = timer() plaintext_d = decryptor.update(ciphertext) + decryptor.finalize() end_d = timer() #decryption ends -this is the fragment we should time for decryption time #print("Deciphered text: "+ str(plaintext_d)) timelist.append((end_e - start_e, end_d - start_d)) return timelist
def get_cipher(key, method, op, iv): if method == 'bypass': return bypass() if method in ('salsa20', 'chacha20', 'chacha20-ietf'): return Salsa20Crypto(method, key, iv, op) elif method == 'rc4-md5': md5 = hashlib.md5() md5.update(key) md5.update(iv) key = md5.digest() method = 'rc4' cipher = None if method.startswith('rc4'): pass elif method.endswith('ctr'): mode = modes.CTR(iv) elif method.endswith('ofb'): mode = modes.OFB(iv) elif method.endswith('cfb'): mode = modes.CFB(iv) else: raise ValueError('operation mode "%s" not supported!' % method.upper()) if method.startswith('rc4'): cipher = Cipher(algorithms.ARC4(key), None, default_backend()) elif method.startswith('aes'): cipher = Cipher(algorithms.AES(key), mode, default_backend()) elif method.startswith('camellia'): cipher = Cipher(algorithms.Camellia(key), mode, default_backend()) else: raise ValueError('crypto algorithm "%s" not supported!' % method.upper()) return cipher.encryptor() if op else cipher.decryptor()
def cli(filename): """Send file over to server""" s = socket.socket() host = '172.30.7.187' port = 4567 click.echo(click.style('Connecting...', bold=True, fg='yellow')) try: s.connect((host, port)) except socket.error as msg: click.echo( click.style('Error connecting to server: ' + str(msg[1]), bold=True, fg='red')) pt = b"" while True: chunk = filename.read(100) if not chunk: break pt += chunk key = open("key.txt", "rb").read(16) cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(pt) s.send(ct) s.close() click.echo(click.style('File sent!', bold=True, fg='green'))
def setup_cipher_rc4(salt, password, encrypt=False): hash = Hash(SHA1(), default_backend()) hash.update(salt + bytes(password, 'ascii')) cipher = Cipher(algorithms.ARC4(hash.finalize()), None, default_backend()) cryptor = cipher.encryptor() if encrypt else cipher.decryptor() cryptor.update(bytes(RC4_SKIP)) return cryptor
def encrypt(nonce, counter, data): try: nonce = bytes.fromhex(nonce) assert len(nonce) == NONCESIZE counter = int(counter) assert counter >= 0 counter = counter.to_bytes(length=COUNTERSIZE, byteorder="little", signed=False) data = bytes.fromhex(data) assert len(data) == BLOCKSIZE except Exception as e: logging.error("Failed to validate inputs", exc_info=e) return "Failed to validate inputs." block_key = nonce + counter + RC4_KEY cipher = Cipher(algorithm=algorithms.ARC4(block_key), mode=None, backend=default_backend()) encryptor = cipher.encryptor() ciphertext_bytes = encryptor.update(data) return ciphertext_bytes.hex()
def __init__(self, key): if isinstance(key, str): key = key.encode('utf-8') cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) self.encrypter = cipher.encryptor()
def get_msg_from_queue(s, msg_buffers, recv_len, msg_len, msg_ids, symmetric_keys): recv_str = msg_buffers[s] ret_str = '' if recv_str is not None: # Recommended spot for decryption of symmetric cipher if s in symmetric_keys and symmetric_keys[s]: algorithm = algorithms.ARC4(symmetric_keys[s]) cipher = Cipher(algorithm, mode=None, backend=default_backend()) decryptor = cipher.decryptor() recv_str = decryptor.update(recv_str) try: ret_str = recv_str.decode() except BaseException: ret_str = recv_str del msg_buffers[s] del recv_len[s] del msg_len[s] id = None if s in msg_ids: id = msg_ids[s] del msg_ids[s] return id, ret_str
def __read_and_decrypt(self, filename, password): """ Reads and decrypts files using the given password expanded as a key Arguments: filename - The filename to open and decrypt password - Tha password to expand and use as key Returns: String containing decrypted contents """ if(type(password) is str): password = str.encode(password) key = KeyStore.__generate_key(password) file_ = open(filename, 'rb') cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) decryptor = cipher.decryptor() ct = file_.read() dt = decryptor.update(ct) return dt.decode("utf-8")
def decrypt(password, salt, keySize, ibuf, blocksize=0x200): r''' Return decrypted data. ''' obuf = io.BytesIO() block = 0 key = _makekey(password, salt, keySize, block) for c, buf in enumerate(iter(functools.partial(ibuf.read, blocksize), b'')): cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) decryptor = cipher.decryptor() dec = decryptor.update(buf) + decryptor.finalize() obuf.write(dec) # From wvDecrypt: # at this stage we need to rekey the rc4 algorithm # Dieter Spaar <*****@*****.**> figured out # this rekeying, big kudos to him block += 1 key = _makekey(password, salt, keySize, block) obuf.seek(0) return obuf
def _build_vectors(): count = 0 output = [] key = None plaintext = binascii.unhexlify(32 * '0') for size in _SIZES_TO_GENERATE: for keyinfo in _RFC6229_KEY_MATERIALS: key = _key_for_size(size, keyinfo) cipher = ciphers.Cipher(algorithms.ARC4(binascii.unhexlify(key)), None, default_backend()) encryptor = cipher.encryptor() current_offset = 0 for offset in _RFC6229_OFFSETS: if offset % 16 != 0: raise ValueError( "Offset {} is not evenly divisible by 16".format( offset)) while current_offset < offset: encryptor.update(plaintext) current_offset += len(plaintext) output.append("\nCOUNT = {}".format(count)) count += 1 output.append("KEY = {}".format(key)) output.append("OFFSET = {}".format(offset)) output.append("PLAINTEXT = {}".format( binascii.hexlify(plaintext))) output.append("CIPHERTEXT = {}".format( binascii.hexlify(encryptor.update(plaintext)))) current_offset += len(plaintext) assert not encryptor.finalize() return "\n".join(output)
def encrypt(secret, plaintext, nosalt=False): """Given the first 16 bytes of splunk.secret, encrypt a Splunk password""" if len(secret) < 16: raise ValueError("secret too short, need 16 bytes, got %d" % len(secret)) key = secret[:16] chars = [] if nosalt is False: for char1, char2 in zip(plaintext, itertools.cycle("DEFAULTSA")): if ord(char1) == ord(char2): chars.append(ord(char1)) else: chars.append(ord(char1) ^ ord(char2)) else: chars = [ord(x) for x in plaintext] chars.append(0) plaintext = b"".join([six.int2byte(c) for c in chars]) algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext) return "$1$%s" % base64.b64encode(ciphertext).decode()
def __init__(self, flags, session_key): self._key = _Ntlm1Session._weaken_key(flags, session_key) cipher = Cipher(algorithms.ARC4(self._key), mode=None, backend=default_backend()) self._encrypt = cipher.encryptor() self._decrypt = cipher.decryptor() self._sequence = 0
def get_cipher(self, iv): md5 = hashlib.md5() md5.update(self.key) md5.update(iv) rc4_key = md5.digest() return Cipher(algorithms.ARC4(rc4_key), None, backend=default_backend())
def ARC4_encrypt(key, data, skip=0): """Encrypt data @data with key @key, skipping @skip first bytes of the keystream""" algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) encryptor = cipher.encryptor() if skip: encryptor.update("\x00" * skip) return encryptor.update(data)
def decrypt(self, key=None): if key is None: key = conf.wepkey if key and conf.crypto_valid: d = Cipher( algorithms.ARC4(self.iv + key.encode("utf8")), None, default_backend(), ).decryptor() self.add_payload(LLC(d.update(self.wepdata) + d.finalize()))
def store_key(key, keystore_file, master_password): """Encrypts file with the given password using RC4""" if(type(master_password) is str): master_password = str.encode(master_password) cipher = Cipher(algorithms.ARC4(master_password), mode=None, backend=default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(key) keystore_file.write(ct)
def DRC4(key, file_path, iv): # RC4 decryption function f = open(file_path, "rb") content = f.read() f.close() backend = default_backend() cipher = Cipher(algorithms.ARC4(key), mode=None, backend=backend) decryptor = cipher.decryptor() content = decryptor.update(content) + decryptor.finalize() f = open(file_path, "wb") f.write(content) f.close()
class TestARC4(object): test_rfc = generate_stream_encryption_test( load_nist_vectors, os.path.join("ciphers", "ARC4"), [ "rfc-6229-40.txt", "rfc-6229-56.txt", "rfc-6229-64.txt", "rfc-6229-80.txt", "rfc-6229-128.txt", "rfc-6229-192.txt", "rfc-6229-256.txt", "arc4.txt" ], lambda key, **kwargs: algorithms.ARC4(binascii.unhexlify(key)), )
def rc4(message, key): """ Simple wrapper for RC4 cipher that encrypts message with key :param str message: input to encrypt :param str key: encryption key :return: ciphertext :rtype: str """ algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) encryptor = cipher.encryptor() return encryptor.update(message)
def encrypt(cls, key, keyusage, plaintext, confounder): if confounder is None: confounder = get_random_bytes(8) ki = HMAC_HASH(key.contents, cls.usage_str(keyusage), hashes.MD5) cksum = HMAC_HASH(ki, confounder + plaintext, hashes.MD5) ke = HMAC_HASH(ki, cksum, hashes.MD5) encryptor = Cipher( ciphers.ARC4(ke), None, default_backend()).encryptor() ctext = encryptor.update(confounder + plaintext) return cksum + ctext
def decrypt(secret, ciphertext, nosalt=False): """Given the first 16 bytes of splunk.secret, decrypt a Splunk password""" plaintext = None if ciphertext.startswith("$1$"): ciphertext = b64decode(ciphertext[3:]) if len(secret) < 16: raise ValueError("secret too short, need 16 bytes, got %d" % len(secret)) key = secret[:16] algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) chars = [] if nosalt is False: for char1, char2 in zip(plaintext[:-1], itertools.cycle("DEFAULTSA")): if six.byte2int([char1]) == ord(char2): chars.append(six.byte2int([char1])) else: chars.append(six.byte2int([char1]) ^ ord(char2)) else: chars = [six.byte2int([char]) for char in plaintext[:-1]] plaintext = "".join([six.unichr(c) for c in chars]) elif ciphertext.startswith("$7$"): if len(secret) < 254: raise ValueError("secret too short, need 254 bytes, got %d" % len(secret)) ciphertext = b64decode(ciphertext[3:]) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b"disk-encryption", iterations=1, backend=default_backend()) key = kdf.derive(secret[:254]) iv = ciphertext[:16] # pylint: disable=invalid-name tag = ciphertext[-16:] ciphertext = ciphertext[16:-16] algorithm = algorithms.AES(key) cipher = Cipher(algorithm, mode=modes.GCM(iv, tag), backend=default_backend()) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext).decode() return plaintext
def load_key(keystore_file, master_password): """Decrypts file with the given password using RC4""" if(type(master_password) is str): master_password = str.encode(master_password) cipher = Cipher(algorithms.ARC4(master_password), None, backend=default_backend()) decryptor = cipher.decryptor() ct = keystore_file.read() dt = decryptor.update(ct) return dt
def verifypw(password, salt, keySize, encryptedVerifier, encryptedVerifierHash, algId=0x00006801): r''' Return True if the given password is valid. ''' # https://msdn.microsoft.com/en-us/library/dd953617(v=office.12).aspx block = 0 key = _makekey(password, salt, keySize, block) cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) decryptor = cipher.decryptor() verifier = decryptor.update(encryptedVerifier) verfiferHash = decryptor.update(encryptedVerifierHash) hash = sha1(verifier).digest() logging.debug([verfiferHash, hash]) return hash == verfiferHash
def __init__(self, flags, session_key, mode): self.key_exchange = True self.outgoing_sequence = 0 self.incoming_sequence = 0 session_key = _Ntlm2Session._weaken_key(flags, session_key) #logger.debug("Session Key after Weakening: %s", AsHex(session_key)) client_signing_key = _Ntlm2Session._generate_key( session_key + _Ntlm2Session.client_signing) server_signing_key = _Ntlm2Session._generate_key( session_key + _Ntlm2Session.server_signing) client_sealing_key = _Ntlm2Session._generate_key( session_key + _Ntlm2Session.client_sealing) server_sealing_key = _Ntlm2Session._generate_key( session_key + _Ntlm2Session.server_sealing) if mode == 'client': self.outgoing_signing_key = client_signing_key self.incoming_signing_key = server_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(client_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(server_arc4, mode=None, backend=default_backend()).decryptor() elif mode == 'server': self.outgoing_signing_key = server_signing_key self.incoming_signing_key = client_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(server_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(client_arc4, mode=None, backend=default_backend()).decryptor()
def encrypt(key, plaintext): """Given the first 16 bytes of splunk.secret, encrypt a Splunk password""" chars = [] for char1, char2 in zip(plaintext, itertools.cycle("DEFAULTSA")): chars.append(ord(char1) ^ ord(char2)) chars.append(0) plaintext = b"".join([six.int2byte(c) for c in chars]) algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext) return "$1$%s" % base64.b64encode(ciphertext).decode()
def decrypt(key, ciphertext): """Given the first 16 bytes of splunk.secret, decrypt a Splunk password""" if ciphertext.startswith("$1$"): ciphertext = base64.b64decode(ciphertext[3:]) algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None, backend=default_backend()) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) chars = [] for char1, char2 in zip(plaintext[:-1], itertools.cycle("DEFAULTSA")): chars.append(six.byte2int([char1]) ^ ord(char2)) return "".join([six.unichr(c) for c in chars])
def _DecryptARC4(self, key, data): """Decrypts ARC4 encrypted data. Args: key (str): key used to decrypt the data. data (bytes): data to decrypt. Returns: bytes: decrypted data. """ algorithm = algorithms.ARC4(key) backend = backends.default_backend() cipher = ciphers.Cipher(algorithm, mode=None, backend=backend) cipher_context = cipher.decryptor() return cipher_context.update(data)
def decrypt_RC4(connection, outfile): key = open("key.txt", 'rb').read(16) cipher = Cipher(algorithms.ARC4(key), None, backend=default_backend()) decryptor = cipher.decryptor() ct = b"" while True: chunk = connection.recv(50) if not chunk: break ct += chunk dt = decryptor.update(ct) outfile.write(dt) click.echo(click.style('Decryption successful!', bold = True, fg = 'green'))
def utils_encrypt_plainfile(filename, password, output): file_ = open(filename, 'rb') file_out = open(output, 'wb') if(type(password) is str): password = str.encode(password) key = KeyStore.__generate_key(password) cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) encryptor = cipher.encryptor() bite_stream = file_.read() ct = encryptor.update(bite_stream) file_out.write(ct)
def get_encryptor(algoname, key, iv=None, mode='ecb', padd='pkcs7'): backend = default_backend() if algoname == 'ChaCha20': algoer = algorithms.ChaCha20(key, iv) cipher = Cipher(algoer, None, backend=backend) elif algoname == 'ARC4': algoer = algorithms.ARC4(key) cipher = Cipher(algoer, None, backend=backend) else: algoer = algos[algoname](key) if mode == 'ecb': mode = modes.ECB() if mode == 'cfb': mode = modes.CFB(iv) if mode == 'ofb': mode = modes.OFB(iv) if mode == 'cbc': mode = modes.CBC(iv) if mode == 'ctr': mode = modes.CTR(iv) cipher = Cipher(algoer, mode, backend=backend) def enc(bitstring): if algoname not in ['ARC4', 'ChaCha20']: if padd.upper() == 'PKCS7': padder = padding.PKCS7(algoer.block_size).padder() bitstring = padder.update(bitstring) + padder.finalize() elif padd.upper() == 'ANSIX923': padder = padding.ANSIX923(algoer.block_size).padder() bitstring = padder.update(bitstring) + padder.finalize() encryptor = cipher.encryptor() return encryptor.update(bitstring) + encryptor.finalize() def dec(bitstring): decryptor = cipher.decryptor() ddata = decryptor.update(bitstring) + decryptor.finalize() if algoname not in ['ARC4', 'ChaCha20']: if padd.upper() == 'PKCS7': unpadder = padding.PKCS7(algoer.block_size).unpadder() ddata = unpadder.update(ddata) + unpadder.finalize() elif padd.upper() == 'ANSIX923': unpadder = padding.ANSIX923(algoer.block_size).unpadder() ddata = unpadder.update(ddata) + unpadder.finalize() return ddata class f: pass f.encrypt = enc f.decrypt = dec return f