1. Home
  2. Computing & Technology
  3. Delphi Programming

How to encrypt a string in Delphi for .NET
String encryption (hashing) in .NET

By Zarko Gajic, About.com

If you need to encrypt a string in Delphi for .NET you can use the System.Security.Cryptography namespace. Here's a sample function:

Note: the example below uses MD5 algorithm implementation, for a list of possible implementations read MSDN help for System.Security.Cryptography namespace.

~~~~~~~~~~~~~~~~~~~~~~~~~
uses System.Security.Cryptography, System.Text;
function Encrypt(const cleanString: string): string;
var
   ue : UnicodeEncoding;
   clearBytes, hashedBytes : array of Byte;
begin
   ue := UnicodeEncoding.Create;
   clearBytes := ue.GetBytes(cleanString) ;
   hashedBytes := (CryptoConfig.CreateFromName('MD5') AS HashAlgorithm).ComputeHash(clearBytes) ;
   Result := BitConverter.ToString(hashedBytes) ;

   //Remove "-"'s
   Result := Result.Replace('-',System.String.Empty) ;
end; (* Encrypt *)
~~~~~~~~~~~~~~~~~~~~~~~~~
Usage sample:
HashedString := Encrypt('http://delphi.about.com') ;
// HashedString = DC31A33D559C4B6609EEA9A6DA137486

Delphi tips navigator:
» LastPos function - last occurrence of one string within another
« How to add the "Select All (CTRL+A)" functionality to TMemo/TDBMemo

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2004 Delphi Tips
  7. How to encrypt a string in Delphi for .NET

©2009 About.com, a part of The New York Times Company.

All rights reserved.