Delphi长字符串加密失效求助:短字符串正常长字符串异常
Delphi加密函数处理长字符串失效的原因及修复
问题根源
你的加密函数中循环变量i被定义为Byte类型,而Byte是8位无符号整数,取值范围仅为0-255。当处理长度超过255的字符串时,循环执行到i=255后,下一次递增会导致Byte溢出变为0,此时for i := 1 to Length(Text)的循环条件不再满足,循环直接终止——最终只加密了前255个字符,所以加密结果长度仅为255×2=510位左右(你看到的250字符可能是截断或描述误差)。
修复方案
把循环变量i的类型从Byte改为Integer(或Cardinal),这样就能支持更大的数值范围,处理任意长度的字符串:
function Encrypt(const Text: string): string; var i: Integer; // 将Byte替换为Integer Key: Word; strTemp: string; const KEY = 7519; KEY1 = 03001; KEY2 = 002279; begin Key := KEY; SetLength(strTemp, Length(Text)); Result := ''; for i := 1 to Length(Text) do begin strTemp[i] := Char(byte(Text[I]) xor (Key shr 8)); Result := Result + IntToHex(Byte(strTemp[i]), 2); Key := (Byte(strTemp[i]) + KEY) * KEY1 + KEY2 ; end; end;
额外性能优化
每次循环执行Result := Result + ...会频繁分配内存,处理长字符串时性能会很低。可以预先计算结果长度(原字符串长度×2),直接填充字符提升效率:
function Encrypt(const Text: string): string; var i: Integer; Key: Word; strTemp: string; HexChars: array[0..15] of Char; begin // 预定义十六进制字符,避免调用IntToHex的额外开销 HexChars := ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']; Key := 7519; SetLength(strTemp, Length(Text)); // 提前分配结果内存,长度为原字符串的2倍 SetLength(Result, Length(Text)*2); for i := 1 to Length(Text) do begin strTemp[i] := Char(byte(Text[I]) xor (Key shr 8)); // 直接填充十六进制字符 Result[2*i-1] := HexChars[Byte(strTemp[i]) shr 4]; Result[2*i] := HexChars[Byte(strTemp[i]) and $0F]; Key := (Byte(strTemp[i]) + 7519) * 03001 + 002279 ; end; end;
内容的提问来源于stack exchange,提问作者wh0v1
相关产品推荐
相关产品推荐

