Skip to content

Commit

Permalink
Fix RSAEncrypt padding
Browse files Browse the repository at this point in the history
There is a bug in the `RSAEncrypt` function pulled from
[jsbn's rsa.js](http://www-cs-students.stanford.edu/~tjw/jsbn/)
where the result of the RSAEncryption is not properly left-paded.

Per http://tools.ietf.org/html/rfc2437#section-7.2.1;

   4. Convert the ciphertext representative c to a ciphertext C of
            length k octets: C = I2OSP (c, k)

where ``k`` is the length in octets of the modulus
  • Loading branch information
calve committed May 11, 2016
1 parent c41f21e commit 4fba242
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/jsbn/rsa.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ function byte2Hex(b) {
return b.toString(16);
}

function pad(value, length) {
return (value.toString().length < length) ? pad("0"+value, length):value;
}

// 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
Expand Down Expand Up @@ -94,7 +98,7 @@ function RSAEncrypt(text) {
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;
return pad(h, 512);
}

// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
Expand Down

0 comments on commit 4fba242

Please sign in to comment.