def test1(self): padded = pad(b(""), 4) self.assertTrue(padded == uh(b("04040404"))) padded = pad(b(""), 4, 'pkcs7') self.assertTrue(padded == uh(b("04040404"))) back = unpad(padded, 4) self.assertTrue(back == b(""))
def test1(self): padded = pad(b(""), 4) self.failUnless(padded == uh(b("04040404"))) padded = pad(b(""), 4, 'pkcs7') self.failUnless(padded == uh(b("04040404"))) back = unpad(padded, 4) self.failUnless(back == b(""))
def encrypt(self, file_path): if not os.path.exists(file_path): raise ValueError('Input file path not exists: %s ', file_path) with open(file_path, 'rb') as f: data_to_encrypt = f.read() return self.cipher.encrypt(pad(data_to_encrypt, self.multiple_of_byte))
def encrypt(self, string): pad_byte_string = pad(string.encode('utf-8'), self.multiple_of_byte) encrypt_byte_string = self.cipher.encrypt(pad_byte_string) if self.use_urlsafe: encrypt_string = base64.urlsafe_b64encode(encrypt_byte_string).decode('ascii') else: encrypt_string = base64.b64encode(encrypt_byte_string).decode('ascii') return encrypt_string
def encrypt(self, original_string): self.cipher = self.gen_cipher() # 将原字符串长度补齐到AES.block_size的整数倍长度 pad_byte_string = pad(original_string.encode('utf-8'), AES.block_size) ct_bytes = self.cipher.encrypt(pad_byte_string) if self.use_urlsafe: encrypt_string = base64.urlsafe_b64encode(ct_bytes).decode('utf-8') else: encrypt_string = base64.b64encode(ct_bytes).decode('utf-8') return encrypt_string
def file_encrypt(password, file_path, output_file_path): key = generate_key(password) # 使用ECB模式进行加密解密 cipher = AES.new(key, AES.MODE_ECB) # 设置加密解密时分块读取10240KB read_kb = 10240 block_size = read_kb * 1024 data_handle_func = cipher.encrypt # 读取到文件尾部时,执行尾部补位操作后加密 data_end_handle_func = lambda d: cipher.encrypt(pad(d, MULTIPLE_OF_BYTE)) file_handle(file_path, output_file_path, block_size, data_handle_func, data_end_handle_func)
def encrypt(hstr, payload, encryptionKey): paddedEncryptionKey = pad(encryptionKey, AES.block_size) key = base64.b64encode(paddedEncryptionKey) cipher = AES.new(key, AES.MODE_CTR) hstrBytes = base64.b64encode(cipher.encrypt(hstr)).decode('utf-8') payloadBytes = base64.b64encode(cipher.encrypt(payload)).decode('utf-8') nonce = base64.b64encode(cipher.nonce).decode('utf-8') return [hstrBytes, payloadBytes, nonce]
def encode(data, marker, passphrase=None, randfunc=None): """Encode a piece of binary data into PEM format. Args: data (byte string): The piece of binary data to encode. marker (string): The marker for the PEM block (e.g. "PUBLIC KEY"). Note that there is no official master list for all allowed markers. Still, you can refer to the OpenSSL_ source code. passphrase (byte string): If given, the PEM block will be encrypted. The key is derived from the passphrase. randfunc (callable): Random number generation function; it accepts an integer N and returns a byte string of random data, N bytes long. If not given, a new one is instantiated. Returns: The PEM block, as a string. .. _OpenSSL: https://github.com/openssl/openssl/blob/master/include/openssl/pem.h """ if randfunc is None: randfunc = get_random_bytes out = "-----BEGIN %s-----\n" % marker if passphrase: # We only support 3DES for encryption salt = randfunc(8) key = PBKDF1(passphrase, salt, 16, 1, MD5) key += PBKDF1(key + passphrase, salt, 8, 1, MD5) objenc = DES3.new(key, DES3.MODE_CBC, salt) out += "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n" %\ tostr(hexlify(salt).upper()) # Encrypt with PKCS#7 padding data = objenc.encrypt(pad(data, objenc.block_size)) elif passphrase is not None: raise ValueError("Empty password") # Each BASE64 line can take up to 64 characters (=48 bytes of data) # b2a_base64 adds a new line character! chunks = [tostr(b2a_base64(data[i:i + 48])) for i in range(0, len(data), 48)] out += "".join(chunks) out += "-----END %s-----" % marker return out
def send_encrypted_msg(sock, msg, key): cipher = AES.new(key, AES.MODE_CBC) encrypted = cipher.encrypt(pad(msg.encode(), AES.block_size)) data = encrypted + cipher.iv data = len(data).to_bytes(4, byteorder='big') + data sock.send(data)
def encrypt_message(self, message: str) -> bytes: iv = Random.get_random_bytes(16) cipher = AES.new(self.session_key, AES.MODE_CBC, iv) cipher_text = iv + cipher.encrypt(pad(message.encode(), AES.block_size)) return cipher_text
def write(self, data): """Write data.""" if len(data) % BLOCK_SIZE != 0: data = pad(data, BLOCK_SIZE) self._file.write(self._aes.encrypt(data))
def encrypt_bytes(symmetric_key: bytes, message: bytes): aes = AES.new(key=symmetric_key, mode=AES.MODE_CBC) ciphertext = aes.encrypt(pad(data_to_pad=message, block_size=Constants.AES_BLOCK_SIZE)) iv = aes.iv return ciphertext, iv
block_size = 16 b64d = lambda x: base64.decodestring(x.replace('~', '=').replace('!', '/').replace('-', '+')) b64e = lambda x: base64.b64encode(x).replace('=', '~').replace('/', '!').replace('+', '-') data = { "flag": "^FLAG^6bd8dc9702e4bc4a9ea80736f00ec6bd528e7c41c9e9cdc12bc1555adf725e2f$FLAG$", "id": "21", "key": b64e(key), } dump = json.dumps(data) encoded = dump.encode("utf8") assert encoded == dump assert encoded == '{"flag": "^FLAG^6bd8dc9702e4bc4a9ea80736f00ec6bd528e7c41c9e9cdc12bc1555adf725e2f$FLAG$", "id": "21", "key": "8JAiOeF!BAzbRwSrKL4IHg~~"}' padded = pad(encoded, block_size, style="pkcs7") assert padded == '{"flag": "^FLAG^6bd8dc9702e4bc4a9ea80736f00ec6bd528e7c41c9e9cdc12bc1555adf725e2f$FLAG$", "id": "21", "key": "8JAiOeF!BAzbRwSrKL4IHg~~"}\t\t\t\t\t\t\t\t\t' def encrypt(key): cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = cipher.encrypt(padded) cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(encrypted) assert decrypted == padded querystring = b64e(iv + encrypted) print repr(encrypted)
def main(): s = b'YELLOW SUBMARINE' block_size = 20 print(pad(s, block_size))
import base64 from Crypto.Cipher import AES from Crypto.Util.Padding import unpad from urllib.parse import urlencode from Crypto.Util.Padding import pad uid = 'a' iv = b"VFNSJQXI0P6IZ7UC" key = b"HQR9NSTXMCY7R463" uid = "CHECKOK_" + uid bi_data = uid.encode("UTF-8") cipher = AES.new(key, AES.MODE_CBC, iv) encode_uid = base64.b64encode(cipher.encrypt(pad(bi_data, AES.block_size))).decode() url = "https://casino.oakrange.io/heysongScratch?" p_url = urlencode(dict(uid=encode_uid)) print("game_check OK: ", url + p_url)
def encrypt(self, file_path, output_file_path): self.cipher = self.gen_cipher() data_handle_func = self.cipher.encrypt # 读取到文件尾部时,执行尾部补位操作后加密 data_end_handle_func = lambda d: self.cipher.encrypt(pad(d, AES.block_size)) self.handle(file_path, output_file_path, data_handle_func, data_end_handle_func)
def encrypt(data, passphrase, protection, prot_params=None, randfunc=None): """Encrypt a piece of data using a passphrase and *PBES2*. :Parameters: data : byte string The piece of data to encrypt. passphrase : byte string The passphrase to use for encrypting the data. protection : string The identifier of the encryption algorithm to use. The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'. prot_params : dictionary Parameters of the protection algorithm. +------------------+-----------------------------------------------+ | Key | Description | +==================+===============================================+ | iteration_count | The KDF algorithm is repeated several times to| | | slow down brute force attacks on passwords | | | (called *N* or CPU/memory cost in scrypt). | | | | | | The default value for PBKDF2 is 1 000. | | | The default value for scrypt is 16 384. | +------------------+-----------------------------------------------+ | salt_size | Salt is used to thwart dictionary and rainbow | | | attacks on passwords. The default value is 8 | | | bytes. | +------------------+-----------------------------------------------+ | block_size | *(scrypt only)* Memory-cost (r). The default | | | value is 8. | +------------------+-----------------------------------------------+ | parallelization | *(scrypt only)* CPU-cost (p). The default | | | value is 1. | +------------------+-----------------------------------------------+ randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data, N bytes long. If not specified, a new RNG will be instantiated from ``Crypto.Random``. :Returns: The encrypted data, as a binary string. """ if prot_params is None: prot_params = {} if randfunc is None: randfunc = Random.new().read if protection == 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC': key_size = 24 module = DES3 cipher_mode = DES3.MODE_CBC enc_oid = "1.2.840.113549.3.7" elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC', 'scryptAndAES128-CBC'): key_size = 16 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.2" elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC', 'scryptAndAES192-CBC'): key_size = 24 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.22" elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC', 'scryptAndAES256-CBC'): key_size = 32 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.42" else: raise ValueError("Unknown PBES2 mode") # Get random data iv = randfunc(module.block_size) salt = randfunc(prot_params.get("salt_size", 8)) # Derive key from password if protection.startswith('PBKDF2'): count = prot_params.get("iteration_count", 1000) key = PBKDF2(passphrase, salt, key_size, count) key_derivation_func = newDerSequence( DerObjectId("1.2.840.113549.1.5.12"), # PBKDF2 newDerSequence( DerOctetString(salt), DerInteger(count) ) ) else: # It must be scrypt count = prot_params.get("iteration_count", 16384) scrypt_r = prot_params.get('block_size', 8) scrypt_p = prot_params.get('parallelization', 1) key = scrypt(passphrase, salt, key_size, count, scrypt_r, scrypt_p) key_derivation_func = newDerSequence( DerObjectId("1.3.6.1.4.1.11591.4.11"), # scrypt newDerSequence( DerOctetString(salt), DerInteger(count), DerInteger(scrypt_r), DerInteger(scrypt_p) ) ) # Create cipher and use it cipher = module.new(key, cipher_mode, iv) encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) encryption_scheme = newDerSequence( DerObjectId(enc_oid), DerOctetString(iv) ) # Result encrypted_private_key_info = newDerSequence( # encryptionAlgorithm newDerSequence( DerObjectId("1.2.840.113549.1.5.13"), # PBES2 newDerSequence( key_derivation_func, encryption_scheme ), ), DerOctetString(encrypted_data) ) return encrypted_private_key_info.encode()
def test4(self): padded = pad(uh(b("1234567890")), 4, 'iso7816') self.failUnless(padded == uh(b("1234567890800000"))) back = unpad(padded, 4, 'iso7816') self.failUnless(back == uh(b("1234567890")))
def encrypt(self, original_data): self.cipher = self.gen_cipher() return self.cipher.encrypt(pad(original_data, AES.block_size))
def show_uri(path, datetime=None): global IPFS_API daemonAddress = '{0}:{1}'.format(IPFSAPI_HOST, IPFSAPI_PORT) if not ipwbUtils.isDaemonAlive(daemonAddress): errStr = ('IPFS daemon not running. ' 'Start it using $ ipfs daemon on the command-line ' ' or from the <a href="/">' 'IPWB replay homepage</a>.') return Response(errStr, status=503) path = getCompleteURI(path) cdxjLine = '' try: surtedURI = surt.surt( path, path_strip_trailing_slash_unless_empty=False) indexPath = ipwbUtils.getIPWBReplayIndexPath() searchString = surtedURI if datetime is not None: searchString = surtedURI + ' ' + datetime cdxjLine = getCDXJLine_binarySearch(searchString, indexPath) except Exception as e: print(sys.exc_info()[0]) respString = ('{0} not found :(' + ' <a href="http://{1}:{2}">Go home</a>').format( path, IPWBREPLAY_HOST, IPWBREPLAY_PORT) return Response(respString) if cdxjLine is None: # Resource not found in archives return generateNoMementosInterface(path, datetime) cdxjParts = cdxjLine.split(" ", 2) jObj = json.loads(cdxjParts[2]) datetime = cdxjParts[1] digests = jObj['locator'].split('/') class HashNotFoundError(Exception): pass payload = None header = None try: def handler(signum, frame): raise HashNotFoundError() if os.name != 'nt': # Bug #310 signal.signal(signal.SIGALRM, handler) signal.alarm(10) payload = IPFS_API.cat(digests[-1]) header = IPFS_API.cat(digests[-2]) if os.name != 'nt': # Bug #310 signal.alarm(0) except ipfsapi.exceptions.TimeoutError: print("{0} not found at {1}".format(cdxjParts[0], digests[-1])) respString = ('{0} not found in IPFS :(' + ' <a href="http://{1}:{2}">Go home</a>').format( path, IPWBREPLAY_HOST, IPWBREPLAY_PORT) return Response(respString) except TypeError as e: print('A type error occurred') print(e) abort(500) except HTTPError as e: print("Fetching from the IPFS failed") print(e) abort(503) except HashNotFoundError: if payload is None: print("Hashes not found:\n\t{0}\n\t{1}".format( digests[-1], digests[-2])) abort(404) else: # payload found but not header, fabricate header print("HTTP header not found, fabricating for resp replay") header = '' except Exception as e: print('Unknown exception occurred while fetching from ipfs.') print(e) abort(500) if 'encryption_method' in jObj: keyString = None while keyString is None: if 'encryption_key' in jObj: keyString = jObj['encryption_key'] else: askForKey = ('Enter a path for file', ' containing decryption key: \n> ') keyString = raw_input(askForKey) paddedEncryptionKey = pad(keyString, AES.block_size) key = base64.b64encode(paddedEncryptionKey) nonce = b64decode(jObj['encryption_nonce']) cipher = AES.new(key, AES.MODE_CTR, nonce=nonce) header = cipher.decrypt(base64.b64decode(header)) payload = cipher.decrypt(base64.b64decode(payload)) hLines = header.decode() \ .replace('\r', '') \ .replace('\n\t', '\t') \ .replace('\n ', ' ') \ .split('\n') hLines.pop(0) status = 200 if 'status_code' in jObj: status = jObj['status_code'] resp = Response(payload, status=status) for idx, hLine in enumerate(hLines): k, v = hLine.split(':', 1) if k.lower() == 'transfer-encoding' and \ re.search(r'\bchunked\b', v, re.I): try: unchunkedPayload = extractResponseFromChunkedData(payload) except Exception as e: print('Error while dechunking') print(sys.exc_info()[0]) continue # Data may have no actually been chunked resp.set_data(unchunkedPayload) if k.lower() not in ["content-type", "content-encoding", "location"]: k = "X-Archive-Orig-" + k resp.headers[k] = v.strip() # Add ipwb header for additional SW logic newPayload = resp.get_data() lineJSON = cdxjLine.split(' ', 2)[2] mime = json.loads(lineJSON)['mime_type'] if 'text/html' in mime: ipwbjsinject = """<script src="/ipwbassets/webui.js"></script> <script>injectIPWBJS()</script>""" newPayload = newPayload.decode('utf-8').replace( '</html>', ipwbjsinject + '</html>') resp.set_data(newPayload) resp.headers['Memento-Datetime'] = ipwbUtils.digits14ToRFC1123(datetime) if header is None: resp.headers['X-Headers-Generated-By'] = 'InterPlanetary Wayback' # Get TimeMap for Link response header # respWithLinkHeader = getLinkHeaderAbbreviatedTimeMap(path, datetime) # resp.headers['Link'] = respWithLinkHeader.replace('\n', ' ') if status[0] == '3' and isUri(resp.headers.get('Location')): # Bad assumption that the URI-M will contain \d14 but works for now. uriBeforeURIR = request.url[:re.search(r'/\d{14}/', request.url).end()] newURIM = uriBeforeURIR + resp.headers['Location'] resp.headers['Location'] = newURIM return resp
def test4(self): padded = pad(uh(b("1234567890")), 4, 'x923') self.failUnless(padded == uh(b("1234567890000003"))) back = unpad(padded, 4, 'x923') self.failUnless(back == uh(b("1234567890")))
def test3(self): padded = pad(uh(b("123456")), 4, 'x923') self.failUnless(padded == uh(b("12345601"))) back = unpad(padded, 4, 'x923') self.failUnless(back == uh(b("123456")))
from Crypto.Util.Padding import pad, unpad from Crypto.Hash import SHA3_512, SHA1, SHA512 from Crypto.Protocol.KDF import PBKDF2 # --------------------- # AES and PKCS7 padding # --------------------- # Generate random bytes key = get_random_bytes(32) iv = get_random_bytes(16) # Encrypt data = b'Unaligned' cipher1 = AES.new(key, AES.MODE_CBC, iv) pad_data = pad(data, 16, style="pkcs7") enc = cipher1.encrypt(pad_data) # Decrypt cipher2 = AES.new(key, AES.MODE_CBC, iv) dec = cipher2.decrypt(enc) unpad_data = unpad(dec, 16, style="pkcs7") # Encrypt a file def sym_encrypt_file(input_file, output_file, cipher, buffer_size=4096): pad_done = False while True: clear = input_file.read(buffer_size) if not clear: break
def test1(self): padded = pad(b(""), 4, 'iso7816') self.assertTrue(padded == uh(b("80000000"))) back = unpad(padded, 4, 'iso7816') self.assertTrue(back == b(""))
def ECBEncrypt(s): s2 = pad(s + unknownString, block_size) return cipher.encrypt(s2)
def test3(self): padded = pad(uh(b("123456")), 4, 'iso7816') self.assertTrue(padded == uh(b("12345680"))) #import pdb; pdb.set_trace() back = unpad(padded, 4, 'iso7816') self.assertTrue(back == uh(b("123456")))
def encryptContent(self, content): aes_cipher = AES.new(self._aes_key, AES.MODE_CBC, iv=self._aes_iv) return aes_cipher.encrypt(pad(content, AES.block_size))
def test4(self): padded = pad(uh(b("1234567890")), 4, 'iso7816') self.assertTrue(padded == uh(b("1234567890800000"))) back = unpad(padded, 4, 'iso7816') self.assertTrue(back == uh(b("1234567890")))
def des3EcbEncryptToBase64(encryptionKey, plaintext): cipher = DES3.new(encryptionKey, DES.MODE_ECB) ciphertext = cipher.encrypt(pad(plaintext.encode("ascii"),8)) ciphertextBase64 = base64Encoding(ciphertext) return ciphertextBase64
def test3(self): padded = pad(uh(b("123456")), 4, 'iso7816') self.failUnless(padded == uh(b("12345680"))) #import pdb; pdb.set_trace() back = unpad(padded, 4, 'iso7816') self.failUnless(back == uh(b("123456")))
def pad_text(plaintext): if len(plaintext) % 16 != 0: return pad(plaintext, 16) return plaintext
def test1(self): padded = pad(b(""), 4, 'x923') self.assertTrue(padded == uh(b("00000004"))) back = unpad(padded, 4, 'x923') self.assertTrue(back == b(""))
def test2(self): padded = pad(uh(b("12345678")), 4, 'x923') self.failUnless(padded == uh(b("1234567800000004"))) back = unpad(padded, 4, 'x923') self.failUnless(back == uh(b("12345678")))
def test2(self): padded = pad(uh(b("12345678")), 4, 'x923') self.assertTrue(padded == uh(b("1234567800000004"))) back = unpad(padded, 4, 'x923') self.assertTrue(back == uh(b("12345678")))
from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes from functools import reduce import re print('CBC padding oracle attack demo') print('Tekst jawny:') data = input() key = get_random_bytes(AES.block_size) iv = get_random_bytes(AES.block_size) encrypter = AES.new(key, AES.MODE_CBC, iv=iv) padded_data = pad(data.encode(encoding="ascii", errors="replace"), AES.block_size) ciphertext = encrypter.encrypt(padded_data) print('Szyfrogram:') print(re.sub("(.{32})", "\\1\n", ciphertext.hex().upper(), 0, re.DOTALL)) def oracle(ciphertext, key, iv): decrypter = AES.new(key, AES.MODE_CBC, iv=iv) try: unpad(decrypter.decrypt(ciphertext), AES.block_size) return True except ValueError: return False
def test3(self): padded = pad(uh(b("123456")), 4, 'x923') self.assertTrue(padded == uh(b("12345601"))) back = unpad(padded, 4, 'x923') self.assertTrue(back == uh(b("123456")))
def test4(self): padded = pad(uh(b("1234567890")), 4, 'x923') self.assertTrue(padded == uh(b("1234567890000003"))) back = unpad(padded, 4, 'x923') self.assertTrue(back == uh(b("1234567890")))
def encryption(ciphBlock, msg): cipherText = ciphBlock.encrypt(pad(msg.encode('ascii'),32)) #Note 32: key len/divisible by is 256 return cipherText
def encrypt(self, string): pad_byte_string = pad(string.encode('utf-8'), MULTIPLE_OF_BYTE) encrypt_byte_string = self.cipher.encrypt(pad_byte_string) encrypt_string = base64.urlsafe_b64encode(encrypt_byte_string).decode('ascii') return encrypt_string
self.c = [randbelow(ring) for _ in range(n)] self.s = [randbelow(ring) for _ in range(n)] def f(self): return sum(map(mul, self.c, self.s)) % self.ring def update(self): self.s = self.s[1:] + [self.f()] return self.s[-1] if __name__ == '__main__': r = Random(RING, N) print(r.c) [r.update() for _ in range(N**2)] hints = [r.update() >> HIDDEN for _ in range(HINT)] print(hints) [r.update() for _ in range(N**2)] size = RING.bit_length() // 4 flag = pad(open('flag.txt', 'rb').read(), size) key = reduce(xor, r.s + r.c)**2 key = key.to_bytes(size, byteorder='big') cipher = AES.new(key, AES.MODE_ECB) enc_flag = cipher.encrypt(flag).hex() print(enc_flag)
def test1(self): padded = pad(b(""), 4, 'iso7816') self.failUnless(padded == uh(b("80000000"))) back = unpad(padded, 4, 'iso7816') self.failUnless(back == b(""))
#!/usr/bin/python3 from sys import argv from Crypto.Cipher import AES from Crypto.Util.Padding import pad _, first, second, third = argv assert len(first) == 21 data = bytearray(first, encoding='utf-8') ciphertext = bytearray.fromhex(second) iv = bytearray.fromhex(third) with open('./words.txt') as f: keys = f.readlines() for k in keys: k = k.rstrip('\n') if len(k) <= 16: key = k + '#' * (16 - len(k)) cipher = AES.new(key=bytearray(key, encoding='utf-8'), mode=AES.MODE_CBC, iv=iv) guess = cipher.encrypt(pad(data, 16)) if guess == ciphertext: print("find the key:", key) exit(0) print("cannot find the key!")
from ptrlib import padding_oracle_encrypt, Socket from Crypto.Util.Padding import pad from binascii import hexlify, unhexlify from logging import getLogger, WARN getLogger("ptrlib.pwn").setLevel(WARN + 1) def decrypt(c): sock = Socket("youshallnotgetmycookies.3k.ctf.to", 13337) sock.sendlineafter("your cookie:", hexlify(c).upper()) result = sock.recvline().decode() result = sock.recvline().decode() sock.close() if 'Nop' in result: return True elif "rude" in result: raise Exception("RUDE!!!") else: return False plain = pad(b'Maple Oatmeal Biscuits', 16) print(padding_oracle_encrypt(decrypt, plain, bs=16))
def get_proximity_id(self, enin): data = ('EN-RPI' + str(enin)).encode() enc = self.cipher.encrypt(pad(data, AES.block_size)) self.cipher = AES.new(self.key, AES.MODE_ECB) return enc.hex()
g = int(g) a = randint(2, p-2) print("a generado:", a) a_mayus = pow(g,a,p) print("A generado:", a_mayus) ip = sys.argv[1] sock = socket(AF_INET, SOCK_STREAM) sock.connect((ip, 8888)) sock.sendall(str(a_mayus).encode()) data = sock.recv(8192) K = pow(int(data),a,p) print("K generado:", K) h = SHA256.new(str(K).encode()) key = h.digest() mensaje = b"Hola! Mis detalles de cuenta bancaria son los siguientes: blablabla" print("Texto en claro: ", mensaje) cifrador = AES.new(key, AES.MODE_ECB) mensaje_cifrado = cifrador.encrypt(pad(mensaje, AES.block_size)) print("Texto cifrado: ", mensaje_cifrado) sock.sendall(mensaje_cifrado) data = sock.recv(8192) print("Cifrado recibido: ", data) data = unpad(cifrador.decrypt(data), AES.block_size) print("Recibido en claro: ", data)
if (fname != 'script.py'): dirs.append(dirName + "//" + fname) return dirs def encrypt_all_files(self): dirs = self.getAllFiles() for file_name in dirs: self.encrypt_file(file_name) def decrypt_all_files(self): dirs = self.getAllFiles() for file_name in dirs: self.decrypt_file(file_name) key = pad(b"myKey", AES.block_size) enc = Encryptor(key, iv) clear = lambda: os.system('cls') def main(): while True: clear() choice = int( input( " Select an option: \n1 -> Encrypt single file\n2 -> Decrypt single file\n3 -> Encrypt all files in the curr folder\n4 -> Decrypt all files in the curr folder\n5 -> Quit\n" )) clear() if choice == 1: enc.encrypt_file(str(input("Enter name of file to encrypt: "))) elif choice == 2:
def encrypt(self, file_path): block_size = self.read_kb * 1024 data_handle_func = self.cipher.encrypt # 读取到文件尾部时,执行尾部补位操作后加密 data_end_handle_func = lambda d: self.cipher.encrypt(pad(d, self.multiple_of_byte)) return ByteCrypto.handle(file_path, block_size, data_handle_func, data_end_handle_func)
def encrypt(key): iv = __import__('os').urandom(16) key = sha1(str(key).encode('ascii')).digest()[0:16] cipher = AES.new(key, AES.MODE_CBC, iv) ct = cipher.encrypt(pad(flag,16)) return(ct.hex(),iv.hex())
def des_encrypt(data, key, iv, mode=DES.MODE_CBC): cipher = DES.new(key, mode=mode, IV=iv) padded_text = pad(utf8(data), cipher.block_size) return cipher.encrypt(padded_text).encode('hex')
def encrypt(self, raw): """加密""" raw = pad(raw.encode('utf-8'), 16) cipher = AES.new(self.key, AES.MODE_ECB) return base64.b64encode(cipher.encrypt(raw))
def encrypt(key: str, value: str) -> str: cipher = AES.new(key.encode(), AES.MODE_CBC, iv=token_urlsafe(12).encode()) paddding = pad((token_urlsafe(48) + value).encode(), block_size=16) return b64encode(cipher.encrypt(paddding)).decode()
def encrypt(key: bytes, pt: bytes) -> bytes: key = hashlib.sha256(key).digest()[:16] cipher = AES.new(key, AES.MODE_CBC, os.urandom(16)) return {'cip': cipher.encrypt(pad(pt, 16)).hex(), 'iv': cipher.IV.hex()}
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad import sys import base64 import json from mysecrets import aes_key iv = get_random_bytes(AES.block_size) cipher = AES.new(aes_key, AES.MODE_CBC, iv) f_input = open(sys.argv[1], "rb") # pycryptodome does not support update functions for block ciphers ciphertext = cipher.encrypt(pad(f_input.read(), AES.block_size)) # base64 used to represent IV and ciphertext in strings instead of binary objects # JSON used to go easily on the web ivb64 = base64.b64encode(cipher.iv).decode( 'utf-8') # string good for JSON objects ciphertextb64 = base64.b64encode(ciphertext).decode( 'utf-8') # string good for JSON objects json_object = json.dumps({'IV': ivb64, 'ciphertext': ciphertextb64}) print(json_object) # Receiver b64 = json.loads(json_object) # split JSON object to manipulate it cipher2 = AES.new(aes_key, AES.MODE_CBC, base64.b64decode(b64['IV'])) plaintext_dec = cipher2.decrypt(base64.b64decode(b64['ciphertext']))
from sage.modules.free_module_integer import IntegerLattice length = 723 n = 30004084769852356813752671105440339608383648259855991408799224369989221653141334011858388637782175392790629156827256797420595802457583565986882788667881921499468599322171673433298609987641468458633972069634856384101309327514278697390639738321868622386439249269795058985584353709739777081110979765232599757976759602245965314332404529910828253037394397471102918877473504943490285635862702543408002577628022054766664695619542702081689509713681170425764579507127909155563775027797744930354455708003402706090094588522963730499563711811899945647475596034599946875728770617584380135377604299815872040514361551864698426189453 e = 65537 f = open("chal.py","rb") inp = f.read() f.close() f = open("chal.enc", "rb") outp = f.read() f.close() data = [] e = 65537 for i in range(0, 768, 256): cc = inp[i:i+256] if len(cc) < 256: cc = pad(cc, 256) res = bytes_to_long(cc) ^ bytes_to_long(outp[i:i+256]) data.append([res, e]) e = nextprime(e) u = inverse(65537, 65539) v = (65537 * u - 1) // 65539 m = (pow(data[0][0], u, n) * inverse(pow(data[1][0], v, n), n)) % n print(long_to_bytes(m))
def derive_key(password): start = bytes_to_long(password) #Making sure I am safe from offline bruteforce attack for i in range(NB_ITERATIONS): start = start**e start %= N #We are never too cautious let's make it harder key = 1 for i in range(NB_ITERATIONS): key = key**e key %= N key *= start key %= N return sha256(long_to_bytes(key)).digest() assert (len(password) == 2) assert (password.decode().isprintable()) key = derive_key(password) IV = b"random_and_safe!" cipher = AES.new(key, AES.MODE_CBC, IV) enc = cipher.encrypt(pad(flag, 16)) with open("flag.enc", "wb") as output_file: output_file.write(enc)
def logEditView(request, *args, **kwargs): logtoview = kwargs.get('pk') try: logtoview = UUID(str(logtoview)) except ValueError: return HttpResponse("Error: Invalid log ID", status=400) try: thelog = Logger.objects.get(id=logtoview) password = thelog.password BLOCK_SIZE = 32 encryption_suite = AES.new(password.encode(), AES.MODE_ECB) deciphered_text = encryption_suite.decrypt(bytes.fromhex(thelog.note)).decode() thelog.note = deciphered_text except ObjectDoesNotExist: return HttpResponse("Error: Invalid log ID", status=400) except: messages.add_message(request, messages.ERROR, "An Unknown error occurred.") return redirect('landing-page') if request.method == "POST": log_title = request.POST.get('log-title', "") log_description = request.POST.get('log-description', "") log_content = request.POST.get('log-content', "") # changelog = Logger.objects. BLOCK_SIZE = 32 encryption_suite = AES.new(thelog.password.encode(), AES.MODE_ECB) cipher_text = encryption_suite.encrypt(pad(log_content.encode(), BLOCK_SIZE)).hex() thelog.title = log_title thelog.short_description=log_description thelog.note = cipher_text thelog.save() messages.add_message(request, messages.SUCCESS, "Log saved successfully.") return redirect('log-list') # Get a list of all teams that the user is a part of user_teams = request.user.team_set.all() project_list = [] # Get a list of all projects that the user's teams have made for team in user_teams: [project_list.append(x) for x in team.project_set.all()] context = { "log":thelog, "projects":project_list, } return render(request, 'log/log_edit_view.html', context)
def test1(self): padded = pad(b(""), 4, 'x923') self.failUnless(padded == uh(b("00000004"))) back = unpad(padded, 4, 'x923') self.failUnless(back == b(""))
def encrypt(key, plaintext): cipher = AES.new(str.encode(key[:16]), AES.MODE_CBC) padded_data = pad(plaintext.encode(), cipher.block_size) string = base64.b64encode(cipher.encrypt(padded_data)).decode() pad_count = string.count('=') return "%s%s" % (string.replace('=', ''), pad_count)
def obfuscate(self, obfuscation_info: Obfuscation): self.logger.info('Running "{0}" obfuscator'.format( self.__class__.__name__)) try: native_libs = obfuscation_info.get_native_lib_files() native_lib_invoke_pattern = re.compile( r'\s+invoke-static\s{(?P<invoke_pass>[vp0-9]+)},\s' r'Ljava/lang/System;->loadLibrary\(Ljava/lang/String;\)V') encrypted_libs: Set[str] = set() if native_libs: for smali_file in util.show_list_progress( obfuscation_info.get_smali_files(), interactive=obfuscation_info.interactive, description='Encrypting native libraries'): self.logger.debug( 'Replacing native libraries with encrypted native libraries ' 'in file "{0}"'.format(smali_file)) with open(smali_file, 'r', encoding='utf-8') as current_file: lines = current_file.readlines() class_name = None local_count = 16 # Names of the loaded libraries. lib_names: List[str] = [] editing_constructor = False start_index = 0 for line_number, line in enumerate(lines): if not class_name: class_match = util.class_pattern.match(line) if class_match: class_name = class_match.group('class_name') continue # Native libraries should be loaded inside static constructors. if line.startswith( '.method static constructor <clinit>()V' ) and not editing_constructor: # Entering static constructor. editing_constructor = True start_index = line_number + 1 local_match = util.locals_pattern.match( lines[line_number + 1]) if local_match: local_count = int( local_match.group('local_count')) if local_count <= 15: # An additional register is needed for the encryption. local_count += 1 lines[line_number + 1] = '\t.locals {0}\n'.format( local_count) continue # For some reason the locals declaration was not found where it should be, so assume the # local registers are all used (we can't add any instruction here). break elif line.startswith( '.end method') and editing_constructor: # Only one static constructor per class. break elif editing_constructor: # Inside static constructor. invoke_match = native_lib_invoke_pattern.match( line) if invoke_match: # Native library load instruction. Iterate the constructor lines backwards in order to # find the string containing the name of the loaded library. for l_num in range(line_number - 1, start_index, -1): string_match = util.const_string_pattern.match( lines[l_num]) if string_match and \ string_match.group('register') == invoke_match.group('invoke_pass'): # Native library string declaration. lib_names.append( string_match.group('string')) # Static constructors take no parameters, so the highest register is v<local_count - 1>. lines[line_number] = '\tconst-class v{class_register_num}, {class_name}\n\n' \ '\tinvoke-static {{v{class_register_num}, {original_register}}}, ' \ 'Lcom/decryptassetmanager/DecryptAsset;->loadEncryptedLibrary(' \ 'Ljava/lang/Class;Ljava/lang/String;)V\n'.format( class_name=class_name, original_register=invoke_match.group('invoke_pass'), class_register_num=local_count - 1) # Encrypt the native libraries used in code and put them in assets folder. assets_dir = obfuscation_info.get_assets_directory() os.makedirs(assets_dir, exist_ok=True) for native_lib in native_libs: for lib_name in lib_names: if native_lib.endswith( '{0}.so'.format(lib_name)): arch = os.path.basename( os.path.dirname(native_lib)) encrypted_lib_path = os.path.join( assets_dir, 'lib.{arch}.{lib_name}.so'.format( arch=arch, lib_name=lib_name)) with open(native_lib, 'rb') as native_lib_file: encrypted_lib = AES \ .new(key=self.encryption_secret.encode(), mode=AES.MODE_ECB) \ .encrypt(pad(native_lib_file.read(), AES.block_size)) with open(encrypted_lib_path, 'wb') as encrypted_lib_file: encrypted_lib_file.write(encrypted_lib) encrypted_libs.add(encrypted_lib_path) with open(smali_file, 'w', encoding='utf-8') as current_file: current_file.writelines(lines) if not obfuscation_info.decrypt_asset_smali_file_added_flag and encrypted_libs: # Add to the app the code for decrypting the encrypted native libraries. The code # for decrypting can be put in any smali directory, since it will be moved to the # correct directory when rebuilding the application. destination_dir = os.path.dirname( obfuscation_info.get_smali_files()[0]) destination_file = os.path.join(destination_dir, 'DecryptAsset.smali') with open(destination_file, 'w', encoding='utf-8') as decrypt_asset_smali: decrypt_asset_smali.write( util.get_decrypt_asset_smali_code()) obfuscation_info.decrypt_asset_smali_file_added_flag = True # Remove the original native libraries (the encrypted ones will be used instead). for native_lib in native_libs: try: os.remove(native_lib) except OSError as e: self.logger.warning( 'Unable to delete native library "{0}": {1}'. format(native_lib, e)) else: self.logger.debug('No native libraries found') except Exception as e: self.logger.error( 'Error during execution of "{0}" obfuscator: {1}'.format( self.__class__.__name__, e)) raise finally: obfuscation_info.used_obfuscators.append(self.__class__.__name__)