def __parse_argon2(name: str, params: List[Tuple[str, Optional[str]]]) -> Argon2Kdf: ret = Argon2Kdf.sensitive() if name == "argon2": name = "argon2id" ret.type = Argon2Kdf.str_to_type(name) for key, value in params: if key == "fast": ret = Argon2Kdf.fast() elif key == "sensitive": ret = Argon2Kdf.sensitive() elif value is None: log.warning(f"Key '{key}' is unrecognized for argon2 and/or needs an associated value.") elif key in {"time_cost", "n", "n_iterations"}: vint = int(value) ret.time_cost = vint elif key in {"mem_cost", "mem", "m", "memory"}: mint = __parse_memory_unit(value) // 1024 ret.memory_cost = mint elif key in {"salt", "s"}: ret.salt = b64.decode(value) elif key in {"salt-len", "sl"}: sint = int(value) ret.salt = rand_unique_bytes(sint) elif key in {"parallelism", "para", "p"}: pint = int(value) ret.parallelism = pint else: log.warning(f"Unrecognized key '{key}' in params string.") return ret
def __parse_scrypt(name: str, params: List[Tuple[str, Optional[str]]]) -> ScryptKdf: ret = ScryptKdf.sensitive() if name != "scrypt": raise ValueError(f"Name must be 'scrypt'. Was '{name}'") for key, value in params: if key == "fast": ret = ScryptKdf.fast() elif key == "sensitive": ret = ScryptKdf.sensitive() elif value is None: log.warning(f"Key '{key}' is unrecognized for scrypt and/or needs an associated value.") elif key in {"log2n", "log2_n"}: ret.log2_n = int(value) elif key in {"n"}: ret.log2_n = int(floor(log2(float(value)))) elif key in {"r"}: ret.r = int(value) elif key in {"p"}: ret.p = int(value) elif key in {"salt", "s"}: ret.salt = b64.decode(value) elif key in {"salt-len", "sl"}: sint = int(value) ret.salt = rand_unique_bytes(sint) else: log.warning(f"Unrecognized key '{key}' in params string.") return ret
def main( str='L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ==', key=b'YELLOW SUBMARINE', nonce=0): enc = b64.decode(str) dec = AES.CTR_decrypt(key, enc, nonce) print(dec)
def get_ciphertexts(file): ciphers = [] f = open(file, 'r'); for line in f: line = line.rstrip('\r\n') bytes = b64.decode(line) ciphers.append(AES.CTR_encrypt(key, bytes, 0)) return ciphers
def _monitor(self): while True: line = self._serial.readline().strip() debug('Received raw comm input: %r', line) if len(line) < 4: continue if (not line.startswith(DEVICEID) and not line.startswith('d') and not line.startswith('e')): continue if line[1] == '$' and len(line) == 4: # ACK self._packetcond.acquire() index = None for (i, packet) in enumerate(self._packetlist): if line[2:4] == packet[-4:-2]: debug('Package ACK: %r', line) print('Package ACK: '+ line + '\n') index = i break if index is not None: try: self._packetlist.pop(index) except: pass if self._packetlist == []: self._packetcond.notify() self._packetcond.release() continue if not b64.valid(line): continue if b64.checksum(line[:-2]) != line[-2:]: continue self._lock.acquire() self._serial.write(line[1] + '$' + line[-2:] + '\r\n') self._serial.flush() self._lock.release() data = b64.decode(line[2:-2]) if line.startswith('d'): info('Debug message recieved: %r', data) print data elif line.startswith('e'): error('Error message recieved: %r', data) else: print data for callback in self._callbacks: thread.start_new_thread(callback, (data,))
def recv_response(self, dec_resp=False): response = '' while self.ready_to_read(): b_response = self.client.recv(self.BUF_SIZE) if not b_response: break if dec_resp and b_response[:3] == b'334': response += b_response[:4].decode() + \ b64.decode(b_response[4:-2]).decode() else: response += b_response.decode() if self.verbose: print('S: ' + response) return response
def _monitor(self): while True: line = self._serial.readline().strip() debug('Received raw comm input: %r', line) if len(line) < 4: continue if (not line.startswith(DEVICEID) and not line.startswith('d') and not line.startswith('e')): continue if line[1] == '$' and len(line) == 4: # ACK self._packetcond.acquire() index = None for (i, packet) in enumerate(self._packetlist): if line[2:4] == packet[-4:-2]: debug('Package ACK: %r', line) print('Package ACK: ' + line + '\n') index = i break if index is not None: try: self._packetlist.pop(index) except: pass if self._packetlist == []: self._packetcond.notify() self._packetcond.release() continue if not b64.valid(line): continue if b64.checksum(line[:-2]) != line[-2:]: continue self._lock.acquire() self._serial.write(line[1] + '$' + line[-2:] + '\r\n') self._serial.flush() self._lock.release() data = b64.decode(line[2:-2]) if line.startswith('d'): info('Debug message recieved: %r', data) print data elif line.startswith('e'): error('Error message recieved: %r', data) else: print data for callback in self._callbacks: thread.start_new_thread(callback, (data, ))
def deserialize( props: Dict[str, Union[str, int, bool, None, Dict, List]] ) -> "Aes256GcmCipher": ret = Aes256GcmCipher(b'') base_keys = set(ret.serialize().keys()) if not base_keys.issubset(props.keys()): raise ValueError( f"The properties dict is missing required keys {base_keys - props.keys()}" ) if props["algorithm"] != ret.serialize()["algorithm"]: raise ValueError( f"Expected an algo field of 'aes-256-gcm'. Got '{ret.serialize()['algo']}." ) ret.nonce = b64.decode(props["nonce"]) return ret
def deserialize( props: Dict[str, Union[str, int, bool, None, Dict, List]]) -> "Argon2Kdf": ret = Argon2Kdf.sensitive() base_keys = set(ret.serialize().keys()) if not base_keys.issubset(props.keys()): raise ValueError( f"The properties dict is missing required keys {base_keys - props.keys()}" ) ret.type = Argon2Kdf.str_to_type(props["algorithm"]) ret.version = props["version"] ret.time_cost = props["time_cost"] ret.memory_cost = props["memory_cost"] ret.parallelism = props["parallelism"] ret.salt = b64.decode(props["salt"]) return ret
def fetch_stream(episode_url): html = fetch_html(get_url(episode_url)) metadata = XML.ElementFromString( b64.decode( urllib.unquote( html.xpath('//html/body/div/div[2]/div/div[2]/input[@id="metadata"]')[0].get('value') ) ).replace("utf-16", "utf-8") ) episode_id = metadata.xpath('//movie/eid')[0].text cookie = Cookie.SimpleCookie(HTTP.CookiesForURL("http://www.turbofilm.tv"))["IAS_ID"].value source_hash = metadata.xpath('//movie/sources2/%s' % Prefs["quality"])[0].text # TODO: move to preferences. Example: 8a96c36ca917daa615c0153838e50eec position = "0" lang = Prefs["lang"] b = hashlib.sha1(cookie + str(random.random())).hexdigest() a = hashlib.sha1(b + episode_id + "A2DC51DE0F8BC1E9").hexdigest() return "http://cdn.turbofilm.tv/%s/%s/%s/%s/%s/%s/%s" % (hashlib.sha1(lang).hexdigest(), episode_id, source_hash, position, cookie, b, a)
def __parse_chacha20( name: str, params: List[Tuple[str, Optional[str]]]) -> ChaCha20Poly1305Cipher: ret = ChaCha20Poly1305Cipher() if name not in {"chacha20poly1305", "chacha20-poly1305"}: raise ValueError(f"Given name '{name}' is not aes-256-gcm") for key, value in params: if key in {"iv", "nonce"}: if value is None: value = '' byt = b64.decode(value) if len(byt) != 12: log.error("Nonce must be 12 bytes") sys.exit(0) ret.nonce = byt else: log.warning(f"Unrecognized key '{key}' in params string.") return ret
def deserialize( props: Dict[str, Union[str, int, bool, None, Dict, List]] ) -> "ChaCha20Poly1305Cipher": ret = ChaCha20Poly1305Cipher() base_keys = set(ret.serialize().keys()) if not base_keys.issubset(props.keys()): raise ValueError( f"The properties dict is missing required keys {base_keys - props.keys()}" ) if props["algorithm"] != ret.serialize()["algorithm"]: raise ValueError( f"Expected an algo field of 'aes-256-gcm'. Got '{ret.serialize()['algo']}." ) ret.nonce = b64.decode(props["nonce"]) if len(ret.nonce) != 12: raise ValueError(f"Decoded nonce must be 12 bytes") return ret
def deserialize( props: Dict[str, Union[str, int, bool, None, Dict, List]]) -> "ScryptKdf": ret = ScryptKdf.sensitive() base_keys = set(ret.serialize().keys()) if not base_keys.issubset(props.keys()): raise ValueError( f"The properties dict is missing required keys {base_keys - props.keys()}" ) if props["algorithm"] != "scrypt": raise ValueError( f"The algorithm field must be 'scrypt'. Was '{props['algorithm']}'" ) ret.log2_n = props["log2_n"] ret.r = props["r"] ret.p = props["p"] ret.salt = b64.decode(props["salt"]) return ret
def decode(self, byties): if not isinstance(byties, bytes): return byties pattern = re.compile( "=\?(?P<enc>.*?)\?(?P<qb>[BbQq])\?(?P<text>.*?)\?=") try: string = byties.decode('utf-8') except UnicodeError: return str(byties)[2:-1] found = re.finditer(pattern, string) for part in found: try: enc, qb, text = part.group("enc"), part.group("qb").lower(), \ part.group("text") if qb == "q": new_part = quopri.decodestring(text).decode(enc, errors="ignore") elif qb == "b": new_part = b64.decode(text).decode(enc, errors="ignore") string = string.replace(part.group(), new_part) except: return str(byties)[2:-1] return string
def __parse_aes256gcm( name: str, params: List[Tuple[str, Optional[str]]]) -> Aes256GcmCipher: ret = Aes256GcmCipher() if name not in { "aes256", "aes256gcm", "aes-256", "aes-256-gcm", "aes256-gcm" }: raise ValueError(f"Given name '{name}' is not aes-256-gcm") for key, value in params: if key in {"iv", "nonce"}: if value is None: value = '' ret.nonce = b64.decode(value) if key in {"iv-len", "nonce-len"}: if value is None: log.warning(f"No value given for key '{key}'.") iint = int(value) ret.nonce = rand_unique_bytes(iint) else: log.warning(f"Unrecognized key '{key}' in params string.") return ret
def b_decode(string): # base64 return b64.decode(string.encode())
#!/usr/bin/python3 # ToraNova ([email protected]) # cryptopals set 1 challenge 7 # THIS IS A SCRIPT import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend # mylibs import b64 # opens the file with open('files/aes-7.txt', 'r') as f: buf = f.read() buf = buf.replace('\n', '') buf = b64.decode(buf) key = 'YELLOW SUBMARINE'.encode('utf8') print(key) # initialize AES cipher in ECB mode cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) de = cipher.decryptor() msg = de.update(buf) + de.finalize() print(msg.decode('utf8'))