Skip to content Skip to sidebar Skip to footer

Use Rsa To Encrypt In Javascript And Decrypt In Python3

I'm developing a website using this JS plugin to encrypt some data and send it to the server: https://github.com/travist/jsencrypt I'm running Python 3 with Django, the problem is

Solution 1:

jsencrypt depends on the jsbn library which doesn't provide OAEP, but only PKCS#1 v1.5 padding.

You have to use the same in python which PyCrypto provides. Simply use PKCS1_v1_5 instead of PKCS1_OAEP.


Note that PKCS#1 v1.5 padding shouldn't be used today anymore. I suggest you use the forge library which provides an RSA implementation with OAEP.

Solution 2:

I had been using JSEncrypt JavaScript file to achieve conversation between JavaScript and Python using pycrypto however during encryption in JavaScript it uses a random pad in the function pkcs1pad2 which needed to be removed and it started working. It had been a hack but it worked out. Following are the lines are commented out from function pkcs1pad2(s,n)

while(n > 2) { // random non-zero pad
    x[0] = 0;
    while(x[0] == 0) rng.nextBytes(x);
    ba[--n] = x[0];
  }

  ba[--n] = 2;
  ba[--n] = 0;

Solution 3:

Using PKCS1_v1_5:

def decrypt(key, text):
    if type(key) == str:
        key = key.encode()
    if type(text) == str:
        text = text.encode()

    rsakey = RSA.importKey(key)
    rsakey = PKCS1_v1_5.new(rsakey)
    d = rsakey.decrypt(text, 'bollox')return d

>>> decrypt(key, text)
b'Testing'

Post a Comment for "Use Rsa To Encrypt In Javascript And Decrypt In Python3"