我在控制器中对AES CBC加密字符串(json)进行了解密,但解密后的字符串部分错误:为什么/如何?
首先我在javascript中加密填充的json(使用aes-js):
AddPaddingText(text, size) {
text += " ".repeat(size - text.length % size);
return text;
}
Encrypt(decyphered, size) {
var padded = this.AddPaddingText(decyphered, size);
var textBytes = aesjs.utils.utf8.toBytes(padded);
var encryptedBytes = this.aesCyCtr.encrypt(textBytes);
return aesjs.utils.hex.fromBytes(encryptedBytes);
}
var json = JSON.stringify([this.emailFieldValue, this.textFieldValue]);
this.cyphjson = this.Encrypt(json, 128);
this.cyphjson
被发送到api,然后:
[Route("/contact/decrypt")]
public IActionResult DecryptMessage(string message)
{
if (message is null)
return Content($"null message");
_aes.Padding = PaddingMode.None;
var messageBytes = HexToBytes(message);
using (var target = new MemoryStream())
{
using (var cs = new CryptoStream(target, _aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(messageBytes, 0, messageBytes.Length);
cs.FlushFinalBlock();
}
var dbMessage = MemoryStreamToMessage(target);
var jsonOut = JsonConvert.SerializeObject(dbMessage);
return Content(jsonOut, "application/json");
}
}
private static Message MemoryStreamToMessage(MemoryStream stream)
{
var text = Encoding.Default.GetString(stream.ToArray()).TrimEnd();
var jarray = (JArray)JsonConvert.DeserializeObject(text); //EXCEPTION HERE
var list = jarray.ToObject<List<string>>();
var storableMessage = new Message { Body = list[1], Email = list[0], Date = DateTime.Now };
return storableMessage;
}
public static byte[] HexToBytes(string hex)
{
if (hex.Length % 2 == 1)
throw new Exception("Hex string must have even number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
return arr;
}
public static int GetHexVal(char hex)
{
int val = hex;
return val - (val < 58 ? 48 : 87);
}
在MemoryStreamToMessage
中,text
有症状;所以我得到这种字符串:
“ 0 T. z \u000f 8 ”,“我的信息已满\”]“
而不是:
[“sender@server.com”,“我的消息已满”]
对我来说,在编码中看起来像是字节的变化,但我在两侧都使用了byte [] - UTF8转换。任何一个人?