# Tutorial :python RSA implemention with PKCS1

### Question:

I got the following code in javascript for RSA implementionhttp://www-cs-students.stanford.edu/~tjw/jsbn/:

`` // Return the PKCS#1 RSA encryption of "text" as an even-length hex string  function RSAEncrypt(text) {      var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);      if(m == null) return null;      var c = this.doPublic(m);      if(c == null) return null;      var h = c.toString(16);      if((h.length & 1) == 0) return h; else return "0" + h;    }    // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint    function pkcs1pad2(s,n) {      if(n < s.length + 11) { // TODO: fix for utf-8        alert("Message too long for RSA");        return null;      }      var ba = new Array();      var i = s.length - 1;      while(i >= 0 && n > 0) {        var c = s.charCodeAt(i--);        if(c < 128) { // encode using utf-8          ba[--n] = c;        }        else if((c > 127) && (c < 2048)) {          ba[--n] = (c & 63) | 128;          ba[--n] = (c >> 6) | 192;        }        else {          ba[--n] = (c & 63) | 128;          ba[--n] = ((c >> 6) & 63) | 128;          ba[--n] = (c >> 12) | 224;        }      }      ba[--n] = 0;      var rng = new SecureRandom();      var x = new Array();      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;      return new BigInteger(ba);  }    ``

In the snippets above, it seems that the pkcs1pad2 function is used for padding the message with some random bytes(maybe sth like 0|2|random|0 ) in front of the message.

I'm using the python rsa package (http://stuvel.eu/rsa) for imitating the javascript result, i'm a newbie to python world and have no idea to traslate javascript algorithm code to the python code.

Any help would be appreciated.
Jiee

### Solution:1

I know it's a bit late, but in a few days I'll release a new version of my Python-RSA package. That version will include PKCS#1 v1.5 padding, so it should be compatible with your JavaScript code ;-)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »