1

I am using M2Crypto (0.22.6rc4). I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication to encrypt and decrypt data.

from M2Crypto import Engine, m2, RSA, BIO

slot_id = "slot_01"
pin = "password"
dynamic = Engine.load_dynamic_engine("pkcs11", "/usr/lib/ssl/engines/libpkcs11.so")
pkcs11 = Engine.Engine("pkcs11")
pkcs11.ctrl_cmd_string("MODULE_PATH", "/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so")
pkcs11.init()
r = pkcs11.ctrl_cmd_string("PIN", pin)

pubkey = pkcs11.load_public_key(slot_id, pin)
priv = pkcs11.load_private_key(slot_id, pin)
enc = pubkey.get_rsa().public_encrypt("teste", RSA.pkcs1_oaep_padding)
dec = priv.get_rsa().private_decrypt(enc, RSA.pkcs1_oaep_padding)
print dec

For some reason I can encrypt data, but when try to decrypt I get an instance of RSA_pub and this error:

    File "pkcs11.py", line 14, in <module>
    dec = priv.get_rsa().private_decrypt(enc, RSA.pkcs1_oaep_padding)
  File "/usr/lib/python2.7/dist-packages/M2Crypto/RSA.py", line 279, in private_decrypt
    raise RSAError, 'RSA_pub object has no private key'
M2Crypto.RSA.RSAError: RSA_pub object has no private key

Any help would be appreciated!

miken32
  • 42,008
  • 16
  • 111
  • 154

1 Answers1

0

There is a bug in the M2Crypto wrapping of RSA private keys. A work around is use the low level M2Crypto API to directly access the private key object.

def decrypt(cipher_text):
    # Load the key using high level API
    engine = Engine.Engine('pkcs11')
    engine.init()
    key_slot = 'slot_1-id_01'
    privKey = engine.load_private_key(key_slot)

    # Get a pointer to the low level API object
    rsa_ptr = m2.pkey_get1_rsa(privKey.pkey)
    rsaWrapper = RSA.RSA(rsa_ptr, 1)

    # Decrypt with low level API
    results = m2.rsa_private_decrypt(rsaWrapper.rsa, ciphertext, 1)