...
Excerpt |
---|
There are lots of way can encrypt a text string based on a key. By the approach, you can use a single numerical key, or text string. In terms of security's point of view, text string-based key has better security performance. |
Below example shows the method encrypting a text string based on a numerical key.
Code Block | ||
---|---|---|
| ||
const CKEY1 = 53761; CKEY2 = 32618; function EncryptStrEncrypt(const S InString:WideStringstring; KeySalt: string): Stringstring; var i :integer; RStr :RawByteString Byte; StartKey, MultKey, RStrB AddKey:TBytes Absolute RStrWord; begin Result Result:= ''; if (Salt RStr:= UTF8Encode(S); for i := 0 to Length(RStr)-1 do begin RStrB[i] := RStrB[i] xor (Key shr 8); Key := (RStrB[i] + Key) * CKEY1 + CKEY2; end; '') then begin Result := InString; end else begin StartKey := Length(Salt); MultKey := Ord(Salt[1]); AddKey := 0; for i := 1 to Length(Salt) - 1 do AddKey := AddKey + Ord(Salt[i]); for i := 01 to Length(RStrInString)-1 do begin Result Result:= Result + IntToHexCHAR(Byte(RStrBInString[i], 2); ) xor (StartKey shr 8)); StartKey := (Byte(Result[i]) + StartKey) * MultKey + AddKey; end; end; end; function DecryptStrDecrypt(const SInString: Stringstring; KeySalt: string): Stringstring; var i, tmpKey :Integer; RStr :RawByteString Byte; StartKey, MultKey, RStrB AddKey:TBytes Absolute RStrWord; tmpStr :string; begin Result tmpStr:= UpperCase(S)''; if SetLength(RStr, Length(tmpStr) div 2); i:= 1; try while (i < Length(tmpStr)) do begin RStrB[i div 2]:= StrToInt('$' + tmpStr[i] + tmpStr[i+(Salt = '') then begin Result := InString; end else begin StartKey := Ord(Salt[1]); MultKey Inc(i, 2:= Length(Salt); AddKey := end0; for i except := 1 to Result:= ''; Exit; end; Length(Salt) - 1 do AddKey := AddKey + Ord(Salt[i]); for i := 01 to Length(RStrInString)-1 do begin Result tmpKey:= RStrB[i]; RStrB[i] := RStrB[i]Result + CHAR(Byte(InString[i]) xor (KeyStartKey shr 8)); KeyStartKey := (tmpKey(Byte(InString[i]) + KeyStartKey) * CKEY1MultKey + CKEY2AddKey; end; Result:= UTF8Decode(RStr)end; end; |
Example
Code Block |
---|
procedure TForm1.btn1Click(Sender: TObject); begin txt2.Text:= EncryptStr(txt1.Text, 223); lbl1.Caption:= DecryptStr(txt2.Text, 223); end; |
...