我在RSA http://www-cs-students.stanford.edu/~tjw/jsbn/的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代码。
任何帮助都将不胜感激。
杰伊
发布于 2011-08-03 03:56:28
我知道现在有点晚了,但是几天后我会发布我的Python-RSA包的一个新版本。该版本将包含PKCS#1 v1.5填充,因此它应该与您的JavaScript代码兼容;-)
https://stackoverflow.com/questions/2565096
复制相似问题