创建时间:2023.7.28
建议:最好直接用字符串,我是没办法要求保密,存取都是字符串,程序里面是byte数组
一般数据流到前端会有专门解码的我这边不需要就没搞
既然他到前端接收成字符串就是被转码了
那我们反向转码就好了
这是在后端处理
//byte[]转字符public static string BytesToHex(byte[] bytes){return BytesToHex(bytes, 0, (bytes != null) ? bytes.Length : 0);}public static string BytesToHex(byte[] bytes, int index, int count){StringBuilder stringBuilder = new StringBuilder();int i = index;for (int num = index + count; i < num; i++){stringBuilder.Append(bytes[i].ToString("X2"));}return stringBuilder.ToString();}
用法呢就是
byte[] keyList=[12,12,12,12,12,12]var key = BytesToHex(keyList)
后补充:这个是解码:前端接收byte[]成字符串,传回字符串到后端进行解码
// 字符转byte[] public static bool HexToBytes(string s, int stringIndex, byte[] buffer, int bufferIndex, int byteCount){int num = ((s != null) ? (s.Length - 1) : 0);int num2 = 0;while (stringIndex < num && num2 < byteCount){if (byte.TryParse(s.Substring(stringIndex, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture.NumberFormat, out var result)){buffer[bufferIndex] = result;bufferIndex++;num2++;stringIndex += 2;continue;}return false;}return true;}public static bool HexToBytes(string s, out byte[] bytes){int num = s?.Length ?? 0;if (num % 2 == 0){int num2 = num / 2;bytes = new byte[num2];return HexToBytes(s, 0, bytes, 0, num2);}bytes = null;return false;}使用HexToBytes(s, out var bytes)var bytess 就是解码后的字符
这个是我从俄罗斯大佬项目里面(借鉴的),解码byte[]到前端转成字符后,传回后端字符进行解码的方法。这个我也是抄的,我项目里面可以,不能用我也没办法