Dokumen - Tips - Tms Cryptography Pack Developers Guide Tms Software Tms Cryptography Pack
Dokumen - Tips - Tms Cryptography Pack Developers Guide Tms Software Tms Cryptography Pack
1
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Contents
Contents .........................................................................................................................2
Availability ......................................................................................................................3
Online references ..............................................................................................................3
Description ......................................................................................................................4
AES (modes ECB-CBC-OFB-CTR) .............................................................................................4
AES MAC .........................................................................................................................7
AES GCM .........................................................................................................................9
RSA ............................................................................................................................. 12
EdDSA and ECIES ............................................................................................................. 16
SALSA .......................................................................................................................... 19
SHA-2........................................................................................................................... 21
SHA-3........................................................................................................................... 23
SPECK .......................................................................................................................... 26
PBKDF2 ........................................................................................................................ 29
Blake2 .......................................................................................................................... 31
RIPEMD-160 ................................................................................................................... 33
Argon2 ......................................................................................................................... 35
Converter class ............................................................................................................... 37
X509 certificates ............................................................................................................. 41
Random generators .......................................................................................................... 46
Encrypt an ini file ............................................................................................................ 47
Troubleshooting .............................................................................................................. 48
2
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Availability
TMS Cryptography Pack is available as VCL and FMX component set for Delphi and C++Builder.
TMS Cryptography Pack is available for Delphi XE2, XE3, XE4, XE5, XE6, XE7, XE8, 10 Seattle, 10.1 Berlin,
10.2 Tokyo & C++Builder XE2, XE3, XE4, XE5, XE6, XE7, XE8, 10 Seattle, 10.1 Berlin, 10.2 Tokyo.
TMS Cryptography Pack has been designed for and tested with: Windows Vista, Windows 7, Windows 8,
Windows 10, OSX 10.12.2 and iOS 10.2 or newer.
TMS Cryptography Pack supports following targets: Win32, Win64, Android, OSX32, iOS32, iOS64, (Linux
with no guarantees).
If you want to use TMS Cryptography Pack in Win64 target, there are two options:
- If you have Tokyo 10.2.1 or newer, you must uncomment {$define IDEVERSION1021} in each pas files;
- If you have older version than 10.2.1, you must copy RandomDLL.dll from the Win64 directory to
C:\Windows\System32 if you are running 64-bit Windows or to C:\Windows\SysWOW64 if you are
running 32-bit Windows.
For the use of TMS Cryptography Pack on iOS, Android or Linux, you must add the directory “libAndroid” or
“libiOSDevice32” or “libiOSDevice64” or “libLinux” in the Search Path of the Project options.
Online references
TMS software website:
http://www.tmssoftware.com
3
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Description
TMS Cryptography Pack is a software library that provides various algorithms used to encrypt, sign and
hash data. This library has been developed by Cyberens.
This manual provides a complete description of how to use the library and its various features. Each
section corresponds to an algorithm used in cryptography and a class into TMS Cryptography Pack.
The different algorithms are the following:
TAESEncryption = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
4
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
• property Key: string read FKey write SetKey; to read and write the key
• property KeyLength: TAESKeyLength read FKeyLength write SetKeyLength; to
read and write the key length in bits (128, 192 or 256 bits)
• property AType: TAESType read FType write FType; to read and write the encryption
mode (ECB, CBC, OFB or CTR)
• property OutputFormat: TConvertType read FOutputFormat write FoutputFormat;
to read and write the output format of the data (see Converter class section)
• property IVMode: TIVMode read FIVMode write FIVMode; to read and write the IV
mode, userdefined or rand.
• property IV: string read FIV write SetIV; to read and write the IV of 16 bytes if
the IV mode is userdefined (in rand mode, the IV is randomly generated and added to the
encrypted text)
• property PaddingMode: TPaddingMode read FPaddingMode write FpaddingMode; to
read and write the padding mode, PKCS7 or nopadding. In PKCS7, the length of the
encrypted text is always the length of the clear text + 16 bytes (plus 16 bytes in the case of
rand IV mode). In nopadding mode, the length of the clear text must be a multiple of 16
bytes, and no padding is added to the clear text.
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer or the input file name has Unicode characters
• property Progress: Integer read FProgress write SetProgress; to indicate
progress during encryption / decryption of a stream
• property OnChange: TNotifyEvent write FOnChange; to indicate that the progress
changes
Example of encryption with AES
var
aes: TAESEncryption;
cipher: string;
begin
aes:= TAESEncryption.Create;
aes.AType:= atCBC;
aes.KeyLength:= kl256;
aes.Unicode := yesUni;
aes.Key:= '12345678901234567890123456789012';
aes.OutputFormat:=hexa;
aes.PaddingMode:= TpaddingMode.PKCS7;
aes.IVMode:= TIVMode.rand;
cipher:= aes.Encrypt('test');
aes.Free;
end;
6
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
AES MAC
To produce a message authentication code (MAC), we use the MAC mode. It is described in the NIST
Special Publication 800-38B.
The AES MAC class is:
TAESKeyLength = (kl128,kl192,kl256);
TAESMAC = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(keyLength: TAESKeyLength; key: string;
tagSizeBits: integer; outputFormat: TConvertType; uni: TUnicode);
overload;
Destructor Destroy; override;
function Generate(s: string): string;
function Verify(s, t: string): integer;
function GenerateFromFile(s: string): string;
function VerifyFromFile(s, t: string): integer;
function GenerateFromStream(s: TStream): string;
function VerifyFromStream(s: TStream; t: string): integer;
published
property key: string read FKey write SetKey;
property keyLength: TAESKeyLength read FKeyLength write SetKeyLength default
kl128;
property tagSizeBits: integer read FTagSizeBits write SetTagSizeBits default
128;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
7
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
var
aesmac: TAESMAC;
tag: string;
begin
aesmac:= TAESMAC.Create;
aesmac.KeyLength:= kl256;
aesmac.Key:= '12345678901234567890123456789012';
aesmac.TagSizeBits:= 128;
aesmac.OutputFormat:= hexa;
aesmac.Unicode:= noUni;
tag:= aesmac.Generate('test');
aesmac.Free;
end;
8
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
AES GCM
The last mode is the Galois Counter Mode, that encrypts the message using the CTR mode and products a
tag using a hash function. It is described in the NIST Special Publication 800-38D. This mode allows the
user to verify the integrity of some additional data, without encrypt it.
The AES-GCM class is:
TAESKeyLength = (kl128,kl192,kl256);
TIVMode = (rand, userdefined);
TAESGCM = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(keyLength: TAESKeyLength; key: string;
tagSizeBits: integer; outputFormat: TConvertType; uni: TUnicode);
overload;
Constructor Create(keyLength: TAESKeyLength; key: string;
tagSizeBits: integer; outputFormat: TConvertType; uni: TUnicode;
IVLength: integer; IV: string); overload;
Destructor Destroy; override;
function EncryptAndGenerate(s, a: string): string;
function DecryptAndVerify(s, a: string; var o: string): integer;
procedure EncryptAndGenerateFromFile(inputPath, outputPath, addDataPath,
tagPath: string);
function DecryptAndVerifyFromFile(inputPath, outputPath, addDataPath,
tagPath: string): integer;
procedure EncryptAndGenerateFromStream(inputStream: TStream;
var outputStream: TStream; addDataStream: TStream;
var tagStream: TStream);
function DecryptAndVerifyFromStream(inputStream: TStream;
var outputStream: TStream; addDataStream: TStream;
var tagStream: TStream): integer;
published
property key: string read FKey write SetKey;
property keyLength: TAESKeyLength read FKeyLength write SetKeyLength default
kl128;
property tagSizeBits: integer read FTagSizeBits write SetTagSizeBits default
128;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property IVMode: TIVMode read FIVMode write FIVMode default rand;
property IV: string read FIV write SetIV;
property IVLength: integer read FIVLength write SetIVLength;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
9
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
10
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer has Unicode characters
• property Progress: Integer read FProgress write SetProgress; to indicate
progress during encryption / decryption of a stream
• property OnChange: TNotifyEvent write FOnChange; to indicate that the progress
changes
var
aesgcm: TAESGCM;
cipher: string;
begin
aesgcm:= TAESGCM.Create;
aesgcm.TagSizeBits:= 128;
aesgcm.KeyLength:= kl256;
aesgcm.Key:= '12345678901234567890123456789012';
aesgcm.OutputFormat:= base64;
aesgcm.IVMode:= TIVMode.rand;
aesgcm.Unicode := yesUni;
cipher:= aesgcm.EncryptAndGenerate('test', '');
aesgcm.Free;
end;
11
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
RSA
RSA is an asymmetric encryption algorithm and a signature algorithm, described in 1977 by Ronald Rivest,
Adi Shamir et Leonard Adleman.
To encrypt some data with RSA, it is necessary to use the public key of the recipient and to decrypt, it is
necessary to use the recipient's private key.
To sign some data with RSA, it is necessary to use the sender's private key, and the recipient verifies the
signature with the public key of the sender.
The RSA algorithm is not secured in its initial form. To make it secured, there are two options. The first is
to use OAEP for encryption and PSS for signature. OAEP has been developed as a padding scheme.
Similarly, for the signature, the secure form is called PSS. The second is to use PKCS v1.5 padding scheme
for encryption and signature. OAEP, PSS and v1.5 are described in the PKCS#1 v2.2.
We will use in our algorithms, RSA keys of length 2048, 3072 or 4096 bits.
The RSA class is:
TRSAEncSign = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; reintroduce; overload;
Constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; hashF: THashFunction; hashSB: Integer;
outputFormat: TConvertType; uni: TUnicode); reintroduce; overload;
Constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; hashF: THashFunction; hashSB: Integer;
outputFormat: TConvertType; uni: TUnicode; encT: TRSAEncType);
reintroduce; overload;
Constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; hashF: THashFunction; hashSB: Integer;
outputFormat: TConvertType; uni: TUnicode; signT: TRSASignType);
reintroduce; overload;
constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; privateExp: string; hashF: THashFunction;
hashSB: Integer; outputFormat: TConvertType; uni: TUnicode; CT: Boolean);
reintroduce; overload;
constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; privateExp: string; hashF: THashFunction;
hashSB: Integer; outputFormat: TConvertType; uni: TUnicode;
encT: TRSAEncType; CT: Boolean); reintroduce; overload;
constructor Create(keyLength: TRSAKeyLength; modulus: string;
publicExp: string; privateExp: string; hashF: THashFunction;
hashSB: Integer; outputFormat: TConvertType; uni: TUnicode;
signT: TRSASignType; CT: Boolean); reintroduce; overload;
Destructor Destroy; override;
procedure GenerateKeys;
function Encrypt(m: string): string;
function Decrypt(m: string): string;
function Sign(m: string): string;
function Verify(m: string; s: string): Integer;
function SignFile(filePath: string): string;
function VerifySignatureFile(filePath, s: string): Integer;
procedure FromOpenSSLCert(filePath: string);
procedure FromOpenSSLPublicKey(filePath: string);
procedure FromOpenSSLPrivateKey(filePath: string);
12
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
var
rsa: TRSAEncSign;
cipher: string;
begin
rsa:= TRSAEncSign.Create;
rsa.KeyLength:= kl2048;
rsa.OutputFormat:= base64;
rsa.GenerateKeys;
14
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
rsa.Unicode := noUni;
rsa.encType := oaep;
cipher:= rsa.Encrypt('test');
rsa.Free;
end;
var
rsa: TRSAEncSign;
signature: string;
begin
rsa:= TRSAEncSign.Create;
rsa.KeyLength:= kl2048;
rsa.OutputFormat:= base64;
rsa.GenerateKeys;
rsa.Unicode := yesUni;
rsa.hashFunction := hsha2;
rsa.hashSizeBits := 256;
rsa.signType := pss;
signature:= rsa.Sign('test');
rsa.Free;
end;
15
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
TECCType = (cc25519,cc511187);
TNaCl = (naclno, naclyes);
TECCEncSign = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(AType: TECCType; PublicKey: string; NaCl: TNaCl;
outputFormat: TConvertType; uni: TUnicode); overload;
Constructor Create(AType: TECCType; PublicKey: string; PrivateKey: string;
NaCl: TNaCl; outputFormat: TConvertType; uni: TUnicode); overload;
Destructor Destroy; override;
procedure GenerateKeys;
function Encrypt(m: string): string;
function Decrypt(m: string): string;
function Sign(m: string): string;
function Verify(m: string; s: string): integer;
function SignFile(filePath: string): string;
function VerifySignatureFile(filePath, s: string): Integer;
published
property PublicKey: string read FPublicKey write SetPublicKey;
property PrivateKey: string read FPrivateKey write SetPrivateKey;
property ECCType: TECCType read FECCType write SetType default cc25519;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property NaCl: TNaCl read FNaCl write FNaCl default NaClno;
property Unicode: TUnicode read FUni write FUni default yesUni;
end;
var
ecc: TECCEncSign;
cipher: string;
begin
ecc:= TECCEncSign.Create;
ecc.ECCType:= cc25519;
ecc.OutputFormat:= base64;
ecc.Unicode:= noUni;
ecc.NaCl := naclno;
ecc.GenerateKeys();
cipher:= ecc.Encrypt('test');
ecc.Free;
end;
var
ecc: TECCEncSign;
signature: string;
begin
ecc:= TECCEncSign.Create;
ecc.ECCType:= cc25519;
ecc.OutputFormat:= base64;
ecc.Unicode:= yesUni;
ecc.NaCl := naclno;
17
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
ecc.GenerateKeys();
signature:= ecc.Sign('test');
ecc.Free;
end;
18
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
SALSA
Salsa20 is a stream encryption algorithm proposed by Daniel Bernstein.
The SALSA class is:
TSalsaEncryption = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(keyLength: TSalsaKeyLength; key: string;
outputFormat: TConvertType; uni: TUnicode); overload;
Destructor Destroy; override;
function Encrypt(s: string): string;
function Decrypt(s: string): string;
procedure EncryptFile(s, o: string);
procedure DecryptFile(s, o: string);
procedure EncryptStream(s: TStream; var o: TStream);
procedure DecryptStream(s: TStream; var o: TStream);
published
property key: string read FKey write SetKey;
property keyLength: TSalsaKeyLength read FKeyLength write SetKeyLength
default skl128;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
19
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
var
salsa: TSalsaEncryption;
cipher: string;
begin
salsa:= TSalsaEncryption.Create;
salsa.KeyLength:= skl128;
salsa.Key:= '0123456789012345';
salsa.Unicode := yesUni;
salsa.OutputFormat:= hexa;
cipher:= salsa.Encrypt('test');
salsa.Free;
end;
20
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
SHA-2
SHA-2 (Secure Hash Algorithm) is a family of hash functions that have been designed by the National
Security Agency (NSA) of the USA, on the model of the now deprecated SHA-1 and SHA-0 functions. The
algorithms of the SHA-2 family, SHA-256, SHA-384 and SHA-512 are described and published along with
SHA-1 in the FIPS 180-2 (Secure Hash Standard). In this library, only SHA-256 and SHA-512 have been
implemented.
SHA-2 is described in the FIPS PUB 180-4.
The SHA2 class is:
TSHA2Hash = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(hashSizeBits: Integer; outputFormat: TConvertType;
uni: TUnicode); overload;
function Hash(s: string): string;
function HashFile(s: string): string;
function HashStream(s: TStream): string;
function HMAC(s, k: string): string;
function VerifyHMAC(s, k, h: string): Integer;
published
property hashSizeBits: Integer read FHashSizeBits write SetHashSizeBits
default 256;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
21
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer has Unicode characters
• property Progress: Integer read FProgress write SetProgress; to indicate
progress during hashing of a stream
• property OnChange: TNotifyEvent write FOnChange; to indicate that the progress
changes
var
sha2: TSHA2Hash;
hash: string;
begin
sha2:= TSHA2Hash.Create;
sha2.HashSizeBits:= 256;
sha2.OutputFormat:= hexa;
sha2.Unicode:= noUni;
hash:= sha2.Hash('test');
sha2.Free;
end;
var
sha2: TSHA2Hash;
hash: string;
k: string;
begin
sha2:= TSHA2Hash.Create;
sha2.HashSizeBits:= 256;
sha2.OutputFormat:= hexa;
sha2.Unicode := yesUni;
k:= '0123456789012345';
hash:= sha2.HMAC('test', k);
sha2.Free;
end;
22
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
SHA-3
SHA-3 comes from the NIST hash function competition which elected the algorithm Keccak on October 2,
2012. It is not intended to replace SHA-2 but to provide an alternative following the possibilities of attacks
on the deprecated standards MD5, SHA-0 and SHA-1. This library allows hashing with the SHA-3 standard
algorithm but also with the SHA-3 XOF (Extendable-Output Function) algorithm which allows to have a
variable length output. SHA-3 is described in the FIPS PUB 202. This library includes the SHA3 Derived
functions cSHAKE, KMAC and TupleHash, described in NIST Special Publication (SP) 800-185.
cSHAKE allows a user to add a salt to the hashed output. KMAC provides pseudorandom function and keyed
hash function with variable-length outputs. And TupleHash provides function that hashes tuples of input
strings correctly and unambiguously.
The SHA3 class is:
TSHA3Hash = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(hashSizeBits: Integer; outputFormat: TConvertType;
uni: TUnicode); overload;
Constructor Create(hashSizeBits: Integer; outputFormat: TConvertType;
uni: TUnicode; version: Integer); overload;
function Hash(s: string): string;
function HashFile(s: string): string;
function HashStream(s: TStream): string;
function cSHAKEHash(s, salt: string): string;
function KMACHash(k, s, salt: string): string;
function TupleHash(s: array of string; salt: string): string;
function HMAC(s, k: string): string;
function VerifyHMAC(s, k, h: string): Integer;
published
property hashSizeBits: Integer read FHashSizeBits write SetHashSizeBits
default 256;
property version: Integer read FVersion write SetVersion default 256;
property AType: TSHA3Type read FType write SetType default tsha;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
var
sha3: TSHA3Hash;
hash: string;
begin
sha3:= TSHA3Hash.Create;
sha3.AType:= txof;
sha3.HashSizeBits:= 1024;
sha3.Version:= 512;
sha3.OutputFormat:= base64;
sha3.Unicode := yesUni;
hash:= sha3.Hash('test');
sha3.Free;
end;
var
24
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
sha3: TSHA3Hash;
hash: string;
k: string;
begin
sha3:= TSHA3Hash.Create;
sha3.AType:= tsha;
sha3.HashSizeBits:= 256;
sha3.OutputFormat:= hexa;
sha3.Unicode := yesUni;
k:= '0123456789012345';
hash:= sha3.HMAC('test', k);
sha3.Free;
end;
25
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
SPECK
Speck is a family of lightweight block ciphers publicly released by the National Security Agency (NSA) in
June 2013. Speck has been optimized for performance in software implementations. Speck is an add-
rotate-xor (ARX) cipher.
Speck supports a variety of block and key sizes. A block is always two words, but the words may be 16, 24,
32, 48 or 64 bits in size. The corresponding key is 2, 3 or 4 words. The round function consists in two
rotations, adding the right word to the left word, xoring the key into the left word, then and xoring the
left word to the right word.
To encrypt a message with many blocks, we will use the following modes (like AES):
• ECB (Electronic Code Book)
• CBC (Cipher Block Chaining)
• OFB (Output Feedback)
TSPECKEncryption = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(wordSizeBits: TSPECKWordSizeBits;
keySizeWords: TSPECKKeySizeWords; key: string; AType: TSPECKType;
OutputFormat: TConvertType; paddingMode: TSPECKPaddingMode;
uni: TUnicode); overload;
Constructor Create(wordSizeBits: TSPECKWordSizeBits;
keySizeWords: TSPECKKeySizeWords; key: string; AType: TSPECKType;
OutputFormat: TConvertType; paddingMode: TSPECKPaddingMode; uni: TUnicode;
IV: string); overload;
Destructor Destroy; override;
function Encrypt(s: string): string;
function Decrypt(s: string): string;
procedure EncryptFileW(s, o: string);
procedure DecryptFileW(s, o: string);
procedure EncryptStream(s: TStream; var o: TStream);
procedure DecryptStream(s: TStream; var o: TStream);
published
property key: string read FKey write SetKey;
property wordSizeBits: TSPECKWordSizeBits read FWordSizeBits
write SetWordSizeBits default wsb32;
property keySizeWords: TSPECKKeySizeWords read FKeySizeWords
write SetKeySizeWords default ksw4;
property AType: TSPECKType read FType write FType default stcbc;
property OutputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property IVMode: TSPECKIVMode read FIVMode write FIVMode default rand;
property IV: string read FIV write SetIV;
property paddingMode: TSPECKPaddingMode read FPaddingMode
write FPaddingMode default PKCS7;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
26
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
27
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
the clear text must be a multiple of FwordSizeBits/4 bytes, and no padding is added to the
clear text.
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer or the file name has Unicode characters
• property Progress: Integer read FProgress write SetProgress; to indicate
progress during encryption / decryption of a stream
• property OnChange: TNotifyEvent write FOnChange; to indicate that the progress
changes
var
speck: TSPECKEncryption;
cipher: string;
begin
speck:= TSPECKEncryption.Create;
speck.AType:= stCBC;
speck.WordSizeBits:= wsb32;
speck.KeySizeWords:= ksw4;
speck.Key:= '0123456789012345';
speck.OutputFormat:= hexa;
speck.Unicode := noUni;
speck.PaddingMode:= TSPECKPaddingMode.PKCS7;
speck.IVMode:= TSPECKIVMode.rand;
cipher:= speck.Encrypt('test');
speck.Free;
end;
28
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
PBKDF2
PBKDF2 (Password-Based Key Derivation Function 2) is a key derivation function that is part of RSA
Laboratories' Public-Key Cryptography Standards (PKCS) series, specifically PKCS \#5 v2.0, also published
as Internet Engineering Task Force's RFC 2898. It replaces an earlier standard, PBKDF1, which could only
produce derived keys up to 160 bits long.
PBKDF2 applies a pseudorandom function, such as a cryptographic hash, cipher, or HMAC, to the input
password or passphrase along with a salt value and repeats the process many times to produce a derived
key, which can then be used as a cryptographic key in subsequent operations. The added computational
work makes password cracking much more difficult, and is known as key stretching.
It is described in NIST Special Publication 800-132.
TPBKDF2KeyDerivation = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(outputSizeBits: Integer; salt: string; counter: Integer;
outputFormat: TConvertType; uni: TUnicode, hashF: THashFunction;
hashSB: Integer); overload;
function GenerateKey(s: string): string;
published
property outputSizeBits: Integer read FOutputSizeBits
write SetOutputSizeBits default 128;
property Salt: string read FSalt write FSalt;
property counter: Integer read FCounter write FCounter default 10000;
property hashFunction: THashFunction read FHashFunction write FHashFunction
default hsha2;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property hashSizeBits: Integer read FHashSizeBits write SetHashSizeBits
default 256;
property Unicode: TUnicode read FUni write FUni default yesUni;
end;
var
pbkdf2: TPBKDF2KeyDerivation;
output: string;
begin
pbkdf2:= TPBKDF2KeyDerivation.Create;
pbkdf2.OutputSizeBits:= 1024;
pbkdf2.Counter:= 10000;
pbkdf2.Unicode:= yesUni;
pbkdf2.OutputFormat:= base64;
pbkdf2.Salt:= '012345678901234567890123456789012345678901234567890123456789';
output:= pbkdf2.GenerateKey('test123');
pbkdf2.Free;
end;
30
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Blake2
BLAKE2 is a cryptographic hash function faster than MD5, SHA-1, SHA-2, and SHA-3, yet is at least as
secure as the latest standard SHA-3. BLAKE2 had been adopted by many projects due to its high speed,
security, and simplicity. BLAKE2 is specified in RFC 7693. We have chosen to implement BLAKE2b that is
optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes.
TBlake2BHash = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(hashSizeBytes: Integer; key: string;
outputFormat: TConvertType; uni: TUnicode); overload;
function Hash(s: string): string;
function HashFile(s: string): string;
function HashStream(s: TStream): string;
published
property hashSizeBytes: Integer read FHashSizeBytes write SetHashSizeBytes
default 16;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property key: String read FKey write SetKey;
property Unicode: TUnicode read FUni write FUni default yesUni;
property Progress: Integer read FProgress write SetProgress;
property OnChange: TNotifyEvent write FOnChange;
end;
31
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
output:= blake2B.Hash('ABCDEFGH');
finally
blake2B.Free;
end;
end;
32
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
RIPEMD-160
RIPEMD (RACE Integrity Primitives Evaluation Message Digest) is a family of cryptographic hash functions
developed in Leuven, Belgium, by Hans Dobbertin, Antoon Bosselaers and Bart Preneel at the COSIC
research group at the Katholieke Universiteit Leuven, and first published in 1996. RIPEMD was based upon
the design principles used in MD4, and is similar in performance to the more popular SHA-1 (NOTE: both
MD4 and SHA-1 are deprecated).
RIPEMD-160 is an improved, 160-bit version of the original RIPEMD, and the most common version in the
family.
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer has Unicode characters
• property Progress: Integer read FProgress write SetProgress; to indicate
progress during hashing of a stream
33
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
34
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Argon2
Argon2 is a key derivation function that was selected as the winner of the Password Hashing Competition
(PHC) in July 2015. It was designed by Alex Biryukov, Daniel Dinu, and Dmitry Khovratovich from the
University of Luxembourg. Argon2 provides two related versions:
• Argon2d maximizes resistance to GPU cracking attacks.
• Argon2i is optimized to resist side-channel attacks.
TArgon2KeyDerivation = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(outputSizeBytes: Integer; salt: string; counter: Integer;
outputFormat: TConvertType; memory: Integer; uni: TUnicode); overload;
function GenerateKey(s: string): string;
published
property outputSizeBytes: Integer read FOutputSizeBytes
write SetOutputSizeBytes default 16;
property StringSalt: string read FStringSalt write SetStringSalt;
property counter: Integer read FCounter write SetCounter default 10;
property outputFormat: TConvertType read FOutputFormat write FOutputFormat
default hexa;
property memory: Integer read FMemory write SetMemory default 16;
property Unicode: TUnicode read FUni write FUni default yesUni;
end;
• property Unicode: TUnicode read FUni write FUni; to indicate whether the input
buffer or the file name has Unicode characters
output := argon2.GenerateKey('toto23');
finally
argon2.Free;
end;
end;
36
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Converter class
To display the output binary data of the library functions on a screen, we need to convert them in a
printable format. We have chosen four formats:
• Hexadecimal format: consists in replacing each 4-bit block by a symbol in the list 0, …, 9, A, …, F.
• Base64 format: consists in replacing each 6-bit block by a symbol in the list a, …, z, A, …, Z, 0, …,
9, + and / (the symbol = is used in complement when the length of the data is not a multiple of 3
bytes).
• Base64url format: the same as Base64 with – in place of + and _ in place of /, to be compatible
with URLs.
• Base32 format: consists in replacing each 5-bit block by a symbol in the list A, …, Z, 2, …, 7 (the
symbol = is used in complement when the length of the data is not a multiple of 8 bytes).
We add the raw format to have an output format compatible with the input of some functions.
TConvert = class(TTMSCryptBase)
public
Constructor Create(AOwner: TComponent); overload; override;
Constructor Create; overload;
Constructor Create(AType: TConvertType); overload;
{$IF (defined(MSWINDOWS) or defined(MACOS)) and (not defined(IOS))}
function CharToFormat(charstring: PAnsiChar; charlen: Integer): string;
function FormatToChar(str: string): PAnsiChar;
function UnicodeToPAnsiChar(str: string): PAnsiChar;
function PAnsiCharFromUnicodeLength(str: string): Integer;
{$ELSE}
function CharToFormat(charstring: PByte; charlen: Integer): string;
function FormatToChar(str: string): PByte;
{$IFEND}
function TestUnicode(str: string): Integer;
function StringToUnicode(str: string): string;
function StringToFormat(charstring: string): string;
function FormatToString(str: string): string;
function OutputFormatLength(charlen: Integer): Integer;
function CharLength(charstring: string): Integer;
function Base64ToHexa(base64String: string): string;
function HexaToBase64(hexaString: string): string;
function Base64ToBase64url(inString: string): string;
function Base64urlToBase64(inString: string): string;
function Base64urlToHexa(inString: string): string;
function HexaToBase64url(inString: string): string;
function Base32ToHexa(base32String: string): string;
function HexaToBase32(hexaString: string): string;
function Base32ToBase64url(inString: string): string;
function Base64urlToBase32(inString: string): string;
function Base32ToBase64(inString: string): string;
function Base64ToBase32(inString: string): string;
function KeyRSAOpenSSLToKeyTRSAEncSign(strKey: string): string;
function KeyTRSAEncSignToKeyRSAOpenSSL(strKey: string): string;
37
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
published
property AType: TConvertType read FType write FType default hexa;
end;
38
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
39
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
aes:= TAESEncryption.Create;
conv:= TConvert.Create;
try
aes.AType := atcbc;
aes.KeyLength := kl128;
aes.OutputFormat := hexa;
aes.Key := conv.TBytesToString(b);
aes.IVMode := TIVMode.rand;
aes.PaddingMode := TPaddingMode.PKCS7;
aes.Unicode := yesUni;
str := AES.Encrypt('test');
Finally
aes.Free;
conv.Free;
end;
end;
40
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
X509 certificates
X.509 is a standard that defines the format of public key certificates. X.509 certificates are used in
many Internet protocols, including TLS/SSL, which is the basis for HTTPS, the secure protocol for
browsing the web. They are also used in offline applications, like electronic signatures. An X.509
certificate contains a public key and an identity (a hostname, or an organization, or an individual),
and is either signed by a certificate authority or self-signed. When a certificate is signed by a trusted
certificate authority, or validated by other means, someone holding that certificate can rely on the
public key it contains to establish secure communications with another party, or validate documents
digitally signed by the corresponding private key.
In the library, you can decode an X509 certificate to display all the fields and verify the signature if
the algorithm is supported. You can also generate a self-signed certificate (only on MacOS and
Windows platform). The demo on Windows of these functionalities is here:
https://www.tmssoftware.com/site/freetools.asp
TX509Certificate = class(TTMSCryptBase)
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create; reintroduce; overload;
constructor Create(RootCAPath: string); reintroduce; overload;
{$IF (defined(MSWINDOWS) or defined(MACOS)) and (not defined(IOS))}
procedure GenerateSelfSigned;
{$IFEND}
procedure Decode;
published
property KeyFilePath: string write FKeyFilePath;
property CrtFilePath: string read FCrtFilePath write FCrtFilePath;
property signatureAlgorithm: TSignAlgo read FSignatureAlgorithm
write setSignatureAlgorithm;
property countryName: string read FIssuerCountryName write SetCountryName;
property SubjectCountryName: string read FSubjectCountryName;
property stateName: string read FIssuerStateName write FIssuerStateName;
property SubjectStateName: string read FSubjectStateName;
property localityName: string read FIssuerLocalityName
write FIssuerLocalityName;
property SubjectLocalityName: string read FSubjectLocalityName;
property OrganizationName: string read FIssuerOrganizationName
write FIssuerOrganizationName;
property SubjectOrganizationName: string read FSubjectOrganizationName;
property OrganizationUnitName: string read FIssuerOrganizationUnitName
write FIssuerOrganizationUnitName;
property SubjectOrganizationUnitName: string
read FSubjectOrganizationUnitName;
property commonName: string read FIssuerCommonName write FIssuerCommonName;
property SubjectCommonName: string read FSubjectCommonName;
property AltName1: string read FAltName1 write FAltName1;
property AltName2: string read FAltName2 write FAltName2;
property AltName3: string read FAltName3 write FAltName3;
property AltName4: string read FAltName4 write FAltName4;
property AltName5: string read FAltName5 write FAltName5;
41
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
• procedure Decode; to decode the fields of a certificate and verify the signature
The properties are:
• property KeyFilePath: string write FKeyFilePath; to set the path to the private
key file
• property CrtFilePath: string read FCrtFilePath write FCrtFilePath; to read
and write the path to the certificate file
• property signatureAlgorithm: TSignAlgo read FSignatureAlgorithm
write setSignatureAlgorithm; to read and write the path to the certificate file
• property countryName: string read FIssuerCountryName write SetCountryName;
to read and write the issuer country name field
• property SubjectCountryName: string read FSubjectCountryName; to read and
write the subject country name field
• property stateName: string read FIssuerStateName write FIssuerStateName; to
read and write the issuer state name field
• property SubjectStateName: string read FSubjectStateName; to read and write
the subject state name field
• property localityName: string read FIssuerLocalityName write
FIssuerLocalityName; to read and write the issuer locality name field
• property SubjectLocalityName: string read FSubjectLocalityName; to read and
write the subject locality name field
42
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
43
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
X509Certificate1 := TX509Certificate.Create;
try
X509Certificate1.RootCAPath := '.\\RootCA\\';
X509Certificate1.KeyFilePath := '.\\mykey.key';
X509Certificate1.CrtFilePath := '.\\mycert.crt';
X509Certificate1.signatureAlgorithm := TSignAlgo.sa_sha256rsa
X509Certificate1.BitSizeEncryptionAlgorithm := 2048
X509Certificate1.countryName := 'France';
X509Certificate1.stateName := 'Nouvelle-Aquitaine';
X509Certificate1.localityName := 'Bordeaux';
X509Certificate1.OrganizationName := 'Cyberens';
X509Certificate1.commonName := 'Cyberens certificate;
X509Certificate1.GenerateSelfSigned;
Finally
X509Certificate1.Free;
end;
end;
44
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
All X509 Certificate generation and parsing functions are located in the X509Obj.pas file.
45
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Random generators
To generate random integers or random buffers, you can use the following functions (in MiscObj.pas).
On Windows or OSX:
• function RandomBuffer(len: Integer; MyBuffer: PAnsiChar): Integer;
• function RandomUBuffer(len: Integer; MyBuffer: PAnsiChar): Integer;
• function RandomInt: Integer;
• function RandomUInt: Integer;
On iOS or Android:
• function RandomBuffer(len: Integer; MyBuffer: PByte): Integer;
• function RandomUBuffer(len: Integer; MyBuffer: PByte): Integer;
• function RandomInt: Integer;
• function RandomUInt: Integer;
RandomBuffer and RandomUBuffer fill the buffer MyBuffer with len random characters (and return an
error if it fails). On Windows, the functions use the same algorithm, but in the other targets, they use
/dev/random for RandomBuffer and /dev/urandom for RandomUBuffer. So, if you want to generate some
cryptographic keys, preferably use RandomBuffer, and use RandomUBuffer for salt, IV, or other data
which are not keys. We recommend the same for RandomInt and RandomUInt.
46
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
TEncryptedIniFile = class(TMemInifile)
private
FFileName: string;
FEncoding: TEncoding;
FKey: string;
FOnDecryptError: TNotifyEvent;
procedure LoadValues;
public
constructor Create(const FileName: string; const Key: string); overload;
constructor Create(const FileName: string; const Encoding: TEncoding;
CaseSensitive: Boolean); overload; override;
procedure UpdateFile; override;
published
property OnDecryptError: TNotifyEvent read FOnDecryptError
write FOnDecryptError;
end;
A sample to use this class to read data back from such encrypted file is here:
const
aeskey = 'anijd54dee1c3e87e1de1d6e4d4e1de3';
var
mi: TEncryptedIniFile;
begin
try
mi := TEncryptedIniFile.Create('.settings.cfg', aeskey);
try
FTPUserNameEdit.Text := mi.ReadString('FTP','USER','');
FTPPasswordNameEdit.Text := mi.ReadString('FTP','PWD','');
FTPPortSpin.Value := mi.ReadInteger('FTP','PORT',21);
mi.WriteDateTime('SETTINGS','LASTUSE',Now);
mi.UpdateFile;
finally
mi.Free;
end;
except
ShowMessage('Error in encrypted file. Someone tampered with the file?');
end;
end;
47
TMS SOFTWARE
TMS Cryptography Pack
DEVELOPERS GUIDE
Troubleshooting
There several potential issues when running the various demos included in TMS Cryptography Pack.
RandomDLL.DLL
It is necessary to copy this DLL in the appropriate folder to run the Windows 64 demo and to use
the library in Windows 64 applications.
Copy RandomDLL.dll from the Win64 directory of TMS Cryptography Pack:
- to C:\Windows\SysWOW64 if you are running 32 bit Windows
- or to C:\Windows\System32 if you are running 64 bit Windows
libTMSCPLib.a
Some error messages contain “… libTMSCPLib.a not found”. In this case, the search path for the
libraries needs to be updated. Go to Project->Options, then Search Path and click on “…” to update
your list with the directory location of libTMSCPLib.a (for instance “FULL TMS INSTALLATION
PATH\iOSDevice64”).
C++ demo
To use the C++ demo, you need to add the .a file to the project for Android or iOS target.
iOS Simulator
The TMS Cryptography Pack does not support the iOS Simulator because we generate .a files from
C code and we cannot generate .a file for iOS Simulator target with RAD Studio.
48