Cipher

Fingerprints (hashes), HMAC, Base64, AES, key derivation, password hashes and secure random numbers.

Everything here is written in x itself (runtime/runtime.pb), with no library to link. Results were checked against PureBasic 6.50 and against Python's hashlib, hmac, cryptography, bcrypt and passlib.

Constants

Constant Value
#PB_Cipher_MD5 1 MD5 (128 bits)
#PB_Cipher_CRC32 2 CRC32 (32 bits)
#PB_Cipher_SHA1 3 SHA-1 (160 bits)
#PB_Cipher_SHA2 4 SHA-2: 224, 256 (the default), 384 or 512 bits
#PB_Cipher_SHA3 5 SHA-3: 224, 256 (the default), 384 or 512 bits
#PB_Cipher_HMAC $10000 added to one of the above: an HMAC with a key
#PB_Cipher_NoPadding 32 Base64 without = at the end
#PB_Cipher_URL 16 Base64 with - and _ instead of + and /
#PB_Cipher_CBC 4 AES: cipher block chaining (the default)
#PB_Cipher_ECB 8 AES: each block on its own (weak; avoid)
#PB_Cipher_Encode 2 StartAESCipher: encrypt
#PB_Cipher_Decode 1 StartAESCipher: decrypt
#PB_Cipher_CTR 16 AES: counter mode, any size (x addition)

Fingerprints

UseMD5Fingerprint, UseCRC32Fingerprint, UseSHA1Fingerprint, UseSHA2Fingerprint, UseSHA3Fingerprint ✅

UseMD5Fingerprint()

In PureBasic these register an algorithm. In x the algorithms are always there, so these do nothing, but programs may call them.

Fingerprint, StringFingerprint, FileFingerprint ✅

Result$ = Fingerprint(*Buffer, Size, Plugin [, Bits [, HmacKey$ [, HmacKeyFormat]]])
Result$ = StringFingerprint(String$, Plugin [, Bits [, Format [, HmacKey$ [, HmacKeyFormat]]]])
Result$ = FileFingerprint(Filename$, Plugin [, Bits [, Offset [, Length [, HmacKey$ [, HmacKeyFormat]]]]])

Returns the fingerprint of the memory, the string or the file as lower-case hexadecimal (CRC32 as 8 digits). Bits only matters for SHA-2 and SHA-3. A string is turned into bytes as Format says: #PB_UTF8 (the default), #PB_Ascii or #PB_Unicode. FileFingerprint returns "" if the file can't be read.

With #PB_Cipher_HMAC added to the plugin, the result is the HMAC of the data with the key HmacKey$, which is turned into bytes as HmacKeyFormat says (#PB_UTF8 by default).

OpenConsole()
UseMD5Fingerprint() : UseSHA2Fingerprint() : UseCRC32Fingerprint()
PrintN(StringFingerprint("abc", #PB_Cipher_MD5))
PrintN(StringFingerprint("abc", #PB_Cipher_SHA2))
PrintN(StringFingerprint("abc", #PB_Cipher_SHA2, 512))
PrintN(StringFingerprint("abc", #PB_Cipher_CRC32))
PrintN(StringFingerprint("message", #PB_Cipher_SHA2 | #PB_Cipher_HMAC, 256, #PB_UTF8, "secret key"))

Output:

900150983cd24fb0d6963f7d28e17f72
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
352441c2
c431e4857a6b817f9eeaab86b00f78e210808e5a2b2ae1e5bb6befb213608eed

StartFingerprint, AddFingerprintBuffer, FinishFingerprint, IsFingerprint ✅

Result = StartFingerprint(#Fingerprint, Plugin [, Bits [, HmacKey$ [, HmacKeyFormat]]])
Result = AddFingerprintBuffer(#Fingerprint, *Buffer, Size)
Result$ = FinishFingerprint(#Fingerprint)
Result = IsFingerprint(#Fingerprint)

A fingerprint of data that comes in pieces. The result is the same as Fingerprint of all the pieces together. FinishFingerprint returns it and frees the #Fingerprint.

Base64

Base64Encoder, Base64Decoder ✅

Result$ = Base64Encoder(*InputBuffer, InputSize [, Flags])
Result = Base64Decoder(Input$, *OutputBuffer, OutputSize)

Base64Encoder returns the data as Base64 text. Flags can combine #PB_Cipher_NoPadding and #PB_Cipher_URL.

Base64Decoder reads either alphabet, with or without padding, and skips spaces and line breaks. It returns the number of bytes written (at most OutputSize), or 0 if the text has any other character.

Base64EncoderBuffer, Base64DecoderBuffer ✅

Result = Base64EncoderBuffer(*InputBuffer, InputSize, *OutputBuffer, OutputSize [, Flags])
Result = Base64DecoderBuffer(*InputBuffer, InputSize, *OutputBuffer, OutputSize)

The same, with the Base64 text as ASCII bytes in memory. Both return the number of bytes written. The encoder returns 0 if the output doesn't fit.

StringBase64Encoder, StringBase64Decoder (x additions)

Result$ = StringBase64Encoder(String$ [, Flags [, Format]])
Result$ = StringBase64Decoder(Base64$ [, Format])

Base64 of a string's text and back, without handling memory. Format is how the text is turned into bytes: #PB_UTF8 (the default), #PB_Ascii or #PB_Unicode. A program's own procedures with these names are used instead.

OpenConsole()
e$ = StringBase64Encoder("Hello, world!")
PrintN(e$)
PrintN(StringBase64Decoder(e$))
PrintN(StringBase64Encoder("??>", #PB_Cipher_URL | #PB_Cipher_NoPadding))
*m = AllocateMemory(16)
PrintN(Str(Base64Decoder("SGk=", *m, 16)) + " " + PeekS(*m, 2, #PB_Ascii) + " " + Str(Base64Decoder("SG!k=", *m, 16)))

Output:

SGVsbG8sIHdvcmxkIQ==
Hello, world!
Pz8-
2 Hi 0

AES

AESEncoder, AESDecoder ✅

Result = AESEncoder(*Input, *Output, Size, *Key, Bits, *InitializationVector [, Mode])
Result = AESDecoder(*Input, *Output, Size, *Key, Bits, *InitializationVector [, Mode])

Encrypts or decrypts Size bytes, which must be at least 16 (any size with #PB_Cipher_CTR), into a different buffer. The output is as long as the input.

Bits is 128, 192 or 256, the length of the key at *Key (16, 24 or 32 bytes). Mode is #PB_Cipher_CBC (the default), which needs a 16-byte initialization vector, or #PB_Cipher_ECB, which doesn't.

When Size isn't a multiple of 16, the last part is handled by ciphertext stealing, as PureBasic does. In CBC this is the CS3 variant. Both return Size, or 0 if the arguments aren't valid.

OpenConsole()
*key = AllocateMemory(32) : *iv = AllocateMemory(16)
For i = 0 To 31 : PokeA(*key + i, i) : Next
For i = 0 To 15 : PokeA(*iv + i, 100 + i) : Next
text$ = "Twenty bytes: here."
*in = Ascii(text$) : *out = AllocateMemory(64) : *back = AllocateMemory(64)
n = Len(text$)
AESEncoder(*in, *out, n, *key, 256, *iv)
AESDecoder(*out, *back, n, *key, 256, *iv)
PrintN(Str(n) + " bytes: " + PeekS(*back, n, #PB_Ascii) + ", " + Str(CompareMemory(*in, *out, n)))

Output:

19 bytes: Twenty bytes: here., 0

Counter mode: #PB_Cipher_CTR (x addition)

With #PB_Cipher_CTR as the mode, AES makes a stream of key bytes by enciphering a counter, and XORs the data with it. So:

  • any size works, even 1 byte, and the output is as long as the input;
  • encrypting and decrypting are the same operation;
  • input and output may be the same buffer.

The initialization vector is the counter's start (16 bytes), counted up as a 128-bit big-endian number (NIST SP 800-38A). It must be different for every message sent with the same key: use CryptRandomData for it, and send it along with the message. In a StartAESCipher stream, the pieces can have any size.

OpenConsole()
*key = AllocateMemory(16) : *iv = AllocateMemory(16)
For i = 0 To 15 : PokeA(*key + i, i * 7) : Next
CryptRandomData(*iv, 16)
*msg = Ascii("Hi!")
*enc = AllocateMemory(3) : *dec = AllocateMemory(3)
PrintN(Str(AESEncoder(*msg, *enc, 3, *key, 128, *iv, #PB_Cipher_CTR)))
AESDecoder(*enc, *dec, 3, *key, 128, *iv, #PB_Cipher_CTR)
PrintN(PeekS(*dec, 3, #PB_Ascii))

Output:

3
Hi!

StartAESCipher, AddCipherBuffer, FinishCipher, IsCipher ✅

Result = StartAESCipher(#Cipher, *Key, Bits, *InitializationVector, Mode)
Result = AddCipherBuffer(#Cipher, *Input, *Output, Size)
FinishCipher(#Cipher)
Result = IsCipher(#Cipher)

Encryption or decryption of data that comes in pieces. Mode combines #PB_Cipher_Encode or #PB_Cipher_Decode with #PB_Cipher_CBC or #PB_Cipher_ECB. Each AddCipherBuffer takes at least 16 bytes, and only the last should have a size that isn't a multiple of 16. The result is the same as one AESEncoder on all the pieces together.

Keys and passwords

DeriveCipherKey ✅

Result = DeriveCipherKey(Password$, Salt$, Iterations, *Key, KeyBits, Plugin [, PluginBits])

Makes a key of KeyBits bits from a password, with PBKDF2 (RFC 8018) and the HMAC of Plugin (MD5, SHA-1, SHA-2 or SHA-3). The password and salt are taken as UTF-8. Returns non-zero, or 0 if the plugin isn't valid.

CreatePasswordHash, VerifyPasswordHash ✅

Hash$ = CreatePasswordHash(Password$ [, WorkFactor])
Result = VerifyPasswordHash(Password$, Hash$)

CreatePasswordHash returns a bcrypt hash ($2b$, 60 characters) with a random salt, so the same password gives a different hash each time. WorkFactor is 4 to 31 (10 by default), and each step doubles the time; at 10 a hash takes about 0.1 s.

VerifyPasswordHash returns 1 if the password matches a bcrypt hash ($2a$, $2b$ or $2y$). The password is taken as UTF-8; only its first 72 bytes count.

OpenConsole()
PrintN(Str(VerifyPasswordHash("U*U", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW")))
h$ = CreatePasswordHash("secret", 6)
PrintN(Left(h$, 7) + " " + Str(Len(h$)) + " " + Str(VerifyPasswordHash("secret", h$)) + Str(VerifyPasswordHash("Secret", h$)))
*key = AllocateMemory(32)
DeriveCipherKey("password", "salt", 1000, *key, 256, #PB_Cipher_SHA2)
PrintN(Hex(PeekA(*key)) + Hex(PeekA(*key + 1)) + "...")

Output:

1
$2b$06$ 60 10
632C...

DESFingerprint ✅ (deprecated in PureBasic)

Result$ = DESFingerprint(Password$, Key$)

The old Unix crypt(): DES with a 2-character salt Key$, and only the first 8 characters of the password counting. DESFingerprint("password", "ab") is abJnggxhB/yWI. It is not safe for new programs; use CreatePasswordHash.

Secure random numbers

OpenCryptRandom, CryptRandom, CryptRandomData, CloseCryptRandom ✅

Result = OpenCryptRandom()
Result = CryptRandom(Maximum)
Result = CryptRandomData(*Buffer, Length)
CloseCryptRandom()

Random numbers from the system's generator (BCryptGenRandom on Windows, getrandom on Linux), fit for keys, salts and initialization vectors. CryptRandom returns a number from 0 to Maximum, each equally likely. CryptRandomData fills a buffer and returns non-zero. In x the generator needs no opening, so OpenCryptRandom just returns 1.