2013-07-09 33 views
1

爲什麼這個代碼:RSA解密帶龍頭空字節

s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00" 
from Crypto.PublicKey import RSA 
from Crypto.Util import randpool 
key = RSA.generate(1024, randpool.RandomPool().get_bytes) 
d = key.encrypt(s, None) 
dec = key.decrypt(d) 
print ''.join([ "%02X " % ord(x) for x in dec ]).strip() 

輸出:的

03 00 00 00 69 64 00 00 

代替

00 00 00 00 03 00 00 00 69 64 00 00 

回答

1

這是因爲默認的加密算法增加了一些領先空字節添加到消息中,並且解密算法剝離所有前導空字節,即使它們在原始字節中信息。

解決方案是使用Crypto.Cipher.PKCS1_OAEP進行加密/解密。

from Crypto.PublicKey import RSA 
from Crypto.Util import randpool 
from Crypto.Cipher import PKCS1_OAEP as PKCS 


s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00" 
key = RSA.generate(1024, randpool.RandomPool().get_bytes) 

cipher = PKCS.new(key) 
encr = cipher.encrypt(s) 
decr = cipher.decrypt(encr) 
+2

+1作爲答案,但是您能否將PKCS1_v1_5替換爲PKCS1_OAEP?效果是一樣的,但你不鼓勵任何人使用破解的加密方案。 – SquareRootOfTwentyThree

+0

完成!感謝您的更正。 –