def encrypt(message, pub_key): """Encrypts the given message using PKCS#1 v1.5 :param message: the message to encrypt. Must be a byte string no longer than ``k-11`` bytes, where ``k`` is the number of bytes needed to encode the ``n`` component of the public key. :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with. :raise OverflowError: when the message is too large to fit in the padded block. >>> from rsa import key, common >>> (pub_key, priv_key) = key.newkeys(256) >>> message = b'hello' >>> crypto = encrypt(message, pub_key) The crypto text should be just as long as the public key 'n' component: >>> len(crypto) == common.byte_size(pub_key.n) True """ keylength = common.byte_size(pub_key.n) padded = _pad_for_encryption(message, keylength) payload = transform.bytes2int(padded) encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n) block = transform.int2bytes(encrypted, keylength) return block
def verify(message, signature, pub_key): """Verifies that the signature matches the message. The hash method is detected automatically from the signature. :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param signature: the signature block, as created with :py:func:`rsa.sign`. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. :raise VerificationError: when the signature doesn't match the message. """ keylength = common.byte_size(pub_key.n) encrypted = transform.bytes2int(signature) decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n) clearsig = transform.int2bytes(decrypted, keylength) # Get the hash method method_name = _find_method_hash(clearsig) message_hash = _hash(message, method_name) # Reconstruct the expected padded hash cleartext = HASH_ASN1[method_name] + message_hash expected = _pad_for_signing(cleartext, keylength) # Compare with the signed one if expected != clearsig: raise VerificationError('Verification failed') return True
def decodifica_linha(g, linhas): decod = [] print "Revertendo o int para string..." for linha in range(0, linhas): decod.append(transform.int2bytes(g[linha])) print"linha", linha + 1, decod[linha] print"Decodificacao concluida" print"************************************************" return decod
def mgf1(seed, length, hasher='SHA-1'): """ MGF1 is a Mask Generation Function based on a hash function. A mask generation function takes an octet string of variable length and a desired output length as input, and outputs an octet string of the desired length. The plaintext-awareness of RSAES-OAEP relies on the random nature of the output of the mask generation function, which in turn relies on the random nature of the underlying hash. :param bytes seed: seed from which mask is generated, an octet string :param int length: intended length in octets of the mask, at most 2^32(hLen) :param str hasher: hash function (hLen denotes the length in octets of the hash function output) :return: mask, an octet string of length `length` :rtype: bytes :raise OverflowError: when `length` is too large for the specified `hasher` :raise ValueError: when specified `hasher` is invalid """ try: hash_length = pkcs1.HASH_METHODS[hasher]().digest_size except KeyError: raise ValueError( 'Invalid `hasher` specified. Please select one of: {hash_list}'. format(hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys())))) # If l > 2^32(hLen), output "mask too long" and stop. if length > (2**32 * hash_length): raise OverflowError( "Desired length should be at most 2**32 times the hasher's output " "length ({hash_length} for {hasher} function)".format( hash_length=hash_length, hasher=hasher, )) # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the # hashes formed by (`seed` + C), being `C` an octet string of length 4 # generated by converting `counter` with the primitive I2OSP output = b''.join( pkcs1.compute_hash( seed + transform.int2bytes(counter, fill_size=4), method_name=hasher, ) for counter in range(common.ceil_div(length, hash_length) + 1)) # Output the leading `length` octets of `output` as the octet string mask. return output[:length]
def verify(message, signature, pub_key): '''Verifies that the signature matches the message. The hash method is detected automatically from the signature. :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param signature: the signature block, as created with :py:func:`rsa.sign`. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. :raise VerificationError: when the signature doesn't match the message. .. warning:: Never display the stack trace of a :py:class:`rsa.pkcs1.VerificationError` exception. It shows where in the code the exception occurred, and thus leaks information about the key. It's only a tiny bit of information, but every bit makes cracking the keys easier. ''' blocksize = common.byte_size(pub_key.n) encrypted = transform.bytes2int(signature) decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n) clearsig = transform.int2bytes(decrypted, blocksize) # If we can't find the signature marker, verification failed. if clearsig[0:2] != b('\x00\x01'): raise VerificationError('Verification failed') # Find the 00 separator between the padding and the payload try: sep_idx = clearsig.index(b('\x00'), 2) except ValueError: raise VerificationError('Verification failed') # Get the hash and the hash method (method_name, signature_hash) = _find_method_hash(clearsig[sep_idx+1:]) message_hash = _hash(message, method_name) # Compare the real hash to the hash in the signature if message_hash != signature_hash: raise VerificationError('Verification failed') return True
def sign(message, priv_key, hash): """Signs the message with the private key. Hashes the message, then signs the hash with the given key. This is known as a "detached signature", because the message itself isn't altered. :param message: the message to sign. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with :param hash: the hash method used on the message. Use 'MD5', 'SHA-1', 'SHA-256', 'SHA-384' or 'SHA-512'. :return: a message signature block. :raise OverflowError: if the private key is too small to contain the requested hash. """ # Get the ASN1 code for this hash method if hash not in HASH_ASN1: raise ValueError('Invalid hash method: %s' % hash) asn1code = HASH_ASN1[hash] # Calculate the hash hash = _hash(message, hash) # Encrypt the hash with the private key cleartext = asn1code + hash keylength = common.byte_size(priv_key.n) padded = _pad_for_signing(cleartext, keylength) payload = transform.bytes2int(padded) encrypted = priv_key.blinded_encrypt(payload) block = transform.int2bytes(encrypted, keylength) return block
def decrypt(crypto, priv_key): r"""Decrypts the given message using PKCS#1 v1.5 The decryption is considered 'failed' when the resulting cleartext doesn't start with the bytes 00 02, or when the 00 byte between the padding and the message cannot be found. :param crypto: the crypto text as returned by :py:func:`rsa.encrypt` :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with. :raise DecryptionError: when the decryption fails. No details are given as to why the code thinks the decryption fails, as this would leak information about the private key. >>> import rsa >>> (pub_key, priv_key) = rsa.newkeys(256) It works with strings: >>> crypto = encrypt(b'hello', pub_key) >>> decrypt(crypto, priv_key) b'hello' And with binary data: >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key) >>> decrypt(crypto, priv_key) b'\x00\x00\x00\x00\x01' Altering the encrypted information will *likely* cause a :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use :py:func:`rsa.sign`. .. warning:: Never display the stack trace of a :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the code the exception occurred, and thus leaks information about the key. It's only a tiny bit of information, but every bit makes cracking the keys easier. >>> crypto = encrypt(b'hello', pub_key) >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte >>> decrypt(crypto, priv_key) Traceback (most recent call last): ... rsa.pkcs1.DecryptionError: Decryption failed """ blocksize = common.byte_size(priv_key.n) encrypted = transform.bytes2int(crypto) decrypted = priv_key.blinded_decrypt(encrypted) cleartext = transform.int2bytes(decrypted, blocksize) # If we can't find the cleartext marker, decryption failed. if cleartext[0:2] != b('\x00\x02'): raise DecryptionError('Decryption failed') # Find the 00 separator between the padding and the message try: sep_idx = cleartext.index(b('\x00'), 2) except ValueError: raise DecryptionError('Decryption failed') return cleartext[sep_idx + 1:]
for linha in range(0, linhas): # a funcao pow(x,y,z) eh nativa do python e com 3 argumentos vale (x**y) % z ou seja, x^y modz c.append(pow(linha_int[linha], e, n)) print"C=M^e mod(n) vale:", linha + 1, c[linha] print"Decryptando..." for linha in range(0, linhas): g.append(pow(c[linha], d, n)) print"M=C^d mod(n) vale:", linha, g[linha] print "Revertendo o int para string..." for linha in range(0, linhas): decod.append(transform.int2bytes(g[linha])) print"linha", linha, decod[linha] print"Codificacao concluida" print"************************************************" exit(0) print"Algoritmo de forca bruta..." # Conhecida a mensagem M e a chave publica e, achar a chave privada d, sabendo que n=pq e ( #https://www.vivaolinux.com.br/artigo/Quebrando-a-criptografia-RSA?pagina=3 duracao = verifica_fatores(n) print duracao
for linha in range(0, linhas): # a funcao pow(x,y,z) eh nativa do python e com 3 argumentos vale (x**y) % z ou seja, x^y modz c.append(pow(linha_int[linha], e, n)) print "C=M^e mod(n) vale:", linha + 1, c[linha] print "Decryptando..." for linha in range(0, linhas): g.append(pow(c[linha], d, n)) print "M=C^d mod(n) vale:", linha, g[linha] print "Revertendo o int para string..." for linha in range(0, linhas): decod.append(transform.int2bytes(g[linha])) print "linha", linha, decod[linha] print "Codificacao concluida" print "************************************************" exit(0) print "Algoritmo de forca bruta..." # Conhecida a mensagem M e a chave publica e, achar a chave privada d, sabendo que n=pq e ( #https://www.vivaolinux.com.br/artigo/Quebrando-a-criptografia-RSA?pagina=3 duracao = verifica_fatores(n) print duracao