How to encrypt data with RSA private key in python?

耗尽温柔 提交于 2019-12-12 17:55:39

问题


I've installed pyCrypto package on Python 2.7.1 to do some cryptography operations.

Q1: The operation that I want to do is encrypting some data with private Key (instead of public Key). It seems that this library can't do it. Am I right? If so, is there any library capable to do that?

Q2: In the documentation it is not mentioned which hash algorithm is used to calculate the signature! How can I find out which hash function is used for sign method?

Q3: You see a part of documentation about encrypt method:

encrypt(self, plaintext, K)

Encrypt a piece of data with RSA.

Parameters:

plaintext (byte string or long) - The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (n).

(Censored!)

As you see above, the input data is limited to those that are not numerically larger than the RSA module. Does this mean that I can't encrypt 0x21...(257 bytes) with an RSA key pair with module = 0x11...(257 bytes) (for example) because 0x21 is greater than 0x11? If so, why? Isn't it weird to compare the values before encryption each time?! Or it is only meant that the data length must be equal or smaller than the module length?


回答1:


In public key cryptography, you do not encrypt with the private key -- you always use the public key. Otherwise, since the public key is "public", anybody could decrypt the ciphertext.

You might be tempted to use the public and private keys interchangeably, but generally, given the private key, you can figure out the public key without much work. So, if you give someone the private key thinking that you will keep the public key safe, well, it won't be safe.

When they say not larger than the modulus, they mean the size in bytes. It will actually be smaller that the size of the modulus (256 bytes for a 2048 bit RSA key pair). But the data should actually be smaller than the modules because you will want to always pad the data. Padding, for example with OAEP padding, randomizes the ciphertext. Each time you encrypt the same plaintext, you get different ciphertext that looks random. This is important because otherwise the ciphertext is weak and open to attack even if the attacker does not have the private key. So you want to leave some room for the data plus the padding to fit in the modulus (e.g. 256 bytes).

Generally, you sign with the private key. In RSA, this actually does "encrypt" with the private key, but I don't think you will find "encrypt with private key" in any popular API.

I am not familiar with pyCrypto but it looks to me like you pick your favorite hash when signing. You hash yourself, and give the digest to the sign function, as far as I can tell from examples I've googled.



来源:https://stackoverflow.com/questions/38045324/how-to-encrypt-data-with-rsa-private-key-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!