def aes_key_unwrap(key, c): """ AES key unwrap @type key: bytes @param key: Key; length MUST be 16, 24, or 32 octets @type c : bytes @param c : Ciphertext; length MUST be a multiple of 8 octets @rtype: bytes @return: Unwrapped version of ciphertext """ assert (len(c) % 8 == 0) n = len(c) / 8 - 1 r = list(range(n + 1)) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1, n + 1): r[i] = c[i * 8:(i + 1) * 8] a = c[:8] aes = AESCipher(key) for j in range(5, -1, -1): for i in range(n, 0, -1): t = pack("!q", (n * j) + i) a = strxor(a, t) b = aes.decrypt( a + r[i]) # B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i a = b[:8] # A = MSB(64, B) r[i] = b[8:] # R[i] = LSB(64, B) if (a == b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6'): return "".join(r[1:]) else: raise Exception("Key unwrap integrity check failed")
def decrypt(self, string): enc_gcode = string[0x2000:] aes = AESCipher("@[email protected]", mode=MODE_ECB, IV=chr(0) * 16) gcode = aes.decrypt(enc_gcode) self.gcode = GCodeFile.from_string(gcode)
def encrypt_header(self): key = "@xyzprinting.com" iv = chr(0) * 16 aes = AESCipher(key, mode=MODE_CBC, IV=iv) text = self.gcode.header_text header = Padding.appendPadding(text) return aes.encrypt(header)
def aes_key_wrap(key, p): """ AES key wrap @type key: bytes @param key: Key; length MUST be 16, 24, or 32 octets @type p : bytes @param p : Plaintext; length MUST be a multiple of 8 octets @rtype: bytes @return: Wrapped version of plaintext """ assert (len(p) % 8 == 0) n = len(p) / 8 r = list(range(n + 1)) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1, n + 1): r[i] = p[(i - 1) * 8:i * 8] a = b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6' aes = AESCipher(key) for j in range(0, 6): for i in range(1, n + 1): t = pack("!q", (n * j) + i) b = aes.encrypt(a + r[i]) # B = AES(K, A | R[i]) a = strxor(b[:8], t) # A = MSB(64, B) ^ t where t = (n*j)+i r[i] = b[8:] # R[i] = LSB(64, B) r[0] = a return "".join(r)
def encrypt(self): key = "@[email protected]" iv = chr(0) * 16 aes = AESCipher(key, mode=MODE_ECB, IV=iv) fulltext = self.gcode.text padded = Padding.appendPadding(fulltext) enc_text = aes.encrypt(padded) magic = "3DPFNKG13WTW" magic2 = struct.pack("8B", 1, 2, 0, 0, 0, 0, 18, 76) blanks = chr(0) * 4684 tag = "TagEJ256" magic3 = struct.pack("4B", 0, 0, 0, 68) crc32 = binascii.crc32(enc_text) crcstr = struct.pack(">l", crc32) encrypted_header = self.encrypt_header() bio = BytesIO() bio.write(magic) bio.write(magic2) bio.write(blanks) bio.write(tag) bio.write(magic3) bio.write(crcstr) bio.write((chr(0) * (68 - len(crcstr)))) log.debug("Length of encrypted header: {}".format( len(encrypted_header))) if len(encrypted_header) > (8192 - bio.tell()): log.error("Header is too big to fit file format!") bio.write(encrypted_header) left = 8192 - bio.tell() bio.write((chr(0) * left)) bio.write(enc_text) return bio.getvalue()
class CryptoPan: def __init__(self, key): if len(key) != 32: raise CryptoPanError("Key must be a 32 byte long string") self.aes = AES(key[0:16]) self.pad = self.aes.encrypt(key[16:32]) f4bp = self.toint([ord(x) for x in self.pad[0:4]]) self.masks = [(mask, f4bp & (~mask)) for mask in (0xFFFFFFFF >> (32 - p) << (32 - p) for p in range(0, 32))] def toint(self, array): return array[0] << 24 | array[1] << 16 | array[2] << 8 | array[3] def toarray(self, n): for i in range(3, -1, -1): yield (n >> (i * 8)) & 0xFF def anonymize(self, ip): result = 0 address = [int(x) for x in ip.split(".")] if len(address) != 4: raise CryptoPanError("Invalid IPv4 Address") address = self.toint(address) def calc(a): """ calculate the first bit for Crypto-PAN""" inp = "".join((chr(x) for x in self.toarray(a))) + self.pad[4:] rin_output = self.aes.encrypt(inp) return ord(rin_output[0]) >> 7 addresses = ((address & mask[0]) | mask[1] for mask in self.masks) result = reduce(lambda x, y: x << 1 | y, (calc(a) for a in addresses), 0) return ".".join(["%s" % x for x in self.toarray(result ^ address)])
def aes_decrypt(msg, key=None): msg = base64.b64decode(msg) global _aes if key is not None: _aes_local = AESCipher(key) ret = _aes_local.decrypt(msg) else: ret = _aes.decrypt(msg) return ret.rstrip(chr(0))
def apply_aes_ctr(key, nonce, source): cipher = AESCipher(key) dest = b"" for (i, cipher_block) in generate_blocks(source, BLOCK_SIZE): pre_enc = add_bytestrings(nonce, int_to_bytes(i, BLOCK_SIZE)) enc = cipher.encrypt(pre_enc) dest_block = xor_bytestrings(enc, cipher_block) dest += dest_block return dest
def aes_encrypt(msg, key=None): msg = _aes_pad(msg) global _aes if key is not None: _aes_local = AESCipher(key) ret = _aes_local.encrypt(msg) else: ret = _aes.encrypt(msg) ret = base64.b64encode(ret) return ret
def get_secret(self): """Returns item secret (bytestring).""" self.ensure_not_locked() if not self.session: self.session = open_session(self.bus) secret = self.item_iface.GetSecret(self.session.object_path, signature='o') if not self.session.encrypted: return bytes(bytearray(secret[2])) aes_cipher = AESCipher(self.session.aes_key, mode=MODE_CBC, IV=bytes(bytearray(secret[1]))) padded_secret = bytearray(aes_cipher.decrypt( bytes(bytearray(secret[2])))) return padded_secret[:-padded_secret[-1]]
def get_secret(self): """Returns item secret (bytestring).""" self.ensure_not_locked() if not self.session: self.session = open_session(self.bus) secret = self.item_iface.GetSecret(self.session.object_path, signature='o') if not self.session.encrypted: return bytes(bytearray(secret[2])) aes_cipher = AESCipher(self.session.aes_key, mode=MODE_CBC, IV=bytes(bytearray(secret[1]))) padded_secret = bytearray( aes_cipher.decrypt(bytes(bytearray(secret[2])))) return padded_secret[:-padded_secret[-1]]
def encrypt_aes_cbc(key, plaintext): padded_plaintext = pad_pkcs7(plaintext) cipher = AESCipher(key) iv = cryptorandom(BLOCK_SIZE) pre_xor = iv ciphertext = b"" for (i, plaintext_block) in generate_blocks(padded_plaintext, BLOCK_SIZE): xord = xor_bytestrings(plaintext_block, pre_xor) cipher_block = cipher.encrypt(xord) ciphertext += cipher_block pre_xor = cipher_block return iv + ciphertext
def __init__(self, key): if len(key) != 32: raise CryptoPanError("Key must be a 32 byte long string") self.aes = AES(key[0:16]) self.pad = self.aes.encrypt(key[16:32]) f4bp = self.toint([ord(x) for x in self.pad[0:4]]) self.masks = [(mask, f4bp & (~mask)) for mask in (0xFFFFFFFF >> (32 - p) << (32 - p) for p in range(0, 32))]
def parse_grabbed(conn: socket.socket, aes: AES.AESCipher): sig_from_client = conn.recv(32) chunked_data_len = struct.unpack("<q", conn.recv(8))[0] total_data = b"" while chunked_data_len > 0: chunk = aes.decrypt(conn.recv(1024)) total_data += chunk chunked_data_len -= 1024 g = gost3411_12.GOST341112(digest_size=256) g.update(total_data) assert sig_from_client == bytearray(i ^ 0xAA for i in g.digest()) while len(total_data) > 0: cut = 10 header = parse_header(total_data[:cut]) total_data = total_data[cut:] if list(header.values()) == [65535, 0, 0]: thread_print('got terminator-header, terminating...') break cut = header['data_len'] grabbed_by_header = total_data[:cut] total_data = total_data[cut:] assert binascii.crc32(grabbed_by_header) == header['data_crc'] assert grabbed_by_header.startswith( GRABBER_HEADERS[header['data_type']]) print(grabbed_by_header.decode()) assert any(i == 0xcc for i in total_data) # there must be only 0xcc's return True
def format_secret(session, secret, content_type): """Formats `secret` to make possible to pass it to the Secret Service API.""" if not isinstance(secret, bytes): secret = secret.encode('utf-8') if not session.encrypted: return dbus.Struct( (session.object_path, '', dbus.ByteArray(secret), content_type)) # PKCS-7 style padding padding = 0x10 - (len(secret) & 0xf) secret += bytes(bytearray((padding, )) * padding) aes_iv = long_to_bytes(getrandbits(0x80)) # If shorter than 16 bytes, prepend zero bytes aes_iv = b'\x00' * (0x10 - len(aes_iv)) + aes_iv aes_cipher = AESCipher(session.aes_key, mode=MODE_CBC, IV=aes_iv) return dbus.Struct( (session.object_path, dbus.Array(aes_iv), dbus.Array(bytearray(aes_cipher.encrypt(secret))), content_type))
def decrypt_aes_cbc(key, ciphertext): if (len(ciphertext) % BLOCK_SIZE != 0): raise Exception("Not block aligned") if (len(ciphertext) // BLOCK_SIZE < 2): raise Exception("Invalid size") cipher = AESCipher(key) plaintext = b"" dec_xor = ciphertext[0:BLOCK_SIZE] # IV for (i, ciphertext_block) in generate_blocks(skip_bytes(ciphertext, BLOCK_SIZE), BLOCK_SIZE): decrypted_block = cipher.decrypt(ciphertext_block) plaintext_block = xor_bytestrings(dec_xor, decrypted_block) plaintext += plaintext_block dec_xor = ciphertext_block return unpad_pkcs7(plaintext)
def format_secret(session, secret, content_type): """Formats `secret` to make possible to pass it to the Secret Service API.""" if not isinstance(secret, bytes): secret = secret.encode('utf-8') if not session.encrypted: return dbus.Struct((session.object_path, '', dbus.ByteArray(secret), content_type)) # PKCS-7 style padding padding = 0x10 - (len(secret) & 0xf) secret += bytes(bytearray((padding,)) * padding) aes_iv = get_random_bytes(block_size) aes_cipher = AESCipher(session.aes_key, mode=MODE_CBC, IV=aes_iv) return dbus.Struct(( session.object_path, dbus.Array(aes_iv), dbus.Array(bytearray(aes_cipher.encrypt(secret))), content_type ))
def aes_key_wrap(key, p): assert (len(p) % 8 == 0) n = len(p) / 8 r = range(n + 1) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1, n + 1): r[i] = p[(i - 1) * 8:i * 8] a = b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6' aes = AESCipher(key) for j in range(0, 6): for i in range(1, n + 1): t = struct.pack("!q", (n * j) + i) b = aes.encrypt(a + r[i]) # B = AES(K, A | R[i]) a = strxor(b[:8], t) # A = MSB(64, B) ^ t where t = (n*j)+i r[i] = b[8:] # R[i] = LSB(64, B) r[0] = a return "".join(r)
def aes_key_wrap(key, p): assert( len(p) % 8 == 0 ) n = len(p)/8 r = range(n+1) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1,n+1): r[i] = p[(i-1)*8:i*8] a = b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6' aes = AESCipher(key) for j in range(0,6): for i in range(1,n+1): t = struct.pack("!q", (n*j)+i) b = aes.encrypt(a+r[i]) # B = AES(K, A | R[i]) a = strxor(b[:8], t) # A = MSB(64, B) ^ t where t = (n*j)+i r[i] = b[8:] # R[i] = LSB(64, B) r[0] = a return "".join(r)
def format_secret(session, secret, content_type): """Formats `secret` to make possible to pass it to the Secret Service API.""" if not isinstance(secret, bytes): secret = secret.encode('utf-8') if not session.encrypted: return dbus.Struct((session.object_path, '', dbus.ByteArray(secret), content_type)) # PKCS-7 style padding padding = 0x10 - (len(secret) & 0xf) secret += bytes(bytearray((padding,)) * padding) aes_iv = long_to_bytes(getrandbits(0x80)) # If shorter than 16 bytes, prepend zero bytes aes_iv = b'\x00' * (0x10 - len(aes_iv)) + aes_iv aes_cipher = AESCipher(session.aes_key, mode=MODE_CBC, IV=aes_iv) return dbus.Struct(( session.object_path, dbus.Array(aes_iv), dbus.Array(bytearray(aes_cipher.encrypt(secret))), content_type ))
class CryptoPan(): def __init__(self, key): if len(key) != 32: raise CryptoPanError("Key must be a 32 byte long string") self.aes = AES(key[0:16]) self.pad = self.aes.encrypt(key[16:32]) self.first4bytes_pad = self.toint([ord(x) for x in self.pad[0:4]]) def toint(self, array): return array[0] << 24 | array[1] << 16 | array[2] << 8 | array[3] def toarray(self, n): for i in range(3, -1, -1): yield (n >> (i * 8)) & 0xFF def anonymize(self, ip): result = 0 address = [int(x) for x in ip.split(".")] if len(address) != 4: raise CryptoPanError("Invalid IPv4 Address") address = self.toint(address) def calc(a): """ calculate the first bit for Crypto-PAN""" inp = "".join([chr(x) for x in self.toarray(a)]) + self.pad[4:] rin_output = self.aes.encrypt(inp) return ord(rin_output[0]) >> 7 def prep_addr(p, address): """ prepare adress for calculation """ mask = 0xFFFFFFFF >> (32 - p) << (32 - p) return (address & mask) | (self.first4bytes_pad & (~mask)) addresses = [prep_addr(p, address) for p in range(0, 32)] result = reduce(lambda x, y: x << 1 | y, [calc(a) for a in addresses], 0) return ".".join(["%s" % x for x in self.toarray(result ^ address)])
def aes_key_unwrap(key, c): assert( len(c) % 8 == 0 ) n = len(c)/8 - 1 r = range(n+1) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1,n+1): r[i] = c[i*8:(i+1)*8] a = c[:8] aes = AESCipher(key) for j in range(5,-1,-1): for i in range(n,0,-1): t = struct.pack("!q", (n*j)+i) a = strxor(a, t) b = aes.decrypt(a+r[i]) # B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i a = b[:8] # A = MSB(64, B) r[i] = b[8:] # R[i] = LSB(64, B) if (a == b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6'): return "".join(r[1:]) else: raise "Key unwrap integrity check failed"
def aes_key_unwrap(key, c): assert (len(c) % 8 == 0) n = len(c) / 8 - 1 r = range(n + 1) r[0] = b'\0\0\0\0\0\0\0\0' for i in range(1, n + 1): r[i] = c[i * 8:(i + 1) * 8] a = c[:8] aes = AESCipher(key) for j in range(5, -1, -1): for i in range(n, 0, -1): t = struct.pack("!q", (n * j) + i) a = strxor(a, t) b = aes.decrypt( a + r[i]) # B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i a = b[:8] # A = MSB(64, B) r[i] = b[8:] # R[i] = LSB(64, B) if (a == b'\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6'): return "".join(r[1:]) else: raise "Key unwrap integrity check failed"
def noor2ro(text): h = SHA256.new() h.update(flag) key = h.digest() try: text2 = 'noor2ro' + text.decode('base64') + flag except: print "Please enter the correct Base64 input." exit() padding = block_size - (len(text2) % block_size) text2 += 'A' * padding cipher = AESCipher(key).encrypt(text2).encode('base64') return cipher
def decrypt_telegraph(cipher, private_key=None): """ Decrypt key and IV self-including 'cipher' into secret string. """ json_dict = json.loads(b64decode(cipher)) if not has_all_key( json_dict, [ENCRYPT_TELEGRAPH_KEY_NAME, ENCRYPT_TELEGRAPH_CIPHER_NAME]): return ValueError('Invalid telegraph cipher.') key = b64decode( decrypt(json_dict[ENCRYPT_TELEGRAPH_KEY_NAME], private_key=private_key)) # combined with key + iv iv = key[AES_KEY_SIZE:] # pylint: disable=invalid-name key = key[0:AES_KEY_SIZE] telegraph_cipher = b64decode(json_dict[ENCRYPT_TELEGRAPH_CIPHER_NAME]) return AESCipher(key, AES_CIPHER_MODE, iv).decrypt(telegraph_cipher).rstrip(AES_PADDING)
def encrypt(message: bytes, aes: AES.AESCipher) -> bytes: """Chiffre une chaine d'octets Chiffrement d'une chaine codée sur un multiple de 16 octets. Le chiffrement est effectué à l'aide de l'AES, fourni au préalable. La fonction retourne donc la chaine chiffrée. Un Zero Padding est appliqué. """ # Convert eventual not-bytes object to bytes message = pickle.dumps(message) # Convert sequence of bytes to acii-compatible sequence of bytes message = binascii.hexlify(message) # Crypto.Cipher.AES.AESCipher needs an ASCII string to work on message_str = message.decode('ascii') # Section with zero-padding logic length = len(message_str) # Adding a position for the header value length += 1 # Calculating length of needed padding if (length % 16) != 0: complement_size = 16 - (length % 16) else: complement_size = 0 # Header holds the size of added padding header = hex(complement_size) # Stripping leading "0x" by keeping only last char header = header[-1] # Creating padding ASCII string with zeros complement = "0" * complement_size # Merging header message and padding message_str = "".join([header, message_str, complement]) # Encrypt zero-padded message return aes.encrypt(message_str)
def handle(self): req = self.request signal.alarm(5) req.sendall("Welcome to l33tserver where all your encryption needs are served.\n") req.sendall("Send me something to encrypt:\n") data = recvline(req).strip() try: data = base64.b64decode(data) except: req.sendall("bad data\n") req.close() return if not data.startswith("l33tserver please"): req.sendall("You didnt say the magic word :(\n") req.close() return c = AESCipher(KEY).encrypt(pad(data, 16)) req.sendall("Your l33tcrypted data:\n") req.sendall(base64.b64encode(c) + "\n") req.close()
def decrypt(message: bytes, aes: AES.AESCipher) -> bytes: """Déchiffre une chaîne d'octets Déchiffrement d'une chaine codée sur un multiple de 16 octets. Le déchiffrement est effectué à l'aide de l'AES, fourni au préalable. La fonction retourné donc la chaine déchiffré. """ # Get ASCII string of decrypted data encrypted = aes.decrypt(message).decode() # Retrieve size of padding by parsing header header = int(encrypted[0], 16) # Retrieve only payload of encoded data by stripping header # and padding decrypted = encrypted[1:(len(encrypted) - header)] # Decoding data from ASCII binary representation decrypted_bytes = binascii.unhexlify(decrypted) # Returning bytes after pickle unserialization return pickle.loads(decrypted_bytes)
def encrypt_telegraph(secret, public_key=None): """ Encrypt 'secret' with AES encryption and get its key and iv RSA encrypted. Return a key and IV self-including cipher string. :Parameters: secret: string string to encrypt. output: string string in base64. """ secret += AES_PADDING * (AES.block_size - len(secret) % AES.block_size) key = Random.new().read(AES_KEY_SIZE) iv = Random.new().read(AES_KEY_SIZE) cipher = AESCipher(key, AES_CIPHER_MODE, iv).encrypt(secret) result_dict = { ENCRYPT_TELEGRAPH_KEY_NAME: encrypt(b64encode(key + iv), public_key=public_key), ENCRYPT_TELEGRAPH_CIPHER_NAME: b64encode(cipher), } return b64encode(json.dumps(result_dict))
def decrypt_AES128CCM(key, n, M, c, a): # Set parameters L = 15-len(n) ln = len(n) la = len(a) lm = len(c) - M lblock = AES.block_size assert( L >= 2 and L <= 8 ) assert( lm < (1<<(8*L)) ) aes = AESCipher(key) # PART 1: Compute the key stream to get MAC value and authentication tag U = c[-M:] Lp = L-1 Flags = struct.pack("B", Lp) i = 0 A0 = Flags + n + struct.pack("!Q", 0)[-L:] S0 = aes.encrypt(A0) T = strxor(U, S0[:M]) remaining = lm S = b'' while remaining >= lblock: remaining -= lblock i += 1 Ai = Flags + n + struct.pack("!Q", i)[-L:] Si = aes.encrypt(Ai) S = S + Si i += 1 Aend = Flags + n + struct.pack("!Q", i)[-L:] Send = aes.encrypt(Aend)[:remaining] S = S + Send m = strxor(c[:-M], S) # PART 2: Compute the MAC to verify the authentication tag # Note: With no data, this is just AES-CBC with B0 as the IV Adata = 0 if la > 0: Adata = 1 Mp = (M-2)/2 Lp = L-1 Flags = 64*Adata + 8*Mp + Lp B = struct.pack("B", Flags) + n + struct.pack("!Q", lm)[-L:] # If there is associated data, append it if la > 0: # Encode the length La = b'' if (la < 2**16 - 2**8): La = struct.pack("!H", la) elif (la < 2**32): La = b'\xFF\xFE' + struct.pack("!I", la) elif (la < 2**64): La = b'\xFF\xFE' + struct.pack("!Q", la) lla = len(La) # Compute the amount of zero-padding we need lza = lblock - ((la + lla)%lblock) B = B + La + a + b'\0'*lza # Append the message lzm = lblock - (lm % lblock) B = B + m + b'\0'*lzm nB = len(B) / lblock # Compute the CBC-MAC X = aes.encrypt( B[:lblock] ) for i in range(nB-1): X = strxor( X, B[ lblock*(i+1) : lblock*(i+2) ] ) X = aes.encrypt(X) if T != X[:M]: raise Exception("Integrity check failed") return m
def encrypt_AES128CCM(key, n, M, m, a): # Set parameters ln = len(n) lm = len(m) la = len(a) lblock = AES.block_size L = 15-len(n) assert( L >= 2 and L <= 8 ) assert( lm < (1<<(8*L)) ) aes = AESCipher(key) # PART 1: Compute the authentication tag # Note: With no data, this is just AES-CBC with B0 as the IV Adata = 0 if la > 0: Adata = 1 Mp = (M-2)/2 Lp = L-1 Flags = 64*Adata + 8*Mp + Lp B = struct.pack("B", Flags) + n + struct.pack("!Q", lm)[-L:] # If there is associated data, append it if la > 0: # Encode the length La = b'' if (la < 2**16 - 2**8): La = struct.pack("!H", la) elif (la < 2**32): La = b'\xFF\xFE' + struct.pack("!I", la) elif (la < 2**64): La = b'\xFF\xFE' + struct.pack("!Q", la) lla = len(La) # Compute the amount of zero-padding we need lza = lblock - ((la + lla)%lblock) B = B + La + a + b'\0'*lza # Append the message lzm = lblock - (lm % lblock) B = B + m + b'\0'*lzm nB = len(B) / lblock # Compute the CBC-MAC X = aes.encrypt( B[:lblock] ) for i in range(nB-1): X = strxor( X, B[ lblock*(i+1) : lblock*(i+2) ] ) X = aes.encrypt(X) T = X[:M] # PART 2: Encrypt the message Flags = struct.pack("B", Lp) i=0 A0 = Flags + n + struct.pack("!Q", i)[-L:] S0 = aes.encrypt(A0) U = strxor(T, S0[:M]) remaining = lm S = b'' while remaining >= lblock: remaining -= lblock i += 1 Ai = Flags + n + struct.pack("!Q", i)[-L:] Si = aes.encrypt(Ai) S = S + Si i += 1 Aend = Flags + n + struct.pack("!Q", i)[-L:] Send = aes.encrypt(Aend)[:remaining] S = S + Send c = strxor(m, S) return c+U
s = G.get_identity() a = self while n > 0: if n & 1: s = s.star(a) a = a.star(a) n = n >> 1 return s def __repr__(self): return repr(self.x) def __str__(self): return str(self.x) # PART 2: all you need to get flag import os from Crypto.Cipher.AES import AESCipher from secret import flag key = os.urandom(16) print( AESCipher(key).encrypt(flag.encode() + b"\x00" * (-len(flag) % 16)).hex()) # 4e8f206f074f895bde336601f0c8a2e092f944d95b798b01449e9b155b4ce5a5ae93cc9c677ad942c32d374419d5512c k = int.from_bytes(key, "big") g = G(2) print(g.repeated_star(k)) # 675847830679148875578181214123109335717
def decrypt(self, message) : cipher = AESCipher.__init__(self, self.sessionKey) decryptedMessage = cipher.decrypt(b64decode(message)) return decryptedMessage
import base64 from Crypto.Cipher.AES import AESCipher KEY = 'YELLOW SUBMARINE' if __name__ == '__main__': cipher = AESCipher(KEY) with open('7.txt', 'r') as f: ctext = base64.b64decode(f.read()) print(cipher.decrypt(ctext))
def encrypt_AES128CCM(key, n, M, m, a): # Set parameters ln = len(n) lm = len(m) la = len(a) lblock = AES.block_size L = 15 - len(n) assert (L >= 2 and L <= 8) assert (lm < (1 << (8 * L))) assert (2 <= M and M <= 16 and M % 2 == 0) aes = AESCipher(key) # PART 1: Compute the authentication tag # Note: With no data, this is just AES-CBC with B0 as the IV Adata = 0 if la > 0: Adata = 1 Mp = (M - 2) / 2 Lp = L - 1 Flags = 64 * Adata + 8 * Mp + Lp B = struct.pack("B", Flags) + n + struct.pack("!Q", lm)[-L:] # If there is associated data, append it if la > 0: # Encode the length La = b'' if (la < 2**16 - 2**8): La = struct.pack("!H", la) elif (la < 2**32): La = b'\xFF\xFE' + struct.pack("!I", la) elif (la < 2**64): La = b'\xFF\xFE' + struct.pack("!Q", la) lla = len(La) # Compute the amount of zero-padding we need lza = lblock - ((la + lla) % lblock) B = B + La + a + b'\0' * lza # Append the message lzm = lblock - (lm % lblock) B = B + m + b'\0' * lzm nB = len(B) / lblock # Compute the CBC-MAC X = aes.encrypt(B[:lblock]) for i in range(nB - 1): X = strxor(X, B[lblock * (i + 1):lblock * (i + 2)]) X = aes.encrypt(X) T = X[:M] # PART 2: Encrypt the message Flags = struct.pack("B", Lp) i = 0 A0 = Flags + n + struct.pack("!Q", i)[-L:] S0 = aes.encrypt(A0) U = strxor(T, S0[:M]) remaining = lm S = b'' while remaining >= lblock: remaining -= lblock i += 1 Ai = Flags + n + struct.pack("!Q", i)[-L:] Si = aes.encrypt(Ai) S = S + Si i += 1 Aend = Flags + n + struct.pack("!Q", i)[-L:] Send = aes.encrypt(Aend)[:remaining] S = S + Send c = strxor(m, S) return c + U
def encrypt(self, message) : cipher = AESCipher.__init__(self, self.sessionKey) encrypted = cipher.encrypt(message) return encrypted.encode('base64')
def decrypt_AES128CCM(key, n, M, c, a): # Set parameters L = 15 - len(n) ln = len(n) la = len(a) lm = len(c) - M lblock = AES.block_size assert (L >= 2 and L <= 8) assert (lm < (1 << (8 * L))) aes = AESCipher(key) # PART 1: Compute the key stream to get MAC value and authentication tag U = c[-M:] Lp = L - 1 Flags = struct.pack("B", Lp) i = 0 A0 = Flags + n + struct.pack("!Q", 0)[-L:] S0 = aes.encrypt(A0) T = strxor(U, S0[:M]) remaining = lm S = b'' while remaining >= lblock: remaining -= lblock i += 1 Ai = Flags + n + struct.pack("!Q", i)[-L:] Si = aes.encrypt(Ai) S = S + Si i += 1 Aend = Flags + n + struct.pack("!Q", i)[-L:] Send = aes.encrypt(Aend)[:remaining] S = S + Send m = strxor(c[:-M], S) # PART 2: Compute the MAC to verify the authentication tag # Note: With no data, this is just AES-CBC with B0 as the IV Adata = 0 if la > 0: Adata = 1 Mp = (M - 2) / 2 Lp = L - 1 Flags = 64 * Adata + 8 * Mp + Lp B = struct.pack("B", Flags) + n + struct.pack("!Q", lm)[-L:] # If there is associated data, append it if la > 0: # Encode the length La = b'' if (la < 2**16 - 2**8): La = struct.pack("!H", la) elif (la < 2**32): La = b'\xFF\xFE' + struct.pack("!I", la) elif (la < 2**64): La = b'\xFF\xFE' + struct.pack("!Q", la) lla = len(La) # Compute the amount of zero-padding we need lza = lblock - ((la + lla) % lblock) B = B + La + a + b'\0' * lza # Append the message lzm = lblock - (lm % lblock) B = B + m + b'\0' * lzm nB = len(B) / lblock # Compute the CBC-MAC X = aes.encrypt(B[:lblock]) for i in range(nB - 1): X = strxor(X, B[lblock * (i + 1):lblock * (i + 2)]) X = aes.encrypt(X) if T != X[:M]: raise Exception("Integrity check failed") return m
def encrypt(s): return AESCipher(KEY).encrypt(pad('ENCRYPT:' + s.decode('hex') + FLAG))
#!/usr/bin/env python3 #https://zachgrace.com/posts/attacking-ecb/ #Really good explanation for ECB import sys from Crypto.Hash import SHA256 from Crypto.Cipher.AES import AESCipher import base64 flag = "THIS_IS_AN_INCREDIBLY_LONG_STRING_FOR_TEST_PURPOSES_AS_THE_FLAG_MAY_ALSO_BE_LONG" #83 block_size = 16 # CAN BE 8 OR MULTIPLE OF 16 def get_key(flag): flag = flag.encode('utf-8') h = SHA256.new() h.update(flag) key = h.digest() return key key = get_key(flag) text = str(sys.argv[1]) UserInput = text + flag padding = block_size - (len(text) % block_size) UserInput += 'P' * padding # must be divisible by 16 total length cipher = AESCipher(key).encrypt(UserInput) print(str(base64.b64encode(cipher))[2:-1])
def oracle(s): # so, this is simulated. In reality we'd have to run javascript on a target web browser # and capture the traffic. That's pretty hard to do in a way that scales, though, so we # simulate it instead. # This uses ECB mode. return AESCipher(key).encrypt(pkcs7_pad('GET /' + s.decode('hex') + secret_data))
def decrypt_func(data): cipher = AESCipher(encryption_key, MODE_CBC, iv) return cipher.decrypt(data)
def decrypt(self, message): cipher = AESCipher.__init__(self, self.sessionKey) decryptedMessage = cipher.decrypt(b64decode(message)) return decryptedMessage