簡體   English   中英

我有一個 RSA 公鑰指數和模數。 如何使用 Python 加密字符串?

[英]I have a RSA public key exponent and modulus. How can I encrypt a string using Python?

給定如下所示的公鑰指數和模數,如何加密字符串並將其作為文本發送到服務器?

publicKey: 10001,
modulus: 'd0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6602'

我正在嘗試在 python 中復制 javascript rsa 庫http://www.ohdave.com/rsa/提供的功能。 在 javascript 中,它看起來像這樣:

setMaxDigits(67); //sets a max digits for bigInt
var key = new RSAKeyPair('10001', '10001', 'd0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6602');
var encrypted = encryptedString(key, 'message');
console.log(encrypted); //prints '88d58fec172269e5186592dd20446c594dbeb82c01edad41f841666500c9a530e24a282c6527ec66f4c826719f12478c6535bdc2baef86e4ff26906a26398413'

我想有一種方法可以用 PyCrypto 庫來做到這一點,但我找不到任何使用指數和模數的例子。

編輯1:

使用下面的解決方案,它似乎有效。 由於我使用的是 python 2.7,我將其修改為如下所示:

from Crypto.PublicKey.RSA import construct
from binascii import unhexlify
from codecs import encode

e = long(10001)
n = int(encode('d0eeaf17801.....5d041817005535171', 'hex'), 16)

key = construct((n, e))
a = key.encrypt('hello', None)
print(a)

('.X?\xdc\x81\xfb\x9b(\x0b\xa1\xc6\xf7\xc0\xa3\xd7}U{Q?\xa6VR\xbdJ\xe9\xc5\x1f\x
f9i+\xb2\xf7\xcc\x8c&_\x9bD\x00\x86}V[z&3\\]_\xde\xed\xdc~\xf2\xe1\xa9^\x96\xc3\
xd5R\xc2*\xcb\xd9\x1d\x88$\x98\xb0\x07\xfaG+>G#\xf7cG\xd8\xa6\xf3y_ 4\x17\x0b\x0
3z\x0cvk7\xf7\xebPyo-\xa1\x81\xf5\x81\xec\x17\x9e\xfe3j\x98\xf2\xd5\x80\x1d\xdd\
xaf\xa4\xc8I\xeeB\xdaP\x85\xa7',)

現在我想將此加密文本轉換為字符串以通過發布請求發送。 但這似乎不起作用:

a.decode('utf-8')

通過 PyCrypto,您可以使用Crypto.PublicKey.RSA.construct()函數。 您需要將模數轉換為int 這是一個示例(假設為大端):

from Crypto.PublicKey.RSA import construct

e = int('10001', 16)
n = int('d0eeaf...0b6602', 16)  #snipped for brevity
pubkey = construct((n, e))

然后您可以使用密鑰執行通常的操作(例如encrypt ):

pubkey.encrypt(b'abcde', None)

編輯:請注意,您的公共指數 10001 很可能是十六進制。 這將對應於公共公共指數 65537。我已經更新了上面的內容以反映這一點。

我嘗試了另一種使用Crypto.Cipher.PKCS1_OAEP的方法: https : Crypto.Cipher.PKCS1_OAEP並且它剛剛奏效。

PS:給定的模數似乎有問題,因為模數 n 必須是兩個大素數的乘積,因此不應該是偶數。 對 n 進行了微小的修改,以使示例代碼可運行。

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

e = int('10001', 16)
n = int('d0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6601', 16)

# Construct a `RSAobj` with only ( n, e ), thus with only PublicKey
rsaKey = RSA.construct( ( n, e ) )
pubKey = rsaKey.publickey()
print(f"Public key:  (n={hex(pubKey.n)}, e={hex(pubKey.e)})")

# Export if needed
pubKeyPEM = rsaKey.exportKey()
print(pubKeyPEM.decode('ascii'))

# Encrypt message using RSA-OAEP scheme
msg = b'Hello, world.'
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(msg)
print("Encrypted:", binascii.hexlify(encrypted))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM