我必须使用Javascript对URL进行加密和编码,然后使用C#进行解密和解码。
如果我使用Visual Studio在“调试”中运行代码。它表现很好。但是,当我使用表单中的URL调用应用程序时,它失败并显示错误:“要解密的数据长度无效。”
我在这里做错了什么?我已经审查了多个教程,但是找不到并解决该问题。
加密JavaScript代码:
function Encrypt(value){
var key = CryptoJS.enc.Utf8.parse("1234567812345678");
var iv = CryptoJS.enc.Utf8.parse("1234567812345678");
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var encodedValue = window.btoa(encrypted);
console.log("encodedValue: " + encodedValue);
var decodedValue = window.atob(encodedValue);
console.log("decodedValue: " + decodedValue);
return encodedValue;
}
function openAws(event) {
event.preventDefault()
var lastname = document.getElementById("lastname").value;
var firstname = document.getElementById("firstname").value;
var email = document.getElementById("email").value;
var time1 = new Date();
var hour = time1.getUTCHours();
if(hour < 10)
hour = "0" + hour;
var min = time1.getUTCMinutes();
if(min < 10)
min = "0" + min;
var sec = time1.getUTCSeconds();
if(sec < 10)
sec = "0" + sec;
var timestamp = hour.toString() + min.toString() + sec.toString();
var encryptedValues = encryptTestURL + "?lastname=" + Encrypt(lastname) + "&firstname=" + Encrypt(firstname) + "&email=" + Encrypt(email) + "×tamp=" + Encrypt(timestamp);
}
解密C#代码:
public string DecryptParams(string param)
{
var keyBytes = Encoding.UTF8.GetBytes("1234567812345678");
var iv = Encoding.UTF8.GetBytes("1234567812345678");
//Decrypt from CryptoJS
var decodedParam = HttpUtility.UrlDecode(param);
var encrypted = Convert.FromBase64String(decodedParam);
var decriptedFromJavascript = DecryptedStringFromBytes(encrypted, keyBytes, iv);
return decriptedFromJavascript;
}
public static string DecryptedStringFromBytes(byte[] cypherText, byte [] key, byte [] iv)
{
if(cypherText == null || cypherText.Length <= 0)
{
throw new ArgumentException("cypherText");
}
if(key == null || key.Length <= 0)
{
throw new ArgumentException("key");
}
if(iv == null || iv.Length <= 0)
{
throw new ArgumentException("key");
}
//Declare String to be used
string plainText = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.None;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
using (var msDecrypt = new MemoryStream(cypherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
//Read Decrypted bytes
plainText = srDecrypt.ReadToEnd();
}
}
}
}
return plainText;
}
答案 0 :(得分:0)
我在这里有一个猜测,也许您的URL参数解析器可能会由于'='填充字符而与base64解码混淆。最重要的是,AES函数的输入/输出必须按块对齐。看到您使用的是128位密钥/ IV,则必须确保提供的加密/解密功能具有16字节对齐的大小(除非您的框架另有明确说明)。