Python中带PKCS1的RSA实现

0 投票
1 回答
4020 浏览
提问于 2025-04-15 21:09

我在网上找到了一个用JavaScript实现RSA加密的代码,链接在这里http://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);
}  

在上面的代码片段中,似乎有一个叫做pkcs1pad2的函数,它的作用是给消息前面加上一些随机的字节(可能是像0|2|随机数|0这样的格式)。

我现在在用Python的rsa包(http://stuvel.eu/rsa)来模仿JavaScript的结果,但我对Python还很陌生,不知道怎么把JavaScript的算法代码转换成Python代码。

如果有人能帮帮我,我会非常感激。
Jiee

1 个回答

0

我知道现在说这个有点晚,不过在几天后我会发布我这个Python-RSA包的新版本。这个新版本会加入PKCS#1 v1.5填充功能,这样就可以和你的JavaScript代码兼容了;-)

撰写回答