delphi中使用aes算法加解密示例
delphi中使用aes算法加解密示例在 Delphi 中使用 AES 算法进行加密和解密,可以使用第三方库,例如 "Delphi Encryption Compendium (DEC)"。以下是一个示例代码,展示如何使用 DEC 库进行 AES 加密和解密:
uses
DECUtil, DECCipher, DECHash, DECFormat;
function AESEncrypt(const plainText, key: string): string;
var
cipher: TDECCipher;
keyBytes, plainBytes, cipherBytes: TBytes;
begin
keyBytes := TEncoding.UTF8.GetBytes(key);
plainBytes := TEncoding.UTF8.GetBytes(plainText);
cipher := TDECCipher.Create(TCipherMode.ECB);
try
cipher.InitEncrypt(keyBytes, TDECCipherClass.AES);
cipherBytes := cipher.Update(plainBytes);
cipherBytes := cipher.Final(cipherBytes);
finally
cipher.Free;
end;
Result := TEncoding.UTF8.GetString(cipherBytes);
end;
function AESDecrypt(const encryptedText, key: string): string;
var
cipher: TDECCipher;
keyBytes, cipherBytes, plainBytes: TBytes;
begin
keyBytes := TEncoding.UTF8.GetBytes(key);
cipherBytes := TEncoding.UTF8.GetBytes(encryptedText);
cipher := TDECCipher.Create(TCipherMode.ECB);
try
cipher.InitDecrypt(keyBytes, TDECCipherClass.AES);
plainBytes := cipher.Update(cipherBytes);
plainBytes := cipher.Final(plainBytes);
finally
cipher.Free;
end;
Result := TEncoding.UTF8.GetString(plainBytes);
end;
var
plainText, key, encryptedText, decryptedText: string;
begin
plainText := 'Hello, World!';
key := 'MySecretKey123456';
encryptedText := AESEncrypt(plainText, key);
Writeln('Encrypted Text: ' + encryptedText);
decryptedText := AESDecrypt(encryptedText, key);
Writeln('Decrypted Text: ' + decryptedText);
end.在上述代码中,我们使用了 DEC 库提供的 AES 加密和解密功能。 AESEncrypt函数接受明文和密钥作为参数,使用 AES 算法对明文进行加密,并返回加密后的字符串。 AESDecrypt函数接受加密后的字符串和密钥作为参数,使用 AES 算法对密文进行解密,并返回解密后的明文。在主程序中,我们使用示例的明文和密钥进行加密和解密,并打印结果。请确保在使用前安装并引入 DEC 库,并将相关的单元添加到 uses 子句中。
页:
[1]