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
Related
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.
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.
I want to decrypt ssh traffic in a virtual environment such as OpenNebula.
For this purpose I extracted the six ssh keys (IVs, Encryption keys and integrity keys) from the function key_derive_keys from the openssh/opensshportable code.
If I then trace a ssh connection between a server and a client I can decrypt traffic if the two parties use AES-CBC mode without problems.
But when the parties use AES-CTR the keys derived from the same method are no longer working.
So my question is: Do I maybe extract the wrong IV? So do I have to trace a different function/struct?
My code for the AES-CTR is:
key="1A0A3EBF96277C6109632C5D96AC5AF890693AC829552F33769D6B1A4275EAE2"
iv="EB6444718D73887B1DF8E1D5E6C3ECFC"
key_hex=binascii_a2b_hex(key)
iv_hex=binascii_a2b_hex(iv)
aes = AES.new(key_hex, AES.MODE_CTR, initial_value = iv_hex, nonce=b' ')
decrypted = aes.decrypt(binascii.a2b_hex(cipher).rstrip())
print(decrypted)
Edit: created a new thread for a related but vers similar Problem here: Get the counter value after decrypt finished
Maybe someone has an idea?
Edit: I fixed the problem meanwhile. The problem was that the counter is already incremented at the authentication step, which means that when the encryption starts the counter is a little bit higher than the IV.
Which means that I had the correct keys, but the counter was wrong. I let this thread open for any one interessted.
I have some data in a python program that I'd like to encrypt before writing to a file with a password, and then read it and decrypt it before using it. I'm looking for some secure symmetric algorithm that can encrypt and decrypt against a password.
This question shows a non-secure way and suggests using libsodium. Since I'm using Python, I found pysodium. It seems to have tons of functions mapped from libsodium, but I don't know how to simply encrypt/decrypt data against password.
My problem is that it looks like all encryption algorithms use keys. I don't want to use keys. I want to only use a password. Just like what I do in the terminal:
To encrypt:
$ cat data | openssl aes-256-cbc -salt | dd of=output.des3
To decrypt:
$ dd if=output.des3 | openssl aes-256-cbc -d -salt
Is it possible to do this with pysodium (in a cross-platform way, so please don't suggest using a system call)?
So my question reduced to: "How can I encrypt data against a password in Python". I gave up on pysodium due to the lack of documentation. I used cryptography and argon2 packages to write my own encryption algorithm (it's not my own crypto algorithm, I know Rule No. 1 in crypto; it's just the procedure to utilize what's already there). So here are my functions:
import cryptography.fernet
import argon2
import base64
def encrypt_data(data_bytes, password, salt):
password_hash = argon2.argon2_hash(password=password, salt=salt)
encoded_hash = base64.urlsafe_b64encode(password_hash[:32])
encryptor = cryptography.fernet.Fernet(encoded_hash)
return encryptor.encrypt(data_bytes)
def decrypt_data(cipher_bytes, password, salt):
password_hash = argon2.argon2_hash(password=password, salt=salt)
encoded_hash = base64.urlsafe_b64encode(password_hash[:32])
decryptor = cryptography.fernet.Fernet(encoded_hash)
return decryptor.decrypt(cipher_bytes)
And here's an example on how to use them:
cipher = encrypt_data("Hi Dude, Don't tell anyone I said Hi!".encode(), "SecretPassword", "SaltySaltySalt")
decrypted = decrypt_data(cipher, "SecretPassword", "SaltySaltySalt")
print(cipher)
print(decrypted.decode())
Remember that encryption is for bytes only; not for strings. This is why I'm using encode/decode.
Why argon2? Because it's a memory hard algorithm that's very hard to break with GPUs and ASICs (yes, I'm a cryptocurrency fan).
Why Fernet? Because it uses AES CBC, which seems to be secure enough; besides, it's really easy to use (which is exactly what I need... I'm not a cryptographer, so I need a black-box to use).
Disclaimer: Please be aware that I'm not a cryptographer. I'm just a programmer. Please feel free to critique my way of encrypting and decrypting, and please feel free to add your contribution to make this better.
Can anybody tell me, how to get p,q,dp,dq and u component of rsa private key?
loading of the key:
string = open(keyfile,"rb").read();
bio = BIO.MemoryBuffer(string);
rsa = RSA.load_key_bio(bio);
what shall i do next?
M2Crypto does not support reading the rsa parameters directly, sorry.
you can kind of get e (public exponend) and n (modulus) from res.pub() (kind of, because the first bytes are not part of it).
the Crypto API on the other hand supports reading more parameters:
string = open(keyfile,"rb").read()
import Crypto.PublicKey.RSA
crsa = Crypto.PublicKey.RSA.importKey(string)
print(crsa.n, crsa.e, crsa.d, crsa.p, crsa.q, crsa.u)