Here is the code for the Console app:
namespace ConsoleApplication1;
interface
uses
System.Windows.Forms,
System.Linq;
type
ConsoleApp = class
public
[STAThread]
class method Main(args: array of String);
end;
implementation
class method ConsoleApp.Main(args: array of String);
begin
var x := 'test';
var y := x.Encrypt( x );
Console.WriteLine( 'x=' + x );
Console.WriteLine( 'y=' + y );
Console.ReadLine;
end;
end.
And here is the extension code:
namespace ConsoleApplication1;
interface
Extension method String.Encrypt( dataToEncrypt: String ) : String;
implementation
uses
System.IO,
System.Security.Cryptography,
System.Text;
Extension method String.Encrypt(dataToEncrypt: String ) : String;
var
aes : AesManaged;
password : String;
inBytes : array of Byte;
encryptTransform : ICryptoTransform;
outBytes : array of Byte;
method GetSecretKey( password : String ) : array of Byte;
var
salt : array of Byte;
iterations : Integer;
rfc2898 : System.Security.Cryptography.Rfc2898DeriveBytes;
begin
salt := new Byte[ (172, 137, 25, 56, 156, 100, 136, 211, 84, 67, 96, 10, 24, 111, 112, 137, 3 )];
iterations := 1024;
rfc2898 := new System.Security.Cryptography.Rfc2898DeriveBytes( password, salt, iterations );
result := rfc2898.GetBytes( 16 );
end;
begin
password := 'xxx';
aes := new AesManaged;
aes.KeySize := 128;
aes.BlockSize := 128;
aes.Mode := CipherMode.CBC;
aes.Padding := PaddingMode.PKCS7;
aes.Key := GetSecretKey( password );
inBytes := System.Text.Encoding.UTF8.GetBytes( dataToEncrypt );
encryptTransform := aes.CreateEncryptor();
outBytes := encryptTransform.TransformFinalBlock( inBytes, 0, inBytes.Length);
result := Convert.ToBase64String( outBytes );
end;
end.
… time passes …
It must have something to do with how to initialize a new array of byte. (I never know where to look as I can’t find it in documentation).
But this seemed to get past the compiler error:
salt := new Byte[16];
salt := [ 172, 137, 25, 56, 156, 100, 136, 211, 84, 67, 96, 10, 24, 111, 112, 137, 3 ];