Reputation: 642
Based on Google document and cryptography.io.
I attempt to encrypt a queried result which is in a JSON format which look like this {"data":"abc"}. As I know, when encrypting with SHA256, the encrypted data will be in a form of 64 characters but after I looked on and tried it with the code in the link and some modification, I got a result of 512 characters instead of 64 characters.
This is my code:
def encrypt_rsa(_rsa_pub, plaintext):
key_txt = _rsa_pub.encode()
public_key = serialization.load_pem_public_key(key_txt, default_backend())
# encrypt plaintext
pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
return public_key.encrypt(plaintext, pad)
pk = ....#public key
message = .... #query result (JSON)
x = json.dumps(message).encode('utf-8')
enc = encrypt_rsa(pk , x)
enc = base64.b64encode(enc).decode()
dec = decrypt_rsa(enc)
There is no error but I got a long encrypted data with 512 characters which is really weird. I have tried decrypting it with the code from cryptography.io and got an error:
AttributeError: 'str' object has no attribute 'decrypt'
which I think this error might occured because of the wrong encrypted data that should be 64 characters but the input is 512 characters. So, based on my case, what did I forgot or what should be add to this code to make it become an encrypted data with 64 characters that can be decrypted?
Edit: decrypt function
def decrypt_rsa(ciphertext):
private_key = .....
pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
return private_key.decrypt(ciphertext, pad)
The error occured at decrypt
at the line that return the result. I actually passed the encrypted data into this function. And I think it not because of the key since it should not provide error result like this
Upvotes: 0
Views: 2713
Reputation: 66733
You are encrypting data with RSA. (Not SHA256, that's just a parameter of the RSA encryption.) Note that RSA is typically only used to encrypt/decrypt very small amounts of data. Typically it is used to encrypt/decrypt another symmetric key, e.g. for AES, and then the bulk encryption/decryption is done with AES.
The size of the RSA cipher text is determined by the RSA key size. In this case you are probably using a 4096 bit RSA keys, which results in 4096 / 8 = 512 byte messages. Messages that are smaller are OK, those are padded. Messages that are larger will not work.
Finally, you are trying to call decrypt
on a string, which is not a thing. You need to pass the data to a decrypt_rsa
function instead, which does the reverse of the encrypt_rsa
function that you've shown.
edit, after decrypt_rsa function added to question: the error message shows that private_key
is not actually a private key as it should be, but a string. Why that is we can't say because the code to initialize private_key
is not shown.
Upvotes: 3