我正在从我的前端转发API调用到我的后端。我使用密码“somekey”使用CryptoJS.AES加密API调用。
我的相关客户代码是......
var host = 'http://localhost:3000'
$('.send-button').click(function(){
var request = $('.request-input').val();
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest.toString())
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
console.log('Decrypted Request: ' + decryptedRequest.toString());
handleRequest(encryptedRequest.toString());
});
var handleRequest = function(request){
$.ajax({
type: "GET",
url: host + '/requests?call=' + request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
}
相关的服务器端代码是......
var port = 3000;
var serverUrl = "127.0.0.1";
var http = require("http");
var path = require("path");
var fs = require("fs");
var express = require("express");
var CryptoJs = require("crypto-js");
var app = express();
app.get('/requests', function(req, res) {
console.log('REQUEST: ' + req);
var call = req.query.call;
console.log(call)
console.log("To send: " + CryptoJs.AES.decrypt(call, 'somekey'));
});
我一直遇到的问题是,当我解密时,它要么没有获得原始URL,而是返回一堆乱码。这方面的一个例子是......
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: 68747470733a2f2f6e6577736170692e6f72672f76312f61727469636c6573
或者...它只返回任何内容并显示为空白。
理想情况下,我想要这样的东西。
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: https://newsapi.org/v1/articles
任何人都可以看到我错了吗?
答案 0 :(得分:1)
这是一个有效的jsfiddle: https://jsfiddle.net/5Lr6z4zp/1/
加密产生Base64字符串,而解密字符串为Hex。要取回“消息”,您需要将其转换为Utf8:decryptedRequest.toString(CryptoJS.enc.Utf8)
以下是有效代码的相关部分:
var request = "testing decryption";
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest)
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
console.log('Decrypted Request: ' + decryptedMessage);
以下是更详细地解释加密/解密的资源的链接: http://www.davidebarranca.com/2012/10/crypto-js-tutorial-cryptography-for-dummies/