首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PKCS1实现python RSA

用PKCS1实现python RSA
EN

Stack Overflow用户
提问于 2010-04-02 13:12:58
回答 1查看 3.4K关注 0票数 0

我在RSA http://www-cs-students.stanford.edu/~tjw/jsbn/的javascript中获得了以下代码

代码语言:javascript
复制
 // 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| random |0 )。

我使用python rsa包(http://stuvel.eu/rsa)来模拟javascript结果,我是python世界的新手,不知道如何将javascript算法代码转换成python代码。

任何帮助都将不胜感激。

杰伊

EN

回答 1

Stack Overflow用户

发布于 2011-08-03 03:56:28

我知道现在有点晚了,但是几天后我会发布我的Python-RSA包的一个新版本。该版本将包含PKCS#1 v1.5填充,因此它应该与您的JavaScript代码兼容;-)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2565096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档