Delphi: simple string encryption

后端 未结 4 731
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 23:23

I have a string - a serial number of a mother board (only numbers and letters). How to encrypt/decrypt it and have a normal view: letters only from A to Z and numbers from 0

4条回答
  •  时光取名叫无心
    2020-12-14 23:56

    Simple Enc/Dec with support Unicode , Enc output is only hexadecimal characters :

    const CKEY1 = 53761;
          CKEY2 = 32618;
    
    function EncryptStr(const S :WideString; Key: Word): String;
    var   i          :Integer;
          RStr       :RawByteString;
          RStrB      :TBytes Absolute RStr;
    begin
      Result:= '';
      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;
      for i := 0 to Length(RStr)-1 do begin
        Result:= Result + IntToHex(RStrB[i], 2);
      end;
    end;
    
    function DecryptStr(const S: String; Key: Word): String;
    var   i, tmpKey  :Integer;
          RStr       :RawByteString;
          RStrB      :TBytes Absolute RStr;
          tmpStr     :string;
    begin
      tmpStr:= UpperCase(S);
      SetLength(RStr, Length(tmpStr) div 2);
      i:= 1;
      try
        while (i < Length(tmpStr)) do begin
          RStrB[i div 2]:= StrToInt('$' + tmpStr[i] + tmpStr[i+1]);
          Inc(i, 2);
        end;
      except
        Result:= '';
        Exit;
      end;
      for i := 0 to Length(RStr)-1 do begin
        tmpKey:= RStrB[i];
        RStrB[i] := RStrB[i] xor (Key shr 8);
        Key := (tmpKey + Key) * CKEY1 + CKEY2;
      end;
      Result:= UTF8Decode(RStr);
    end;
    

    Example :

    procedure TForm1.btn1Click(Sender: TObject);
    begin
      txt2.Text:= EncryptStr(txt1.Text, 223);
      lbl1.Caption:= DecryptStr(txt2.Text, 223);
    end;
    

提交回复
热议问题