예제 #1
0
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
예제 #2
0
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")
예제 #3
0
 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)
예제 #4
0
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))
예제 #5
0
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))
예제 #6
0
	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]]
예제 #7
0
 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]]
예제 #8
0
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)
예제 #9
0
 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"
예제 #10
0
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)
예제 #11
0
    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"
예제 #12
0
 def decrypt_func(data):
     cipher = AESCipher(encryption_key, MODE_CBC, iv)
     return cipher.decrypt(data)
예제 #13
0
파일: 7.py 프로젝트: supermari0/matasano
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))
예제 #14
0
 def decrypt_func(data):
     cipher = AESCipher(encryption_key, MODE_CBC, iv)
     return cipher.decrypt(data)
예제 #15
0
def VotaHandler(request, ident, usuario=None):
    response = HttpResponse("", content_type='application/json', status=200)
    ans = {}
    ans['error'] = 0
    if request.method == 'GET':
        
        pg = request.GET.get('pg', None)
        enc = request.GET.get('enc', None)
        dec = request.GET.get('dec', None)
        if (pg is None):
            raise ParametrosIncompletosException()

        if (enc is not None):
            pas = darPassDePg(pg)
            ans['pas'] = pas 
            motor = AESCipher(pas)
            ans['ans'] = motor.encrypt(enc);
            response.write(simplejson.dumps(ans))
            return response
        elif (dec is not None):
            pas = darPassDePg(pg)
            ans['pas'] = pas 
            motor = AESCipher(pas)
            ans['ans'] = motor.decrypt(dec);
            response.write(simplejson.dumps(ans))
            return response
        
        usr = request.GET.get('u', None)
        vot = request.GET.get('v', None)
        if (usr is None or vot is None):
            raise ParametrosIncompletosException()
        
        consulta = [
                    'per.'+usr+'.humId',
                    'per.'+usr+'.nom',
                    'global.votacion',
                    ]
        
        datos = buscarTuplas(pg, consulta)
        datos = to_dict_simple(datos, None, True, ['id', 'i', 'd', 'sd'])
        
        
        if ((not ('global.votacion' in datos)) or datos['global.votacion'] is None):
            raise MalaPeticionException()
        rutaVotacion = datos['global.votacion']
        
        consulta = [
                    rutaVotacion+'.pregunta',
                    rutaVotacion+'.opciones.'+vot+'.txt',
                    ]
        
        datos2 = buscarTuplas(pg, consulta)
        datos2 = to_dict_simple(datos2, None, True, ['id', 'i', 'd', 'sd'])
        
        payloadModificacion = {"dat":{
                            rutaVotacion+'.resultado.u.'+usr: simplejson.dumps(vot)
                            },"acc":"+"}
        crearTuplas(pg, payloadModificacion)
        
        llave = ndb.Key('Pagina', comun.leerNumero(pg))
        unapagina = llave.get()
        
        publicar(unapagina.usr, unapagina.path, pg, payloadModificacion)
        
        ans['msg'] = datos2[rutaVotacion+'.pregunta']+' '+datos['per.'+usr+'.humId']+' vota por "'+datos2[rutaVotacion+'.opciones.'+vot+'.txt']+'"'
        #ans['msg1'] = datos
        #ans['msg2'] = datos2
        #ans['creacion'] = creacion

        response.write(simplejson.dumps(ans))
        return response