/// <summary> /// 字符串加密,原理:开头4字节+每个字节的补偿长度(len*2)+内容len+校验码(1) /// /// </summary> /// <param name="source"></param> /// <returns></returns> public byte[] Encode(byte[] source) { if (source == null || source.Count() == 0) { throw new Exception("source is null"); } int lenth = source.Count(); List <short> offsetList = new List <short>(); List <byte> content = new List <byte>(); for (int i = 0; i < lenth; i++) { short offset = Encode(source[i]); offsetList.Add(offset); content.Add((byte)(source[i] + offset)); } List <byte> result = new List <byte>(); //加入字节长度:4 result.AddRange(BitConverter.GetBytes(lenth)); //加入offset 2*lenth offsetList.ForEach(x => result.AddRange(BitConverter.GetBytes(x))); //加入内容:lenth content.ForEach(x => result.Add(x)); //加入校验码 result.Add(XORHelper.GetXORCode(result)); return(result.ToArray()); }
public byte[] Decode(byte[] source) { if (source == null || source.Length == 0) { throw new Exception("soure is null"); } if (source.Length < 4) { throw new Exception("invalid source"); } byte xorCode = XORHelper.GetXORCode(source, 0, source.Length - 1); if (xorCode != source[source.Length - 1]) { throw new Exception("invalid checksum"); } int lenth = BitConverter.ToInt32(source, 0); if (source.Length != 4 + lenth * 2 + lenth + 1) { throw new Exception("invalid lenth"); } List <short> offsetList = new List <short>(); List <byte> content = new List <byte>(); for (int i = 4; i < 4 + lenth * 2; i += 2) { offsetList.Add(BitConverter.ToInt16(source, i)); } for (int i = 4 + lenth * 2; i < 4 + lenth * 2 + lenth; i++) { content.Add(source[i]); } //除去补偿值 for (int i = 0; i < lenth; i++) { content[i] = (byte)(content[i] - offsetList[i]); } return(content.ToArray()); }