帮我写一个delphi下的加解密算法,加密后的内容尽可能短的
时间: 2023-11-22 08:52:46 浏览: 50
对于 Delphi 下的加解密算法,我可以提供以下两种常见的实现方式:
一、Base64 编码
Base64 编码是一种将二进制数据转换为 ASCII 字符的编码方式,可以将原始数据进行加密处理,同时缩短加密后数据的长度。在 Delphi 中,可以使用 TNetEncoding 类进行 Base64 编码和解码的操作,具体示例如下:
```delphi
uses
System.NetEncoding;
function Encrypt(const Source: string): string;
var
Encoder: TBase64Encoding;
Bytes: TBytes;
begin
Encoder := TBase64Encoding.Create;
try
Bytes := TEncoding.UTF8.GetBytes(Source);
Result := Encoder.EncodeBytesToString(Bytes);
finally
Encoder.Free;
end;
end;
function Decrypt(const Source: string): string;
var
Decoder: TBase64Encoding;
Bytes: TBytes;
begin
Decoder := TBase64Encoding.Create;
try
Bytes := Decoder.DecodeStringToBytes(Source);
Result := TEncoding.UTF8.GetString(Bytes);
finally
Decoder.Free;
end;
end;
```
二、对称加密算法
对称加密算法是一种常见的加密方式,它使用相同的密钥对数据进行加密和解密的操作,常见的对称加密算法有 AES、DES 等。在 Delphi 中,可以使用 TEncryptor 类库进行对称加密和解密的操作,具体示例如下:
```delphi
uses
System.SysUtils, System.Classes, System.Hash, System.NetEncoding, System.Encodings;
function Encrypt(const Source: string; const Key: string): string;
var
Encryptor: TEncryptor;
Bytes: TBytes;
begin
Encryptor := TEncryptor.Create;
try
Bytes := TEncoding.UTF8.GetBytes(Source);
Encryptor.Key := THashMD5.GetHashString(Key).ToBytes;
Encryptor.Mode := TCipherMode.ECB;
Encryptor.PaddingMode := TPaddingMode.PKCS7;
Result := TBase64Encoding.Base64.EncodeBytesToString(Encryptor.EncryptBytes(Bytes));
finally
Encryptor.Free;
end;
end;
function Decrypt(const Source: string; const Key: string): string;
var
Encryptor: TEncryptor;
Bytes: TBytes;
begin
Encryptor := TEncryptor.Create;
try
Bytes := TBase64Encoding.Base64.DecodeStringToBytes(Source);
Encryptor.Key := THashMD5.GetHashString(Key).ToBytes;
Encryptor.Mode := TCipherMode.ECB;
Encryptor.PaddingMode := TPaddingMode.PKCS7;
Result := TEncoding.UTF8.GetString(Encryptor.DecryptBytes(Bytes));
finally
Encryptor.Free;
end;
end;
```
以上是两种常见的 Delphi 下的加解密算法实现方式,具体应该根据实际场景和需求选择合适的算法进行使用。