2016-08-02 66 views
0

我正在使用M2Crypto(0.22.6rc4)。我想使用OpenSC項目中的engine_pkcs11以及Aladdin PKI客戶端進行基於令牌的身份驗證來加密和解密數據。使用M2Crypto和USB令牌需要幫助

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 

出於某種原因,我可以對數據進行加密,但是,當嘗試解密,我得到RSA_pub的一個實例,這個錯誤:

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 

任何幫助,將不勝感激!

回答

0

RSA私鑰的M2Crypto包裝中存在一個錯誤。解決方法是使用低級M2Crypto API直接訪問私鑰對象。

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)