node-rsa解密不起作用

时间:2015-06-08 03:42:01

标签: java javascript node.js encryption rsa

我试图实现rsa公钥系统。 服务器使用node-js实现,并使用node-rsa库加密/解密rsa。

客户端是用java实现的。

在验证部分,客户端(java)使用服务器的公钥加密客户端的id和密码,并使用http post发布到服务器。

所以服务器可以完美地接收它们,但是在node-rsa decrypt函数中,没有任何事情发生,http请求被拒绝500

以下客户端代码

public static boolean REQ_AUTH(String user_id, String user_pw )
{
    InputStreamReader ret = null;
    try
    {
        JSONObject obj = new JSONObject();
        obj.put("user_id", "waps12b");
        obj.put("user_pw", "password");

        String cipher = VoteUtility.EncryptRSA(obj.toString());
        ret = PostHTTP(API_URL.AUTH, "cipher=" + cipher);
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject)parser.parse(ret);
        ret.close();


        String result = (String)json.get(JSON_KEY.Result);
        if(result.equals("FALSE"))
            return false;

        VoteUtility.Setting((String)json.get(JSON_KEY.Kp));
        RN = (String)json.get(JSON_KEY.RN);
        return true;
    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return false;
}

下面的服务器代码

router.all('/auth', function(req, res){
    var cipher = req.body.cipher;
    console.log('[cipher] : ' + cipher);

    var buf = new Buffer(cipher,'hex');
    console.log('[buf] : ' + buf.toString('hex'));

    var decrypted = key.decrypt(buf);
    console.log('[plain] : ' + decrypted);
}

和下面的服务器日志

[cipher] : 46641844ffffff8d18ffffffb6ffffff8d6fffffffcf37ffffffd3ffffffa520721407ffffffbf7810ffffffc87d7925ffffffae16ffffffc9620f356872ffffff892828ffffffb533ffffffb324ffffffffffffffeefffffffa6b78ffffff8effffffb1ffffffb3ffffffdd681affffffae405d105affffff9626ffffff85fffffff8ffffffc9fffffff22c69ffffffa87efffffff8ffffffe64e082fffffffd247500f176dffffffedffffffcc6c5affffffc712ffffff9136ffffffbe26672b206cffffffa56dffffffa4ffffff85ffffffc0ffffffff0b6936fffffffb61ffffff8a0f3effffff8effffff965d5851ffffffaeffffff9dffffffb1417c57ffffffbfffffffee5affffff80ffffff9bffffffac0bffffff9cffffffaf6377327d
[buf] : 46641844ffffff8d18ffffffb6ffffff8d6fffffffcf37ffffffd3ffffffa520721407ffffffbf7810ffffffc87d7925ffffffae16ffffffc9620f356872ffffff892828ffffffb533ffffffb324ffffffffffffffeefffffffa6b78ffffff8effffffb1ffffffb3ffffffdd681affffffae405d105affffff9626ffffff85fffffff8ffffffc9fffffff22c69ffffffa87efffffff8ffffffe64e082fffffffd247500f176dffffffedffffffcc6c5affffffc712ffffff9136ffffffbe26672b206cffffffa56dffffffa4ffffff85ffffffc0ffffffff0b6936fffffffb61ffffff8a0f3effffff8effffff965d5851ffffffaeffffff9dffffffb1417c57ffffffbfffffffee5affffff80ffffff9bffffffac0bffffff9cffffffaf6377327d
POST /api/auth 500 421.025 ms - 1158    

我该如何解决?

1 个答案:

答案 0 :(得分:0)

在节点js中尝试

const NodeRSA   = require('node-rsa');
const key       = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----PRIVATE_key----- 
END RSA PRIVATE KEY-----");
const text = 'helo or array';
const encrypted = key.encrypt(text, 'base64');
console.log('encrypted: ', encrypted);