Search code examples
javapythonrsam2crypto

Python equivalent of password encryption from RSA key Java code


Below is the Java code that uses rsa private key (ex: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB)

and encrypts a plain string test123 using rsa public key (public key generated from rsa private key above)

byte[] array = javax.xml.bind.DatatypeConverter.parseBase64Binary(key); KeyFactorykf = KeyFactory.getInstance(“RSA”);
publicKey = kf.generatePublic(new X509EncodedKeySpec(array)); Cipher = Cipher.getInstance(“RSA”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal (“test123”.getBytes(“UTF-8”));
String output = javax.xml.bind.DatatypeConverter.printBase64Binary(result);

I tried m2crypto library to do so in python:

import base64
from M2Crypto import BIO, RSA

pubkey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB'

# encryption
text = "test123".encode('utf-8')  # Plaintext
pub_bio = BIO.MemoryBuffer(pubkey.encode('utf-8'))  # Public key string
pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
secret = pub_rsa.public_encrypt(text, RSA.pkcs1_padding)  # Public key encryption
sign = base64.b64encode(secret)  # Ciphertext base64 encoding
print(sign)

The error I am getting is:

Traceback (most recent call last):
  File "encrypt_rsa_public_key.py", line 13, in <module>
    pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 444, in load_pub_key_bio
    rsa_error()
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 333, in rsa_error
    raise RSAError(Err.get_error_message())
M2Crypto.RSA.RSAError: no start line

How can I solve this?


Solution

  • The library that you are using might expect to get the public key in PEM format i.e. enclosed between -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. So you would have to change your pubkey to :

    pubkey = '-----BEGIN PUBLIC KEY-----\n' \
             'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB' \
             '\n-----END PUBLIC KEY-----'
    

    the line breaks are important.