有人可以给我在delphi firemonkey Mobile中加密和解密Unicode字符串的代码吗?我已经用 xor 和其他库尝试了所有东西,但什么也没有。总有一些字符无法识别为欧元符号 € 。如果有人可以帮助我,将不胜感激。
编辑:谢谢汉斯,但我总是对 stringstream 有同样的问题。此代码在 windows 中完美运行,但 ios 给我这个错误:“目标多字节代码页中不存在 Unicode 字符的映射”
unit UMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, ElAES,
FMX.StdCtrls, FMX.Layouts, FMX.Memo, Math;
type
TForm2 = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
Label2: TLabel;
Memo1: TMemo;
Layout1: TLayout;
Button1: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
PASSWORD = '1234';
var
Form2: TForm2;
implementation
{$R *.fmx}
{$R *.iPhone.fmx IOS}
function StringToHex(S: string): string;
var
i: integer;
begin
Result := '';
// Go throught every single characters, and convert them
// to hexadecimal...
for i := 1 to Length( S ) do
Result := Result + IntToHex( Ord( S[i] ), 2 );
end;
function HexToString(S: string): string;
var
i: integer;
begin
Result := '';
// Go throught every single hexadecimal characters, and convert
// them to ASCII characters...
for i := 1 to Length( S ) do
begin
// Only process chunk of 2 digit Hexadecimal...
if ((i mod 2) = 1) then
Result := Result + Chr( StrToInt( '0x' + Copy( S, i, 2 )));
end;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
Source: TStringStream;
Dest: TStringStream;
Key: TAESKey128;
begin
try
Source := TStringStream.Create( Memo1.Text );
Dest := TStringStream.Create('');
FillChar( Key, SizeOf(Key), 0 );
Move( PChar(PASSWORD)^, Key, Min( SizeOf( Key ), Length( PASSWORD )));
EncryptAESStreamECB( Source, 0, Key, Dest );
//Memo1.Lines.BeginUpdate;
Memo1.Text := Dest.DataString;
//Memo1.Lines.EndUpdate;
Label2.Text := 'Texto Encriptado';
Source.Free;
Dest.Free;
except on E: Exception do
begin
ShowMessage(e.ToString);
Source.Free;
Dest.Free;
Memo1.Text :='';
end;
end;
end;
procedure TForm2.Button3Click(Sender: TObject);
var
Source: TStringStream;
Dest: TStringStream;
Key: TAESKey128;
Size: integer;
begin
try
Source := TStringStream.Create(Trim(Memo1.Text) );
Dest := TStringStream.Create('');
Size := Source.Size;
Source.ReadBuffer(Size, SizeOf(Size));
FillChar(Key, SizeOf(Key), 0);
Move(PChar(PASSWORD)^, Key, Min(SizeOf(Key), Length(PASSWORD)));
Source.Position := 0;
DecryptAESStreamECB(Source, Source.Size - Source.Position, Key, Dest);
Memo1.Text := Trim(Dest.DataString);
Label2.Text := 'Texto Original';
Source.Free;
Dest.Free;
except on E: Exception do
begin
ShowMessage(e.ToString);
Source.Free;
Dest.Free;
Memo1.Text :='';
end;
end;
end;
end.
我也试过用这个创建字符串流:
Source := TStringStream.Create(Trim(Memo1.Text) , TEncoding.Unicode) ;
有时效果很好,有时会给我以下错误:“Los surrogate char without a prior high surrogate char at index: 8. 检查字符串是否正确编码。有什么想法吗?