def atos(data, separator=' ', fmt='02X'): """ Convert array of bytes to string :param data: Data in bytes or bytearray type :param separator: String separator :param fmt: String format :return string """ ret = '' for x in data: if fmt == 'c' and x not in printable.encode(): ret += '.' continue ret += ('{:' + fmt + '}').format(x) ret += separator return ret
def string_test(prop, allow_multiline=True): """ Check if a property (byte array) is a string Args: prop: (libfdt or byte property) Returns: boolean: True if the property looks like a string """ if not len(prop): return False if prop[-1] != 0: return False byte = 0 while byte < len(prop): bytei = byte while byte < len( prop ) and \ prop[byte] != 0 and \ prop[byte] in printable.encode() and \ prop[byte] not in (ord('\r'), ord('\n')): byte += 1 if prop[byte] in (ord('\r'), ord('\n')): if allow_multiline: byte += 1 continue # if we broke walking through the positions, and # we aren't on a null (multiple strings) or are # where we started, then this isn't a string. if prop[byte] != 0 or byte == bytei: if byte + 3 < len(prop): if prop[byte:byte + 3] == b'\xe2\x80\x9c' or prop[ byte:byte + 3] == b'\xe2\x80\x9d': #print( "jumping ahead, looks like an escaped quote" ) byte += 3 continue return False byte += 1 return True
def is_string(data): """ Check property string validity """ if not len(data): return None if data[-1] != 0: return None pos = 0 while pos < len(data): posi = pos while pos < len(data) and \ data[pos] != 0 and \ data[pos] in printable.encode() and \ data[pos] not in (ord('\r'), ord('\n')): pos += 1 if data[pos] != 0 or pos == posi: return None pos += 1 return True
def is_string(data): """ Check property string validity """ if not len(data): return if data[(-1)] != 0: return pos = 0 while pos < len(data): posi = pos while pos < len(data): if data[pos] != 0: if data[pos] in printable.encode(): if data[pos] not in (ord('\r'), ord('\n')): pos += 1 if data[pos] != 0 or pos == posi: return else: pos += 1 return True
def english_chi_squared(a): letter_freq = { 'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.70, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, 'o': 7.507, 'p': 1.929, 'q': 0.095, 'r': 5.987, 's': 6.327, 't': 9.056, 'u': 2.758, 'v': 0.978, 'w': 2.360, 'x': 0.150, 'y': 1.974, 'z': 0.074, } letter_freq.update((k, v * len(a) / 100) for k, v in letter_freq.items()) for c in a: if not c in printable.encode('UTF-8'): return 1000 * 1000 return sum([ ((letter_freq[l] - a.count(l.encode('UTF-8')))**2 / letter_freq[l]) for l in ascii_lowercase ])
# https://blog.shi1011.cn/ctf/2162 # http://s0rry.cn/archives/vnctf2022re-fu-xian#toc-head-6 from string import printable _m = list(printable.encode()) _m.remove(10) _m.remove(13) _hex = lambda _d: "0x" + hex(_d)[2:].zfill(2) if _d > 15 else _d _chr = lambda _v: hex(_v) if _v not in _m else "'{ch}'".format(ch=chr(_v)) maps = { 0x1: "nop", 0x2: "mov R[{num}], {right} ; {ch}", 0x3: "mov R[{num}], R[{right}]", 0x4: "mov R[{num}], Memory[{right}]", 0x5: "mov Memory[num] R[{right}]", 0x6: "push R[{num}]", 0x7: "pop R[{num}]", 0x8: "add R[{num}], R[{right}]", 0x9: "dec R[{num}], R[{right}]", 0xa: "div R[{num}], R[{right}]", 0xb: "mul R[{num}], R[{right}]", 0xc: "xor R[{num}], R[{right}]", 0xd: "jmp R[{num}]", 0xe: "cmp R[{num}] R[{right}], je R[19]", 0xf: "cmp R[{num}] R[{right}], jne R[19]", 0x10: "cmp R[{num}] R[{right}], jb R[19]", 0x11: "cmp R[{num}] R[{right}], ja R[19]", 0x62: "getchar R[{num}]", 0x63: "putchar R[{num}]", 0x64: "vm quit" }
from base64 import b64decode from string import printable import numpy as np from utilities import ecb_encrypt, randomkey from challenge11 import tester from challenge12 import get_blocksize printable = printable.encode() key = randomkey() prefix = np.random.randint(0x100, size=np.random.randint(5, 10)) prefix = np.uint8(prefix).tostring() unknown_string = b64decode( b'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK' ) def encryptor(plaintext): return ecb_encrypt(prefix + plaintext + unknown_string, key) def get_prefix_complement(encryptor, bsize): for prefcomp in range(bsize): testtext = b'a' * (2 * bsize + prefcomp) crypted = encryptor(testtext) if crypted[bsize:2 * bsize] == crypted[bsize * 2:bsize * 3]: break # have the complement of the prefix len return prefcomp
from six import BytesIO from DateTime.DateTime import DateTime from OFS.Folder import Folder from OFS.Image import File from Testing.ZopeTestCase import ZopeTestCase from .common import FilesystemTestBase from .common import TarballTester from .conformance import ConformsToIChunkableExportContext from .conformance import ConformsToIChunkableImportContext from .conformance import ConformsToIExportContext from .conformance import ConformsToIImportContext from .conformance import ConformsToISetupContext printable_bytes = printable.encode('utf-8') digits_bytes = digits.encode('utf-8') class DummySite(Folder): pass class DummyTool(Folder): pass class DummyPdataStreamIterator:
import re from string import printable import os import queue import subprocess import discord import asyncio import threading import time from ...utils import DBView from .base import GameSystem, GameError, JoinLeaveProhibited, GameEndException from math import ceil, floor printable_set = set(printable) printable_bytes = printable.encode() def avg(n): return sum(n)/len(n) class BackgroundGameExit(GameError): pass more_patterns = [ re.compile(r'\*+(MORE|more)\*+'), # Match ****MORE**** re.compile(r'.*\.\.\.+\s*$') # Match .... ] score_patterns = [ re.compile(r'([0-9]+)/[0-9]+'), re.compile(r'Score:[ ]*([-]*[0-9]+)'), re.compile(r'([0-9]+):[0-9]+ [AaPp][Mm]'),
# coding: utf-8 import base64 import re from collections import namedtuple from string import printable as printable_charset from typing import List from pyshark.packet.packet import Packet CreditCard = namedtuple("CreditCard", ['name', 'number']) STRING_EXTRACT_REGEX = re.compile(b"[^" + printable_charset.encode() + b"]+") class Credentials(object): def __init__(self, username=None, password=None, hash=None, context=None): self.username = username self.password = password self.hash = hash self.context = context if context else {} def __eq__(self, other): for item in self.context: if item not in other.context or self.context[ item] != other.context[item]: return False return self.username == other.username \ and self.password == other.password \ and self.hash == other.hash
from binascii import unhexlify from collections import Counter from string import ascii_letters, printable from Crypto.Util.strxor import strxor_c from utilities import highscore_xor if __name__ == '__main__': ciphertext = unhexlify( b'1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' ) key = highscore_xor(set(printable.encode()), ciphertext) print(chr(key)) print(strxor_c(ciphertext, key))
from string import printable from collections import Counter import struct import numpy as np from Crypto.Cipher import AES from Crypto.Util.strxor import strxor, strxor_c most_common = set(b'etaoin shrdlu') unprintable = set(range(0x100)).difference(set(printable.encode())) def u32_bool(num): return np.fromiter(((num & 2**i) // 2**i for i in range(31, -1, -1)), np.bool) def bool_u32(boolarr): return (boolarr * np.power(2, np.arange(31, -1, -1))).sum() def randomkey(size=16): return np.uint8(np.random.randint(0x100, size=size)).tostring() def highscore_xor(keyspace, ciphertext): # returns the key with the highest number of characters in the most_common # set, and no unprintable characters # any character in the ciphertext is excluded as null byte generating keyspace = keyspace.difference(set(ciphertext))
def nonprintable_to_dots(): printable_bytes = printable.encode()[:-5] return bytes.join( b'', [bytes([c]) if c in printable_bytes else b'.' for c in range(256)])
cbd27e9b76c7ad85ae3f36cbe78e546d45327ed1a50787d9c3b989af27e62bf0 44ba660a6bd8ff6b11b3423f9f3bf0dff4550cc6eb7b2e8a09ed3d4694faeb83 5e07d6fdc602b0f9b99f6ea24c39e65835992faac400264c52449bc409cf4efa 7b774effe4a349c6dd82ad4f4f21d34c c0828e0381730befd1f7a025057c74fb c195aeabeeee007891190b9ff8a32c70 a87ff679a2f3e71d9181a67b7542122c 67d4143062b55c25f383c9fabbbf1422fad06a2fe0644b43da67c17886dd4bd4 b14a7b8059d9c055954c92674ce60032 50e721e49c013f00c62cf59f2163542a9d8df02464efeb615d31051b0fddc326 97fb5f8538b89f6c1accfd19836b65a73b61fbc2e0cbf84bb858a0fffa3f1592 1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9 24cafc74b88dfafb0524ecc85a76f8bd 3fffd018d2223020be85670d93f565b63df54a9ce3ed2cdf6347a61df016938c 2510c39011c5be704182423e3a695e91 582967534d0f909d196b97f9e6921342777aea87b46fa52df165389db1fb8ccf cd0aa9856147b6c5b4ff2b7dfee5da20aa38253099ef1b4a64aced233c9afe29 d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2""".split('\n') table = {} for L in range(1, 3): print("calculating hashes of length", L) for tup in product(chars.encode(), repeat=L): s = bytearray(tup) table[md5(s).digest().hex()] = s.decode() table[sha256(s).digest().hex()] = s.decode() for h in hashes: print(table[h], end='')
from tarfile import TarInfo from DateTime.DateTime import DateTime from OFS.Folder import Folder from OFS.Image import File from .common import FilesystemTestBase from .common import TarballTester from .conformance import ConformsToISetupContext from .conformance import ConformsToIImportContext from .conformance import ConformsToIExportContext from .conformance import ConformsToIChunkableExportContext from .conformance import ConformsToIChunkableImportContext printable_bytes = printable.encode('utf-8') digits_bytes = digits.encode('utf-8') class DummySite(Folder): pass class DummyTool(Folder): pass class DummyPdataStreamIterator:
def keygen(length=16): return b''.join( [bytes([i]) for i in random.choices(valid_chars.encode(), k=length)])