Search code examples
javascriptpython-2.7rsapycryptopidcrypt

RSA communication between Javascript and Python


I am working on a prototype, so it needs to use RSA between a Chrome Extension and a Python Server.

So far I was planning on using https://sourceforge.net/projects/pidcrypt/ and https://www.dlitz.net/. However, while I can get decrypt and encrypt to work as per the documentation, I cannot get one to decrypt each other's message.

Can someone please, either suggest libraries that interoperate or let me know if I am doing something wrong with this libraries?

From what I worked out, pidder uses RSA PKCS#1 encryption-style padding (type 2). From googling, I sort of worked out that it is the type that PyCrypto calls PKCS1_OAEP. I am not too sure, but I have tried the standard and the other one two.

Help would be really appreciated!


Solution

  • The Javascript library (pidCrypt) uses PKCS#1 v1.5 for RSA encryption, not OAEP.

    That is supported by PyCrypto (see here). This is the example for encryption:

    from Crypto.Cipher import PKCS1_v1_5
    from Crypto.PublicKey import RSA
    from Crypto.Hash import SHA
    
    message = 'To be encrypted'
    h = SHA.new(message)
    
    key = RSA.importKey(open('pubkey.der').read())
    cipher = PKCS1_v1_5.new(key)
    ciphertext = cipher.encrypt(message+h.digest())
    

    And decryption:

    from Crypto.Hash import SHA
    from Crypto import Random
    
    key = RSA.importKey(open('privkey.der').read())
    
    dsize = SHA.digest_size
    sentinel = Random.new().read(15+dsize)      # Let's assume that average data length is 15
    
    cipher = PKCS1_v1_5.new(key)
    message = cipher.decrypt(ciphertext, sentinel)
    
    digest = SHA.new(message[:-dsize]).digest()
    if digest==message[-dsize:]:                # Note how we DO NOT look for the sentinel
         print "Encryption was correct."
    else:
         print "Encryption was not correct."
    

    Note that PKCS#1 v1.5 encryption scheme is know to be badly broken.