Esempio n. 1
0
    def probarEncDesc(self):
        rsa = RSA()
        print ""
        opcion = 'x'
        while opcion != 's' and opcion != 'n':
            opcion = raw_input(
                "Deseas encriptar un mensaje [s] o un numero [n]: ")
            if opcion == 's':
                mensaje = raw_input(
                    "Ingresa el mensaje a encriptar (cadena): ")
                tipo = 0
            elif opcion == 'n':
                mensaje = raw_input("Ingresa el numero: ")
                tipo = 1
                if not mensaje.isdigit():
                    raise ValueError("Numero invalido")

        m_encriptado = rsa.encriptar(self.publica, mensaje, tipo)

        print ""
        print "El mensaje encriptado es: "
        if tipo == 0:
            print ''.join(map(lambda x: str(x), m_encriptado))
        else:
            print m_encriptado

        self.probarDesencriptacion(m_encriptado, tipo)
Esempio n. 2
0
 def probarDesencriptacion(self, mensaje, tipo):
     rsa = RSA()
     (_, n, d, _, _) = self.privada
     print ""
     raw_input("Presiona ENTER para probar la desencriptacion...")
     print ""
     print "Desencriptando mensaje con su llave privada..."
     print ""
     print "El mensaje en texto plano es: ", rsa.desencriptar((d, n),
                                                              mensaje, tipo)
Esempio n. 3
0
def sign():
    data = request.get_json()
    test = ImmutableMultiDict(data.get('form').items())
    form = forms.SignatureForm(test)
    response = {}
    if form.validate():
        variables = data['userStuff']
        task = tasks.transform.delay(**variables)
        transformed = task.wait()
        rsa = RSA(**transformed)
        signature = rsa.sign(form.message.data)
        response['signature'] = signature
    return jsonify(response)
Esempio n. 4
0
def decrypt():
    data = request.get_json()
    test = ImmutableMultiDict(data.get('form').items())
    form = forms.DecryptForm(test)
    response = {}
    if form.validate():
        variables = data['userStuff']
        task = tasks.transform.delay(**variables)
        transformed = task.wait()
        rsa = RSA(**transformed)
        decrypted = rsa.decrypt(form.ciphertext.data)
        response['decrypted'] = decrypted
    return jsonify(response)
Esempio n. 5
0
def send():
    data = request.get_json()
    test = ImmutableMultiDict(data.get('form').items())
    form = forms.SendKeyForm(test)
    response = {}
    if form.validate():
        parameters = data['userStuff']
        task = tasks.transform.delay(**parameters)
        keys = task.wait()
        rsa = RSA(**keys)

        task = tasks.transform.delay(**data['form'])
        transformed = task.wait()
        key, signature = rsa.send_key(**transformed)
        response['key'] = key
        response['signature'] = signature
    return jsonify(response)
Esempio n. 6
0
 def send_message(self, data: str):
     key = str(self.DH_key)
     encrypted = Des.encrypt(data, key)
     digest = Blake().digest(encrypted.to_raw())
     message = Message(encrypted, digest)
     message.signature = RSA.encrypt(
         RsaData.from_str(message.data.to_raw()), self.keypair.private)
     self.client_socket.send(pickle.dumps(message))
     print(f'Отправлено сообщение: "{data}"')
Esempio n. 7
0
def receive():
    data = request.get_json()
    test = ImmutableMultiDict(data.get('form').items())
    form = forms.ReceiveKeyForm(test)
    response = {}
    if form.validate():
        parameters = data['userStuff']
        task = tasks.transform.delay(**parameters)
        keys = task.wait()
        rsa = RSA(**keys)

        variables = {
            'modulus': form.modulus.data,
            'exponent': form.exponent.data
        }
        task = tasks.transform.delay(**variables)
        transformed = task.wait()
        key, signature = rsa.receive_key(**transformed)
        response['key'] = key
        response['signature'] = signature
    return jsonify(response)
Esempio n. 8
0
    def receive_message(self) -> str:
        key = str(self.DH_key)
        data = self.client_socket.recv(10240)
        message: Message = pickle.loads(data)
        origin = Des.decrypt(message.data, key)
        print(f'Получено сообщение: "{origin.to_raw()}"', end=', ')

        valid = message.data.to_raw() == RSA.decrypt(message.signature,
                                                     self.client_key).to_raw()

        if valid: print("подпись верна")
        else: print("подпись не верна")
Esempio n. 9
0
File: main.py Progetto: ChMcg/KMZI
def rsa_test():
    start = time.perf_counter()
    keys = RSA.generate_keys()
    end = time.perf_counter()
    print(f"Key generation time: \t{end - start}")

    raw = 'Test test test'
    print('Encrypting:', raw)

    start = time.perf_counter()
    encrypted = RSA.encrypt(raw, keys.public)
    end = time.perf_counter()
    print(f"Encryption time: \t{end - start}")

    print('Encrypted:', encrypted.to_hex())

    start = time.perf_counter()
    decrypted = RSA.decrypt(encrypted, keys.private)
    end = time.perf_counter()
    print(f"Decryption time: \t{end - start}")

    print(f"Decrypted: {decrypted.to_raw()}")
Esempio n. 10
0
    def crearPrivKDer(self, datos):
        from pyasn1.type import univ, namedtype
        from pyasn1.codec.der import encoder

        rsa = RSA()
        n, e, d, p, q = datos

        exp1 = long(d % (p - 1))
        exp2 = long(d % (q - 1))
        (_, coef, _) = rsa.egcd(q, p)

        class AsnPrivKey(univ.Sequence):
            componentType = namedtype.NamedTypes(
                namedtype.NamedType('version', univ.Integer()),
                namedtype.NamedType('modulus', univ.Integer()),
                namedtype.NamedType('publicExponent', univ.Integer()),
                namedtype.NamedType('privateExponent', univ.Integer()),
                namedtype.NamedType('prime1', univ.Integer()),
                namedtype.NamedType('prime2', univ.Integer()),
                namedtype.NamedType('exponent1', univ.Integer()),
                namedtype.NamedType('exponent2', univ.Integer()),
                namedtype.NamedType('coefficient', univ.Integer()),
            )

        # Create the ASN object
        asn_key = AsnPrivKey()
        asn_key.setComponentByName('version', 0)
        asn_key.setComponentByName('modulus', n)
        asn_key.setComponentByName('publicExponent', e)
        asn_key.setComponentByName('privateExponent', d)
        asn_key.setComponentByName('prime1', p)
        asn_key.setComponentByName('prime2', q)
        asn_key.setComponentByName('exponent1', exp1)
        asn_key.setComponentByName('exponent2', exp2)
        asn_key.setComponentByName('coefficient', coef)

        return encoder.encode(asn_key)
Esempio n. 11
0
def generate(self, length):
    rsa = RSA(length)
    keys = dict(modulus=hex(rsa.modulus)[2:],
                exponent=hex(rsa.exponent)[2:],
                secret=hex(rsa.secret)[2:])
    return keys
Esempio n. 12
0
def verify(self, **kwargs):
    verified = RSA.verify(**kwargs)
    return {'verified': verified}
Esempio n. 13
0
def encrypt(self, **kwargs):
    encrypted = RSA.encrypt(**kwargs)
    return {'encrypted': encrypted}
Esempio n. 14
0
def transform(self, **kwargs):
    result = RSA._hex_to_int(**kwargs)
    return result
Esempio n. 15
0
 def verify(self, public_key: PublicKey):
     return self.data == RSA.decrypt(RsaData.from_str(self.signature),
                                     public_key)
Esempio n. 16
0
def init_options():
    arg_parser = argparse.ArgumentParser(description="""
        Check the digital signature of a document (RSA).
    """)
    arg_parser.add_argument('document', type=Path,
                            help='Path to the document')
    arg_parser.add_argument('signature', type=Path,
                            help='Path to the signature')
    arg_parser.add_argument('--key', required=True, type=Path,
                            help='Path to the public key')
    return arg_parser.parse_args()

if __name__ == '__main__':
    options = init_options()

    with open(options.key) as f:
        n, e = f.read().split('\n')
        n = int(n)
        e = int(e)
    rsa = RSA(n)

    with open(options.document) as f:
        message = f.read()
    message_hash = SHA().hash(message)

    with open(options.signature) as f:
        if message_hash == rsa.decrypt(int(f.read()), e):
            print('Success! Document is genuine.')
        else:
            print('Fail! Document is not genuine.')
Esempio n. 17
0
 def sign(self, private_key: PrivateKey):
     return RSA.encrypt(self.data, private_key)
Esempio n. 18
0
#!/usr/bin/env python

from rsa.rsa import RSA
from util.factory import Factory
from util.files import Archivos
from util.operaciones import Opera

carpeta = "claves"

if __name__ == '__main__':
    rsa = RSA()
    print ""
    print "++++++++++ Algoritmo de encriptacion RSA ++++++++++"
    print ""
    print "Generando numeros primos aleatorios (1024-bits)..."
    print ""
    print "Generando clave publica y privada..."
    publica, privada = rsa.generar_claves()
    opera = Opera(publica, privada)
    opera.imprimirClavesP()
    opera.leerFormatoClaves()
    opera.probarEncDesc()
Esempio n. 19
0
 def __init__(self, listener_port: int = 6631) -> None:
     self.listener = socket.socket(AF_INET, SOCK_STREAM)
     self.listener.bind(('0.0.0.0', listener_port))
     self.keypair = RSA.generate_keys()
     self.des_module = Des()
Esempio n. 20
0
def init_options():
    arg_parser = argparse.ArgumentParser(description="""
        Sign a document with the digital signature (RSA).
    """)
    arg_parser.add_argument('document', type=Path, help='Path to the document')
    return arg_parser.parse_args()


if __name__ == '__main__':
    options = init_options()

    Prime_generator = Prime()
    p = Prime_generator.generate_prime(90)
    q = Prime_generator.generate_prime(90)
    e = Prime_generator.generate_prime(30)
    n = p * q
    rsa = RSA(n)
    d = rsa.get_private_key(e, p, q)

    with open(options.document) as f:
        message = f.read()
    message_hash = SHA().hash(message)

    signature = rsa.encrypt(message_hash, d)

    with open('public.key', 'w') as f:
        f.write(f'{n}\n{e}')

    with open(options.document.with_suffix('.sign'), 'w') as f:
        f.write(str(signature))