How to use decrypt with RSA private key and SHA256 on python - python

I am learning for school to encrypt and decrypt a file using public and private keys en encoding.
I used this code to encode the message. (which generates public key ≠ not private key error)
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
def signing():
#open file = message als binary
message = open('C:/Users/Gebruiker/Desktop/message.txt', "rb").read()
#open public key -> key
key = RSA.import_key(open('C:/Users/Gebruiker/Desktop/public.pem').read())
#message becomes a hash
h = SHA256.new(message)
#f = open file as write binary
f = open('C:/Users/Gebruiker/Desktop/message.signature', 'wb')
# sign hash message with private key
signature = pkcs1_15.new(key).sign(h)
#write signed hash to file
f.write(signature)
f.close()
But now i am trying to decode this message and I found all these people that do it in different ways and work with different type of encoding and encrypting. And I cant find a clear answer.
what i have right now is this
First i have to read the message so
def decrypt():
f = open('C:/Users/Gebruiker/Desktop/message.signature', 'rb').read()
then i open up my private key
key = RSA.import_key(open('C:/Users/Gebruiker/Desktop/private.pem').read())
Because I write and read in binary i have to turn it back into a hash
h = SHA256.new(f)
And then i have to decrypt the hash using my private key.???
Instead i see a lot of people using something like this.
h = pkcs1_15.new(key).sign(h) # sign hash message with private key
which i don't get. You are supposed to decode it right? not sign it again. this part makes no sense to me.
Now I have 2 problems.
I get an encoding error saying my public key is not a private key. Which is kinda the point of public keying right. so only private key can decrypt? Why am i getting an error?
I don't know how to proceed with the decrypting of my message
Can anybody help me with this?
Thanks a lot!

There is confusion in your question. Signature generation for RSA requires modular exponentiation using the values of the private key, not the public key. Modular exponentiation is also used for encryption with the public key. But although the same mathematical formula is used - at least on the surface - doesn't mean that signature generation is encryption with the private key because such a thing does not exist. Current PKCS#1 standards go out of their way to explain this fact, even though earlier PKCS#1 standards used to identify signature generation with RSA encryption.
What you are trying to do is to verify the message. That's the function you would expect rather than sign. Verification is performed by a trusted public key, not by a private key. You are not trying to decode the message, you are trying to verify that the bytes of the message are indeed signed by the private key that belongs to the same key pair as the trusted public key. Generally, the message is not recovered, not even partially. PKCS#1 is called signature generation with appendix, which contrasts with other schemes called signature generation giving message recovery. The appendix is the signature value, it needs to be appended (included with) the message to be of any use.
Actually, the fact that you can at least recover the hash over the message is specific to some schemes like PKCS#1 signature generation (officially called RSASSA-PKCS1-v1_5 in the standard). Other schemes such as PSS in the same standard may not even recover the hash. This is OK as long the verification (which can take place given the data and therefore hash) can succeed or fail. In other words, the verification should at least result in a boolean true / false, but it doesn't need to generate any other information.
Or, in simplified pseudo-code:
ciphertext = encrypt(publicKey, plaintext)
(recovered) plaintext = decrypt(privateKey, ciphertext)
and
signature = sign(privateKey, data)
verificationResult = verify(publicKey, data, signature)
where the data hashing algorithm is a configuration parameter for the signature generation & verification algorithm. If you want to include it you could e.g. include it as initial parameter:
signature = sign(SHA256alg, privateKey, data)
verificationResult = verify(SHA256alg, publicKey, data, signature)
Finally, you are talking about "decoding". You decode messages that have been encoded using an encoding scheme. Encoding/decoding does not presume the presence of a key. We're talking about encryption / decryption and signature generation / verification instead. Examples of encoding are hexadecimals / base 64 that convert binary to text. Character encoding such as UTF-8 is about converting text to binary.

The convention is to encrypt with a receives public RSA key so that only the holder of the corresponding private key can decrypt the message.
Also by convention, you would use your private RSA key to create a signatur that everybody else with the corresponding public key can verify.
In principle you could use a public key for creating a signature, but this would be an erroneous use case of the key, and is often prevented in the libraries implementing RSA. In your case you get a "public key ≠ not private key error" as you try to use a public key in a sign(..) call.
When signing you don't use the full message as input to RSA, but instead calculates a hash (you use SHA256). This hash would not need to be "decryped" in the signature verification, but instead recalculated on the original message, that you want to verify.

Related

Python library for RSA public decryption

I'm searching for a python library that is capable if decrypting and encrypting RSA (RSA_PKCS1_PADDING to be precise) with a public key. I've aleready tried pycryptodome, cryptography and rsa and all of them cannot decrypt using public key. I have searched through hundreds of posts, and all answers are useless, so to filter them:
I am not confusing a public key with a private key
Public decryption is possible (I was able to do it here)
There is no other way around. I literally need to send public encrypted messages to the server, and recieve private encrypted messages and decrypt them with the public key
Ideally it should be something like nodejs's crypto.publicDecrypt() and crypto.publicEncrypt(). Please help me to find even if not a library, but just a function that is capable of doing it. I looked through the hundreds of posts and I'm feel like I'm going insane. Thank you.
It is as you say indeed possible to encrypt with private and decrypt with public, the mathematical symmetry in RSA allows just swapping e/d in the keys and then calling the encrypt/decrypt functions.
This being said, I want to emphasize that I'm not a crypto expert and cannot say for certain that this doesn't compromise security.
So, you could extend the RSA-Key class with that swapped logic, use blackmagic to swap the implementation of the loaded key, and pass it to the normal functions:
from Crypto.PublicKey.RSA import RsaKey
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Math.Numbers import Integer
class SwappedRsaKey(RsaKey):
def _encrypt(self, plaintext):
# normally encrypt is p^e%n
return int(pow(Integer(plaintext), self._d, self._n))
def _decrypt(self, ciphertext):
# normally decrypt is c^d%n
return int(pow(Integer(ciphertext), self._e, self._n))
data = "I met aliens in UFO. Here is the map.".encode("utf-8")
# It's important to also use our swapped logic in encryption step, otherwise the lib would still use e&n (the private contains all 3 values).
private_key = RSA.import_key(open("mykey.pem").read())
private_key.__class__ = SwappedRsaKey
public_key = RSA.import_key(open("mykey.pub").read())
public_key.__class__ = SwappedRsaKey
cipher_priv = PKCS1_OAEP.new(private_key)
cipher_pub = PKCS1_OAEP.new(public_key)
enc_data = cipher_priv.encrypt(data)
# Decrypt again, just a showcase to prove we can get the value back
dec_data = cipher_pub.decrypt(enc_data)
print(dec_data.decode("utf-8"))
First of all, big thanks to Tobias K. for the short and clear answer. It worked flawlessly.
But when I tried to decrypt the server messages, pycryptodome kept returning sentinel instead of decrypted data. I decided to look into the library source code, and check what would .decrypt() return if I comment out this lines in .../Crypto/Cipher/PKCS1_v_1_5.py:
if not em.startswith(b'\x00\x02') or sep < 10:
return sentinel
And to my surprise it returned the decrypted message! Not sure that I didn't break something, but it works. I guess it was a bug? This is aleready fixed in their github repo, but the version is not released yet

How to validate a private key using a public key in python

I was wondering how I use a public key to validate a private key.
I have absolute no idea what I am doing
I am given a public key in the form :
"<RSAKeyValue><Modulus>tuRctbsnB4OSsR7gqNy1ovYZ4vDTn543o4ldX8Wthfjk7dAQKPHQYUmB7EyC4qFQ2GY3/Q+mDjJBDCWbsb8gyFuyU3L93UJ/7szvO+2A/t520srjCN4Yv7HirgpAI0LaWlo1UUUixMU2+kYNv/kBeVUL47TvOIpm0JqstQVDHhJtNMwcbY+3Q0nN4D1jNkSrQitCF3Sdms1kwsIFcdHcUh3WcUBkIefcB97DZKVY915IFbhf1/xdpPBa/E0WjNgtF5q4FI5ClH2CxsDwy2mL6qzZMvRPNWUhaFKlX+CcGvFQOtuJ4K8PZ0P3Wsq55ccxafZp3BQrEcBbto5Cll/E0Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
which is a string and I am trying to validate a private key (which is also provided as a string) with it using python. I know what the issuer and audience needs to be but I'm not sure what to do with all this information.
I have looked at some peoples examples of using various packages but I can't seem to figure out what type pub_key, private_key, and message would be... Please help me... I wish to learn
Base 64 decode the components - modulus and public exponent - of the public key from within the XML and create the public key from the decoded unsigned, big endian number values.
Then create a signature with the private key over any data and verify it with the public key using the same RSA signature algorithm such as RSA with PKCS#1 v1.5 padding. If it verifies, the keys form a key pair.
OK, since one user seems to keep struggling, let's actually give some code for you to work with (using Python3 for the integer creation using from_bytes):
#!/bin/python
from Crypto.PublicKey import RSA
from xml.dom import minidom
from base64 import b64decode
document = """\
<RSAKeyValue>
<Modulus>tuRctbsnB4OSsR7gqNy1ovYZ4vDTn543o4ldX8Wthfjk7dAQKPHQYUmB7EyC4qFQ2GY3/Q+mDjJBDCWbsb8gyFuyU3L93UJ/7szvO+2A/t520srjCN4Yv7HirgpAI0LaWlo1UUUixMU2+kYNv/kBeVUL47TvOIpm0JqstQVDHhJtNMwcbY+3Q0nN4D1jNkSrQitCF3Sdms1kwsIFcdHcUh3WcUBkIefcB97DZKVY915IFbhf1/xdpPBa/E0WjNgtF5q4FI5ClH2CxsDwy2mL6qzZMvRPNWUhaFKlX+CcGvFQOtuJ4K8PZ0P3Wsq55ccxafZp3BQrEcBbto5Cll/E0Q==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
"""
xmldoc = minidom.parseString(document)
modulusB64 = xmldoc.getElementsByTagName('Modulus')[0].firstChild.data
modulusBin = b64decode(modulusB64)
modulus = int.from_bytes(modulusBin, 'big', signed=False)
exponentB64 = xmldoc.getElementsByTagName('Exponent')[0].firstChild.data
exponentBin = b64decode(exponentB64)
exponent = int.from_bytes(exponentBin, 'big', signed=False)
public_key = RSA.construct((modulus, exponent))
Unfortunately I don't havea signature to verify (or a private key to decrypt) so I cannot help you verifying that the public key belongs to the private key. I guess there should be code samples out there that shows basic signature verification or encryption with the public key. Note that the modulus should also be unique and present in both keys for RSA, but that only helps with identification of the keys in the key pair, not so much validation.
Beware that I'm not a python programmer by profession, so there may be shortcuts for what I'm doing; feel free to edit them in.

RSA with AES 128

This is my protocol:
Encryption and signing - user A
cipher using the public key from user B
sign the encrypted message with the private key A
Verifying and decrypting - user B
verify the signature with the public key A
decrypt the message with the private key B
The private key A and B are the same (128 bit)
I want to send the text using this protocol with AES in mode CBC so i create this code but doesnt work ,apperar in signature:
bytes object has no attribute n
the code is the following:
def firmar(self, datos):
try:
h = SHA256.new(datos)
signature = pss.new(self.keyprivada).sign(h)
return signature
except (ValueError, TypeError):
return None
def comprobar(self, text, signature):
h = SHA256.new(text)
print(h.hexdigest())
verifier = pss.new(self.keypublica)
try:
verifier.verify(h, signature)
return True
except (ValueError, TypeError):
return False
This section is no longer relevant as the code has changed
Firstly, you are usine ECB this is insecure due to the relationship between text and its output being constant.
Secondly, CBC requires an IV hence a different implementation would be required.
Lastly and most crucially:
AES is NOT an asymmetric encryption algorithm
meaning that it must be encrypted and decrypted with the same key. You use the public and the private keys as you would with asymmetrical encryption methods.
An alternative:
If you were to implement RSA properly you could then generate a random byte array and use that as your key, then send it encrypted to the recipient to decrypt it and use it as the key to decrypt the aes as it would be the same.
Now:
You use the private key to sign the data... RSA requires you to use the public key (now private - not distributed) to encrypt it however you cannot decrypt something encrypted with the private key with the public key. Instead you distribute the ‘private key’ for decryption and keep the ‘public key’ for encryption so no one else can encrypt or sign the data.
WHAT are you doing!
There is a relationship between public and private keys! You cannot just use random byte arrays.
Read the Wikipedia article.

Asymmetric cryptography - Plaintext size error

I’m trying to encrypt small data using asymmetric cryptography with python. I'm currently using M2Crypto to generate 1024 bit private/public key pair.
After using different python libraries, such has M2Crypto and Pycrypto (with several variations on it), I'm having plaintext size problems: ValueError: Plaintext is too long.
This happens because I'm trying to encrypt the data and after that encrypting that last encryption (encryption over encryption), e.g.:
Encryption:
EKpuuser(EKprown(Data)) -> EData
puser: Public key user,
prown: Private key (data) owner
Decryption:
DKpruser(DKpuown(EData)) -> Data
pruser: Private key user,
puown: Public key (data) owner
I have tried many solutions that I've found around the web, but the only one that helped me to pass this problem was using signatures before doing encryption:
ciphertext = 'xpto'
m_EOi = hashlib.sha1()
m_EOi.update(ciphertext_EOi)
sig_EOi = (m_EOi.hexdigest())
But this solution isn't what I need, because after I used it and encrypt the signature (and encrypt the encryption), then do the decryption, can't decrypt the signature, so I can't get to the initial message.
Edited:
I already have done something like e.g.:
BLOCK_SIZE = 32
PADDING = '{'
message = 'today'
key = 'aaaaaaaaaa123456'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) cipher = AES.new(key)
encoded = EncodeAES(cipher, message)
key = 123
h1 = SHA256.new()
h1.update(key)
key1 = h1.digest()[0:16]
iv1 = Random.new().read(16)
cipher1 = AES.new(key1, AES.MODE_CFB, iv1)
criptogram1 = iv1 + cipher1.encrypt(data1)
But I allways have the plaintext size problem.
Asymmetric cryptography isn't made for what you are trying to do. Asymmetric cryptography is usually used in hybrid solutions to encrypt the keys of symmetric cryptographic systems which are used to encrypt the actual data.
Usually something like this:
data + a symmetric (random) key (K) -> symmetric cipher (e.g. AES) -> cipher text
K + public asymmetric key of the recipient -> asymmetric cipher -> Ke
Then you transmit the cipher text and Ke to the recipient
K is usually way smaller than the maximum data size of asymmetric ciphers while your ordinary plain text data is not.
When you encrypt data with an RSA key, for example, you want to pad the data with OAEP padding. No matter how small your plaintext is, like "Today", it's going to get padded out to the full modulus of the key, e.g. 1024 bits. If you next try to encrypt that with the same size key, it won't fit. There is no room anymore to pad again. You need a bigger key, or, you don't pad. Not padding would be a big mistake -- you need the padding to be secure.
Why would you encrypt twice anyway? It's not making it any safer. Are you devising your own scheme? That would be risky.
Why would you sign ciphertext? A digital signature over ciphertext is signing a document of unintelligible gibberish -- try taking that signature in front of a court. Why not just add a MAC?
After more research I've managed to find something that helped me. It isn't 100% what I was looking for (related to the plaintext size error) but helps me in a way that I use signatures the go around the problem. Here is the link were I did find out the information:
http://e1ven.com/2011/04/06/how-to-use-m2crypto-tutorial

How to encrypt using public key?

msg = "this is msg to encrypt"
pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file.
encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding)
Now I am trying to give file containing radix64 format public key as a parameter in this method and unable to get expected result i.e encryption using radix64 format public key.
Is there any other method in the Python API which can encrypt msg using public key after trying some mechanism?
I am getting my public key from public key server with some HTML wrapping and in radix64 format. How can I convert the public key so that it can be accepted by any encryption method?
In case someone searches for this question, I was getting the same error message:
M2Crypto.RSA.RSAError: no start line
In my case, it turned out that my keys were of type unicode. This was solved by converting the key back to ascii:
key.encode('ascii')
Did you ask this question before? See my answer to this question,
how to convert base64 /radix64 public key to a pem format in python
There is an error somewhere in the public key. It appears to be a PGP public key but with different line lengths, so it can't be used directly as an RSA public key.

Categories

Resources