wirelessr
12/6/2017 - 2:26 AM

Encrypt using modulus and exponent

I survey cross over the Internet, but most of information is talking about PEM. There are some using modulus and exponent to encrypt via PHP and javascript. About Python? No! No! Nothing! Thus, I tried to record the piece of code.

import binascii
import M2Crypto
import base64

'''
<RSAKeyValue>
    <Modulus>xF9y25EXh8n99sXtU/JAsYTwML6PB7gSCE8tWw8Www2KBfDqohQBL8FMs8jzsDQa7WwoEmiVJ1resEC9YXJGbwQyWgb9qgooC9oSnCB/TkRdBybwby0DKuZOzq+609OBGkwWpgnS4QVCBc6eW+10l3qE3/2hKdcSV+08iRYp7zs=</Modulus>
    <Exponent>AQAB</Exponent>
</RSAKeyValue>
'''

modulus = 'xF9y25EXh8n99sXtU/JAsYTwML6PB7gSCE8tWw8Www2KBfDqohQBL8FMs8jzsDQa7WwoEmiVJ1resEC9YXJGbwQyWgb9qgooC9oSnCB/TkRdBybwby0DKuZOzq+609OBGkwWpgnS4QVCBc6eW+10l3qE3/2hKdcSV+08iRYp7zs='
exponent = 'AQAB' # AQAB, etc. 
text = 'hello world'

m = base64.b64decode(modulus)
e = base64.b64decode(exponent)

rsaPubKey = M2Crypto.RSA.new_pub_key((
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(binascii.hexlify(str(e)))),
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(binascii.hexlify(str(m)))),
  ))
cipher = rsaPubKey.public_encrypt(text, M2Crypto.RSA.pkcs1_oaep_padding)
ciphertext = base64.b64encode(cipher)