<!--
meta-author: David Ireland, DI Management Services Pty Limited, Australia, www.di-mgt.com.au www.cryptosys.net
meta-content-style-type: text/css
meta-content-type: text/html; charset=UTF-8
meta-copyright: Copyright (C) 2001-25 DI Management Services Pty Limited t/a CryptoSys ABN 78 083 210 584 All Rights Reserved
meta-date: 2024-01-07T07:42:07Z
meta-description: CryptoSys API cryptographic functions for Visual Basic, VBA, `VB.NET`, C, C++, C# and ASP
meta-keywords: cryptography, computer security, data security, block cipher, encryption,
		API, visual basic, VBA, VB6, `VB.NET`, Visual Studio, C programming language, C++, C#, C sharp, Python,
		ASP, VBScript, COM, DLL, developer tool,
		cryptographic operations in visual basic,
		blowfish, DES, Data Encryption Standard, Triple DES, TDEA, DES-EDE3,
		AES, Advanced Encryption Standard, Rijndael block cipher, AES-GCM, Galois/Counter Mode, GCM,
		message digest, secure hash algorithm, hash function, one-way hash, sha-1, SHA-256, SHA-384, SHA-512, SHA-224, SHA-3, MD5, RIPEMD-160,
		Stream Cipher, Salsa20, ChaCha20, Poly1305, Authenticated Encryption With Additional Data, AEAD, AEAD_CHACHA20_POLY1305,
		secure random number generator, RNG, NIST SP800-90, key generator, nonces, Intel(R) DRNG,
		Message Authentication Codes, Keyed-Hashing for Message Authentication, HMAC, CMAC, OMAC1, GMAC, KMAC, key wrap,
		extendable-output function, XOF, SHAKE128, SHAKE256,
		ASCON-128, ASCON-128A, ASCON-HASH, ASCON-HASHA, ASCON-XOF, ASCON-XOFA,
		data compression, zlib, PC1, ARCFOUR, RC4, checksum, CRC-32,
		password-based key derivation, PBKDF2, SCRYPT,
		Block Cipher Modes of Operation, ECB, CBC, CFB, OFB, CTR, GCM
meta-viewport: width=device-width, initial-scale=1
title: CryptoSys API Manual v6.22.1a
-->

<a id="topofpage"></a>CryptoSysTM API Manual
============================================

[Function List](#functionlist)   
[X-refs](#xrefdotnet)   
[Method List](#dotnetsummary)   
[References](#refs)   
[Index](#index)   
[Error Codes](#errorcodes)   

Contents
--------

* [What is the CryptoSys API?](#WhatIs)
* [Introduction](#Introduction)
* [Getting Started](#gettingstarted)
* [Changes in this version](#changesinthis)
* [Changes in earlier versions](#changesearlier)
* [Conventions in this document](#Conventions)
* [Copyright Notice](#Copyright)
* [Background Basics](#Background)

    + [Block cipher algorithms](#blockcipher)
        + [Block Cipher Modes and Initialization Vectors](#blockciphermodes)
        + [Padding](#padding)
        + [Stream ciphers](#streamcipher)
        + [One-way message digest (hash) functions](#hashfunctions)
        + [Notes on SHA-3](#sha3notes)
        + [Message authentication code (MAC) functions](#macfunctions)
        + [The Poly1305 message authentication algorithm](#poly1305algorithm)
        + [KMAC: KECCAK Message Authentication Code](#kmac)
        + [XOF: eXtendable-Output Function](#xof)
        + [Authenticated Encryption with Additional Data (AEAD)](#aeadalgorithms)
        + [The cipher suite ASCON](#ciphersuiteascon)
        + [Data Compression in Cryptography](#compression)
* [Secure Random Number Generator](#rnginfo)

    + [RNG Mechanisms](#rngmechanisms)
        + [Intel(R) DRNG support](#inteldrng)
        + [Techniques to add known security strength to the RNG process](#rngtechniques)
        + [User-supplied entropy (seeds)](#rngentropy)
* [A caution about insecure default algorithms](#cautionwithdefaults)
* [Installation](#installation)

    + [Win64 (X64) Platform](#win64platform)
        + [Detecting Win32 or X64 platform](#detectingplatform)
* [Visual Basic or Visual Basic: VB6 vs `VB.NET`](#vb6vsvbdotnet)
* [VBA in 64-bit versions of Office](#vbain64bitoffice)
* [General Programming Issues](#generalprogramming)

    + [Storing and representing ciphertext](#storingciphertext)
        + [Converting strings to bytes and vice versa](#stringstobytes)
        + [Hexadecimal versus Bytes](#hexvsbytes)
        + [Return Values](#ReturnValues)
* [Using with Classic Visual Basic and VBA](#UsingWithVB)

    + [Pre-dimensioning for VB](#predimensioning)
        + [Zero-length byte arrays in VB6/VBA](#zerolengthbytearrays)
        + [Passing a reference to an empty byte array in VB6/VBA](#passemptybytearray)
        + [Other Issues For VB6/VBA Users](#vb6vbaotherissues)
        + [Notes on VBA wrapper functions](#notesonvbawrapperfunctions)
            - [Empty byte arrays](#emptybytearrays)
* [Using with ANSI C](#UsingWithC)

    + [Type Conversions](#typeconversions)
        + [Compiling with C](#compilingwithc)
        + [Using With Borland C++](#borlandc)
        + [Cautions for C/C++ Users](#cautionsforcusers)
        + [ANSI C users must add one to this value...](#cusersaddone)
* [Using with C++ (STL)](#UsingWithCpp)
* [Using with .NET: C# and `VB.NET`](#UsingWithDotNet)

    + [Combining bitwise options](#bitwiseoptions)
        + [Converting VB6 to `VB.NET`](#vb6tovbnet)
* [Using with COM/ASP](#UsingWithASP)
* ['Hello world' programs](#helloworld)
* [Common problems when encrypting](#commonproblems)
* [Specifying the algorithm and mode for generic block cipher functions](#cipheralgmode)
* [Padding schemes for block ciphers](#paddingschemes)
* [Valid key and block sizes for block cipher algorithms](#blockciphersizes)
* [Extensions to block cipher functions for files](#extensionsforfiles)
* [An interface for Authenticated Encryption with Associated Data (AEAD)](#aeadinterface)

    + [Correct sequence for AEAD incremental functions](#aeadsequence)
* [Filenames with 'International' characters](#filenamesinternational)
* [Security Issues](#SecurityIssues)
* [Self-Tests](#selftests)
* [Optional Registry Settings](#registrysettings)
* [Technical Details](#technicaldetails)
* [Compliance](#Compliance)
* [References](#refs)
* [VBA/C Function Summary](#vb6funcsummary)

    + [AEAD functions](#AEADbyCat)
        + [Advanced Encryption Standard (AES) functions](#AESbyCat)
        + [Block cipher functions](#CIPHERbyCat)
        + [Blowfish functions](#BLFbyCat)
        + [Conversion functions](#CNVbyCat)
        + [Cyclic Redundancy Check functions](#CRCbyCat)
        + [Data Encryption Standard (DES) functions](#DESbyCat)
        + [Message Digest Hash functions](#HASHbyCat)
        + [GCM functions](#GCMbyCat)
        + [General functions](#GENbyCat)
        + [Message Authentication Code functions](#MACbyCat)
        + [MD5 Hash Algorithm functions](#MD5byCat)
        + [Padding functions](#PADbyCat)
        + [Password-based encryption functions](#PBEbyCat)
        + [PC1 Stream Cipher functions](#PC1byCat)
        + [Pseudorandom functions (PRF)](#PRFbyCat)
        + [Secure Random Number Generator (RNG) functions](#RNGbyCat)
        + [Secure Hash Algorithm (SHA-1) functions](#SHA1byCat)
        + [Secure Hash Algorithm (SHA-256) functions](#SHA2byCat)
        + [Secure Hash Algorithm (SHA-3) functions](#SHA3byCat)
        + [Stream cipher functions](#STREAMbyCat)
        + [Triple Data Encryption Algorithm (Triple DES) functions](#TDEAbyCat)
        + [Wipe functions](#WIPEbyCat)
        + [Extendable-output functions (XOF)](#XOFbyCat)
        + [Compression functions](#COMPRbyCat)
        + [ActiveX Interface](#activexinterface)
        + [Deprecated Functions](#deprecatedfunctions)
* [List of Functions](#functionlist)
* [VBA Wrapper Functions](#vbawrapperfunctions)

    + [VBA Wrapper Function List](#vbawrapperfunctionlist)
* [C++ (STL) Functions](#cppfunctions)
* [ActiveX Classes and Methods](#activexmethods)
* [.NET Classes and Methods](#dotnetmethods)

    + [Cross-reference between Functions and .NET Methods](#xrefdotnet)
        + [.NET Help File](#dotnethelp)
* [Summary of .NET Classes](#dotnetsummary)

    + [Aead Class](#mx_Aead)
        + [Aes128 Class](#mx_Aes128)
        + [Aes192 Class](#mx_Aes192)
        + [Aes256 Class](#mx_Aes256)
        + [Blowfish Class](#mx_Blowfish)
        + [Cipher Class](#mx_Cipher)
        + [CipherStream Class](#mx_CipherStream)
        + [Cnv Class](#mx_Cnv)
        + [Compr Class](#mx_Compr)
        + [Crc Class](#mx_Crc)
        + [Des Class](#mx_Des)
        + [Gcm Class](#mx_Gcm)
        + [General Class](#mx_General)
        + [Hash Class](#mx_Hash)
        + [Mac Class](#mx_Mac)
        + [Md5 Class](#mx_Md5)
        + [Pbe Class](#mx_Pbe)
        + [Pc1 Class](#mx_Pc1)
        + [Prf Class](#mx_Prf)
        + [Rng Class](#mx_Rng)
        + [Sha1 Class](#mx_Sha1)
        + [Sha256 Class](#mx_Sha256)
        + [Sha3 Class](#mx_Sha3)
        + [Tdea Class](#mx_Tdea)
        + [Wipe Class](#mx_Wipe)
        + [Xof Class](#mx_Xof)
        + [Zlib Class](#mx_Zlib)
* [List of .Net Methods](#methodlist)
* [Enumerations in .NET](#dotnetenumerations)
* [Error Codes](#errorcodes)

    + [Changes in error codes in version 5.1](#changesinerrorcodes)
* [Acknowledgements](#Acks)
* [Index](#index)
* [Document Revision History](#revisions)

<a id="WhatIs"></a>What is the CryptoSys API?
---------------------------------------------

The CryptoSys API gives you the ability to call fast,
efficient cryptographic functions in your programs using Visual Basic, VBA, `VB.NET`, C/C++, C#, and ASP. 
It can also be called from VBA applications like Access, Excel and Word.
It provides four of the major block cipher algorithms, three stream cipher algorithms,
all the major secure message digest hash algorithms,
the HMAC, CMAC and Poly1305 message authentication algorithms, 
a data compression facility, 
two password-based key derivation functions (PBKDF2 and SCRYPT),
and a secure random number generator.

The block cipher algorithms provided are 
the Advanced Encryption Standard (AES-128, AES-192, AES-256) as specified in FIPS PUB 197;
Triple DES (TDEA, 3DES, DES-EDE3); 
the original Data Encryption Standard (DES) [for legacy applications];
and Bruce Schneier's Blowfish.
Key Wrap algorithms for AES and Triple DES are provided.
The message digest hash functions are SHA-1, the SHA-2 and SHA-3 families plus RIPEMD-160 and (for legacy applications) MD5 and MD2.
The HMAC algorithm is provided for all these hash algorithms and the CMAC algorithm
for the block ciphers Triple DES and AES.
The stream ciphers are ARCFOUR (RC4), Salsa20 and ChaCha20.
The random number generator (RNG) generates cryptographically-secure random numbers 
to the strict NIST SP800-90 standard, an 
Approved Random Number Generator for FIPS PUB 140-2.

The CryptoSys API
functions allow you to encrypt, decrypt, hash and authenticate data in a variety of formats,
as well as generating secure random keys to use in your applications.
Your input data can generally be in a byte array, encoded as a hexadecimal string, or in a file.
The functions can process the data in a one-off manner, or, for longer inputs, you can
call the "update" functions sequentially after initialising.
The block cipher algorithms work in Cipher Block Chaining (CBC), Electronic Codebook (ECB), 
Cipher Feedback (CFB), Output Feedback (OFB), and Counter (CTR) modes.
You can generate random keys and nonces in a secure manner.
All functions are thread-safe.

[[Contents](#topofpage)] [[Index](#index)]

<a id="Introduction"></a>Introduction
-------------------------------------

The CryptoSys API provides functions to carry out primitive cryptographic operations 
intended to be used as part of a security-related application. 
It is up to you the programmer to ensure that keys, passwords and other private data in your application
are kept secret,
and to ensure that appropriate security policies and procedures are followed by end users. 

This manual assumes you are familiar with the basics of cryptography and can program
to a reasonably advanced level. 

[[Contents](#topofpage)] [[Index](#index)]

<a id="gettingstarted"></a>Getting Started
------------------------------------------

To get started, read the section on [Installation](#installation) and 
the section on your programming language:

* [Using with Classic Visual Basic and VBA](#UsingWithVB)
* [Using with C and C++](#UsingWithC)
* [Using with .NET: C# and `VB.NET`](#UsingWithDotNet)
* [Using with COM/ASP](#UsingWithASP)

and if you are a Visual Basic user, please read [Visual Basic or Visual Basic: VB6 vs `VB.NET`](#vb6vsvbdotnet).

Then try one of the ['Hello world' programs](#helloworld) to make sure it works.

For more details, please read [General Programming Issues](#generalprogramming) and the sample code files in the distribution
(these should be in `C:\Program Files\CryptoSys` or 
`C:\Program Files (x86)\CryptoSys` on a 64-bit system). 
There is more [example code](https://cryptosys.net/apiexamples.html "External link") on our web site.

[[Contents](#topofpage)] [[Index](#index)]

<a id="changesinthis"></a>Changes in this version
-------------------------------------------------

Changes in Version 6.22.1 (January 2024):

* Added support for the RNG functions to use the Intel(R) Digital Random Number Generator (DRNG), 
if available and supported on the user's platform.
The output is used to seed and add entropy to the generator state and Fortuna accumulation pools. It is not used directly.
See [Intel(R) DRNG support](#inteldrng) and [RNG_Initialize](#RNG_Initialize).

Changes in Version 6.22 (12 December 2023):

* Upgraded the random number generator (RNG) to use HMAC_DRBG SHA-512 as per 
NIST Special Publication 800-90A [[SP80090A](#SP80090A)].
This supports increased security strengths up to 256 bits.
* Modified the random number functions that create or update a seed file 
([RNG_MakeSeedFile](#RNG_MakeSeedFile), [RNG_UpdateSeedFile](#RNG_UpdateSeedFile), [RNG_Initialize](#RNG_Initialize))
so that a new seed file is always created even if the file does not exist.
* Increased size of RNG seed file `API_RNG_SEED_BYTES` from 64 to 128 bytes.
* Added options to random number functions that prompt for keyboard entropy 
([RNG_MakeSeedFile](#RNG_MakeSeedFile), [RNG_BytesWithPrompt](#RNG_BytesWithPrompt))
to generate an estimated 192 or 256 bits of security strength.
* Updated [RNG_TestDRBGVS](#RNG_TestDRBGVS) to use the latest test vectors for HMAC_DRBG SHA-512 from [[DRBGVS](#DRBGVS)].

<a id="changesearlier"></a>Changes in earlier versions
------------------------------------------------------

Changes in Version 6.21 (27 May 2023):

* Added a new interface for Python 3 - see[A Python interface to CryptoSys API](https://cryptosys.net/python.html "External link").
Call CryptoSys API functions from your Python programs and access the functions directly from the command-line using the Python REPL.
* Added support for the [cipher suite ASCON](#ciphersuiteascon) which was selected as the new standard for lightweight cryptography by NIST in 2023.

    This Toolkit provides Ascon authenticated encryption with associated data (AEAD) (Ascon-128 and Ascon-128a), 
    hashing functionality (Ascon-Hash and Ascon-Hasha), 
    and an extendable output function (XOF) (Ascon-Xof and Ascon-Xofa).
* Added the [HASH_Length](#HASH_Length) function.
* Added the new diagnostic functions [API_Platform](#API_Platform)
and [API_ModuleInfo](#API_ModuleInfo).
* Added new function [`CNV_ShortPathName`](#CNV_ShortPathName) to help handle filenames with "International" characters.
See [Filenames with "International" characters](#filenamesinternational).
* Removed old `VB.NET` examples.

Changes in Version 6.20 (25 September 2021):

* Added new interface for [C++ programmers using STL](#UsingWithCpp). 
No need to allocate or free *any* memory to use the C++ wrapper functions,
just use strings and vectors.
* Added many new [VBA wrapper functions](#vbawrapperfunctions). 
There is now a VBA wrapper function for *all* generic functions (Cipher, Hash, Mac, Compr, etc).
* Added new shorter-named synonyms for the VBA hex and base64 conversion functions 
[cnvToHex](#VB_cnvToHex),
[cnvFromHex](#VB_cnvFromHex),
[cnvToBase64](#VB_cnvToBase64) and
[cnvFromBase64](#VB_cnvFromBase64),
plus a convenient [cnvBytesMid](#VB_cnvBytesMid) function that does the same operations on a byte array as the `Mid` function does on strings.
* Consolidated all the 32-bit and 64-bit VBA declarations and all the wrapper functions into the one module `basCryptoSys.bas`.
The old files `basCryptoSys64.bas`, `basCryptoSys64_32.bas` and `basCryptoSysWrappers.bas`
are no longer needed and indeed *must not* be used.
* Added new generic compression functions including the Zstandard compression algorithm from [[RFC8878](#RFC8878)].
See [`COMPR_Compress`](#COMPR_Compress) and 
[`COMPR_Uncompress`](#COMPR_Uncompress)
and their .NET, VBA and C++ equivalents.
* Added new functions
	[`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes) and
	[`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes)
to replace deprecated
	`CIPHER_EncryptBytes2` and
	`CIPHER_DecryptBytes2`.
This has no effect on .NET methods or the VBA wrapper functions (it just gets rid of that "2").
* Streamlined the .NET interface functions to replace some overloads by a single method with default parameters.
This requires .NET 4.0 and above (previously it just required .NET 2.0, which is now 16 years old).
* Added HMAC-SHA-3 to the Mac incremental functions 
[`MAC_Init`](#MAC_Init) /
[`MAC_AddBytes`](#MAC_AddBytes) /
[`MAC_Final`](#MAC_Final),
and their .NET, VBA and C++ equivalents.
* Added convenient error message formating functions
[errFormatErrorMessage](#VB_errFormatErrorMessage) (VBA),
[General.FormatErrorMessage Method](#M_General_FormatErrorMessage) (.NET),
and `crsysapi::Err::FormatErrorMessage` (C++).

Changes in Version 6.0 (2 March 2021):

* Added generic stateful functions to handle hash, MAC and block cipher functions with repeated inputs using a context handle:

    + Generic stateful hash functions:
        [HASH_Init](#HASH_Init), [HASH_AddBytes](#HASH_AddBytes) and [HASH_Final](#HASH_Final)
        (.NET [`Hash.Init Method`](#M_Hash_Init),
        [`Hash.AddData Method`](#M_Hash_AddData_Byte),
        and
        [`Hash.Final Method`](#M_Hash_Final)).

        + Generic stateful MAC functions:
        [MAC_Init](#MAC_Init), [MAC_AddBytes](#MAC_AddBytes) and [MAC_Final](#MAC_Final)
        (.NET [`Mac.Init Method`](#M_Mac_Init),
        [`Mac.AddData Method`](#M_Mac_AddData_Byte),
        and
        [`Mac.Final Method`](#M_Mac_Final)).

        + Generic stateful block cipher functions:
        [CIPHER_Init](#CIPHER_Init), [CIPHER_Update](#CIPHER_Update) and [CIPHER_Final](#CIPHER_Final),
            (.NET [`Cipher.InitEncrypt Method`](#M_Cipher_InitEncrypt_ByteByteCipherAlgorithmMode),
            [`Cipher.InitDecrypt Method`](#M_Cipher_InitDecrypt_ByteByteCipherAlgorithmMode),
            [`Cipher.Update Method`](#M_Cipher_Update_Byte),
            and
            [`Cipher.Dispose Method`](#M_Cipher_Dispose)).
            Plus alternative functions to pass data in hexadecimal-encoded form
            [CIPHER_InitHex](#CIPHER_InitHex), [CIPHER_UpdateHex](#CIPHER_UpdateHex).

* Added new functions [CIPHER_EncryptHex](#CIPHER_EncryptHex) and [CIPHER_DecryptHex](#CIPHER_DecryptHex) 
carry out block cipher encryption with padding using hex-encoded parameters
(.NET [`Cipher.Encrypt Method`](#M_Cipher_Encrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) 
and [`Cipher.Decrypt Method`](#M_Cipher_Decrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts)).
These functions provide an alternative input mechanism using hexadecimal-encoded strings, which are simpler to handle than byte arrays.
* Added more convenient set of [VBA wrapper functions](#notesonvbawrapperfunctions) that make it simpler for VBA programmers to use the "raw" functions that output to a string or byte array.
No need to do a first pass to find the required length, or pre-dimension variables before use. 
The wrapper functions return the output in one step directly as a string or byte array.
See [VBA wrapper function list](#vbawrapperfunctionlist).

Changes in Version 5.4 (22 March 2020):

* Added new functions [AEAD_EncryptWithTag](#AEAD_EncryptWithTag) and [AEAD_DecryptWithTag](#AEAD_DecryptWithTag) to provide 
AEAD encryption with the authentication tag appended to the ciphertext (instead of being separate).
(.NET [`Aead.EncryptWithTag Method`](#M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts)
and [`Aead.DecryptWithTag Method`](#M_Aead_DecryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts)).
* Added `API_IV_PREFIX` option to [CIPHER_EncryptBytes2](#CIPHER_EncryptBytes) and [CIPHER_DecryptBytes2](#CIPHER_DecryptBytes)
to prepend the IV before the ciphertext in the output.
(.NET [`PrefixIV`](#T_Cipher_Opts) option for  
[`Cipher.Encrypt Method`](#M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts)
and
[`Cipher.Decrypt Method`](#M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts)).
* Added alternative features for C/VBA programmers using [CIPHER_DecryptBytes2](#CIPHER_DecryptBytes) when removal of padding bytes is involved.
The user can now obtain the exact required length of the decrypted output buffer for ECB and CBC mode.
* Added SHA-3 algorithms to [ActiveX](#activexmethods) wrapper diCryptOCX.dll for [hash](#x_hash) and [mac](#x_mac) classes.
* Minor improvements to the install program.
* Added double signing with both SHA-1 and SHA-256 for all distributed executables.

Changes in Version 5.3 (16 September 2018):

* Added the NIST Secure Hash Algorithm SHA-3 as per [[FIPS202](#FIPS202)] (August 2015)
with digest lengths 224, 256, 384 and 512 bits to all the 
[Message Digest Hash functions](#HASHbyCat)
and their .NET equivalent methods in the
[Hash Class](#mx_Hash).
* Added the stateful functions 
[`SHA3_Init`](#SHA3_Init),
[`SHA3_AddBytes`](#SHA3_AddBytes),
[`SHA3_AddString`](#SHA3_AddString) and
[`SHA3_HexDigest`](#SHA3_HexDigest)
to compute the SHA-3 message digest of data passed in several chunks.
The new equivalent .NET methods are 
[`Sha3.Init`](#M_Sha3_Init),
[`Sha3.AddData (Byte[])`](#M_Sha3_AddData_Byte),
[`Sha3.AddData (String)`](#M_Sha3_AddData_String) and
[`Sha3.HexDigest`](#M_Sha3_HexDigest)
together with 
[`Sha3.Instance`](#M_Sha3_Instance)
and
[`Sha3.Dispose`](#M_Sha3_Dispose)
to create and dispose of the objects.

    The [`SHA3_LengthInBytes`](#SHA3_LengthInBytes) function 
    or [`Sha3.LengthInBytes`](#M_Sha3_LengthInBytesProperty) property
    will return the byte-length of the hash output for an initialized SHA-3 context.

    + For the equivalent SHA-3 function to, say, [`SHA1_BytesHexHash`](#SHA1_BytesHexHash),
        		use the HASH function [`HASH_HexFromBytes`](#HASH_HexFromBytes)
        		with the relevant `API_HASH_SHA3_nnn` option.

* Added the HMAC algorithms with the SHA-3 family (HMAC-SHA3-224/256/384/512) to the [MAC functions](#MACbyCat)
and their .NET equivalent methods in the
[Mac Class](#mx_Mac) as per FIPS PUB 202 [[FIPS202](#FIPS202)].
* Added the KMAC128 and KMAC256 algorithms to the [MAC functions](#MACbyCat)
and their .NET equivalent methods in the
[Mac Class](#mx_Mac).
* Added new function [`PRF_Bytes`](#PRF_Bytes) and equivalent .NET method [`Prf.Bytes`](#M_Prf_Bytes)
	to produce pseudorandom output of any length using KMAC128 and KMAC256 as per NIST SP800-185 [[SP800185](#SP800185)].

* Added new function [`XOF_Bytes`](#XOF_Bytes) and equivalent .NET method [`Xof.Bytes`](#M_Xof_Bytes)
	to provide extended-output functions of any length using SHAKE128 and SHAKE256 as per FIPS PUB 202 [[FIPS202](#FIPS202)].

* Improved performance of [`WIPE_File`](#WIPE_File) 
	(.NET [`Wipe.File Method`](#M_Wipe_File)), 
	and added option to overwrite with a single pass of zero bytes (quicker but less secure).

* Improved the [`ZLIB_Inflate`](#ZLIB_Inflate) function
to compute the required output size in bytes from the compressed data. In earlier versions you needed to know the size by other means.
The .NET method [`Zlib.Inflate Method (Byte[])`](#M_Zlib_Inflate_Byte) now supersedes the old
[`Zlib.Inflate Method (Byte[], Int32)`](#M_Zlib_Inflate_ByteInt32).
* Withdrew deprecated functions `CIPHER_EncryptBytesPad` and `CIPHER_DecryptBytesPad`. Use instead
	`CIPHER_EncryptBytes2` and
	`CIPHER_DecryptBytes2`.
	This has no effect on .NET methods.

Changes in Version 5.2 (15 August 2016):

* Added the SCRYPT password-based key derivation function from [[RFC7914](#RFC7914)].
See [`PBE_Scrypt`](#PBE_Scrypt) and 
[`PBE_ScryptHex`](#PBE_ScryptHex)
and their equivalent .NET [`Pbe Class`](#mx_Pbe) methods.
* Added new symmetrical block cipher functions 
	`CIPHER_EncryptBytes2` and
	`CIPHER_DecryptBytes2`
as safer replacements for 
	`CIPHER_EncryptBytesPad` and
	`CIPHER_DecryptBytesPad` (withdrawn in [v5.3])
with explicit checks for lengths of key and IV byte arrays. 
These new safer functions are now used internally in the equivalent .NET [`Cipher class`](#mx_Cipher) methods.

    + *Warning:* These functions now ignore any padding options except the default `NoPadding` for CTR, OFB and CFB modes
        		(formerly the padding would have been added or stripped even though it wasn't needed).

* Added new block cipher functions
	[`CIPHER_FileEncrypt`](#CIPHER_FileEncrypt) and
	[`CIPHER_FileDecrypt`](#CIPHER_FileDecrypt)
with explicit checks for lengths of key and IV byte arrays.
These functions allow the user to specify the type of padding used for ECB and CBC modes 
(previously only `PKCS5Padding`),
and give the option to prepend the IV to the ciphertext data.
The equivalent .NET methods are
[`Cipher.FileEncrypt Method`](#M_Cipher_FileEncrypt) and
[`Cipher.FileDecrypt Method`](#M_Cipher_FileDecrypt).

* Added stricter checks for lengths of key and IV byte arrays for the algorithm-specific .NET file encryption and decryption methods like
`Aes128.FileEncrypt` or `Tdea.FileDecrypt`.
A `byte[]` key or IV of the wrong length will now cause an explicit error 
(`BAD_KEY_LEN_ERROR` or `BAD_IV_LEN_ERROR`) before it does any more harm.
* Improved constant-time checks when stripping padding from decrypted data.
* Added new padding methods `AnsiX923Padding` and `W3CPadding`:
	see [Padding schemes for block ciphers](#paddingschemes).

* Added support for different padding methods to 
the [Padding functions](#PADbyCat):
[`PAD_BytesBlock`](#PAD_BytesBlock),
[`PAD_UnpadBytes`](#PAD_UnpadBytes),
[`PAD_HexBlock`](#PAD_HexBlock) and
[`PAD_UnpadHex`](#PAD_UnpadHex).
* Added the generic padding .NET methods 
	[`Cipher.Pad Method`](#M_Cipher_Pad_ByteCipherAlgorithmPadding) 
	and 
	[`Cipher.Unpad Method`](#M_Cipher_Pad_ByteCipherAlgorithmPadding).

* Added two new methods 
	[`Cipher.BlockBytes Method`](#M_Cipher_BlockBytes)
	and
	[`Cipher.KeyBytes Method`](#M_Cipher_KeyBytes)
	to return the correct sizes in bytes of the cipher block and key for a given block cipher algorithm.

* Changed the behaviour of the decoding functions 
	[`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr) and
	[`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str)
to be stricter and return an error if any obviously invalid characters are found (formerly they were just ignored).
Whitespace characters are still allowed in both hex and base64 strings, and ASCII punctuation characters in a hex string.
So, for example, the hex string `"DE:AD:BE:EF"` is still OK, 
but characters in the range `[G-Zg-z]` in a hex string now cause an error.

    + *Warning:* This change may break your application if you have assumed the earlier rather lax behaviour
        		(but it was probably wrong anyway!).

* Minimum required operating system is now Windows XP SP2 and above (that is, XP/Vista/W7/W8/W10). Legacy support for W98/NT4/W2K removed.

Changes in Version 5.1 (18 July 2015):

* Added the [`AEAD`](#AEADbyCat) family of 11 new functions 
	and the [`Aead`](#mx_Aead) class of methods
	to provide authenticated encryption with additional data (AEAD)
	with support for the following algorithms:

    + `AEAD_AES_128_GCM`
        + `AEAD_AES_256_GCM`
        + `AEAD_CHACHA20_POLY1305`

    + The new AEAD functions supersede the older [GCM](#GCMbyCat) functions (unless you need to use a non-standard
        key or IV length).

        + The functions `[AEAD_Encrypt](#AEAD_Encrypt)` and `[AEAD_Decrypt](#AEAD_Decrypt)` 
        provide a simple, stateless interface to do one-off AEAD computations.

        + If you need to process a large quantity of data in chunks, use the stateful, incremental functions 
        `[AEAD_InitKey](#AEAD_InitKey)`,
        `[AEAD_SetNonce](#AEAD_SetNonce)`, ...,
        `[AEAD_Destroy](#AEAD_Destroy)`.

        + See 
        [Authenticated Encryption with Additional Data (AEAD)](#aeadalgorithms) and 
        [An interface for AEAD](#aeadinterface) for more details.

* Changed some of the error code values. See [Error Codes](#errorcodes) and
[Changes in error codes in version 5.1](#changesinerrorcodes).
* Included lists of current error codes in suitable formats for inclusion in C/C++, VB6/VBA, `VB.NET` and C# programs.
See the files 
`errorcodes-api.h`, 
`errorcodes-api.bas`,
`errorcodes-api.vb` and
`errorcodes-api.cs`
in the distribution. You may need to cut and paste from these into your projects.

Changes in Version 5.0 (29 April 2015):

* Added the [`CIPHER_Stream`](#STREAMbyCat) family of functions 
	and [`CipherStream`](#mx_CipherStream) class of methods
	to provide stream ciphers
	with support for CHACHA20, SALSA20, and ARCFOUR (a.k.a RC4).
* Added the POLY1305 one-time authenticator.
Use the `API_MAC_POLY1305` option with any of the [`MAC`](#MACbyCat) functions
	or the `MacAlgorithm.Poly1305` option with any of the 
	[`Mac`](#mx_Mac) class of methods.
* Added the functions `CIPHER_EncryptBytesPad` 
and `CIPHER_DecryptBytesPad` which use the specified block cipher algorithm,
mode and padding to encrypt and decrypt data in a byte array. Padding is added if required before encryption and removed after decryption.
The equivalent .NET methods are
`[Cipher.Encrypt Method](#M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts)` and `[Cipher.Decrypt Method](#M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts).`
* Removed the SHA-3 algorithm provisionally added in version 4.6.
We'll put it back when it's all finalized and there are decent test vectors available ... if there's any demand.
* Changed [`API_Version`](#API_Version) to return a five-digit number of the form
`Major * 10000 + Minor * 100 + Release`. For example, version 5.2.1 will return the number 50201
whereas version 4.7.0 would have returned 470.

Changes in Version 4.7 (15 September 2013):

* Changed behaviour of the [`RNG_Initialize`](#RNG_Initialize) function and 
[Rng.Initialize](#M_Rng_Initialize) method so they will create a new seed file if one does not exist
(previously it just used to fail).
* Changed the C/C++ return types for 
[`RNG_Number`](#RNG_Number),
[`CRC_Bytes`](#CRC_Bytes),
[`CRC_File`](#CRC_File) and
[`CRC_String`](#CRC_String) functions 
from `long` to the explicit-size `int32_t` type.
This is only relevant for the MAC-OSX library, where the `long` type is 64 bits instead of 32 bits.
It should have no effect in Windows or other platforms.
* Updated the [`RNG_Number`](#RNG_Number) function and 
[Rng.Number](#M_Rng_Number) method to cope with the full range of 32-bit signed integer limits.
* Reorganized the display of function syntaxes in this document and added reference document for C/C++ programmers, 
[diCryptoSys.h File Reference](https://cryptosys.net/diCryptoSys_h-C-programmers-ref.html "External link"), 
a shorter (!) summary of the C/C++ interface.

Changes in Version 4.6 (7 November 2012):

* Added the NIST Secure Hash Algorithm SHA-3 based on the draft [KECCAK] specification (as of October 2012).
*Withdrawn in [v5.0]*. 
Note this implementation is not compatible with the final specification [[FIPS202](#FIPS202)] (August 2015).
* Improved the speed of the SHA-512 and SHA-384 functions.
* Added the [`HASH_HexFromBits`](#HASH_HexFromBits) function 
and [`Hash.HexFromBits`](#M_Hash_HexFromBits) method
to compute the secure hash of a bit string
(as opposed to the byte-oriented methods) using the SHA family of secure hash functions.
* Added the [`RNG_TestDRBGVS`](#RNG_TestDRBGVS) function 
and [`Rng.TestDrbgvs`](#M_Rng_TestDrbgvs) method
to carry out the relevant validation test in 
*The NIST SP 800-90A Deterministic Random Bit Generator Validation System (DRBGVS)* [[DRBGVS](#DRBGVS)].

Changes in Version 4.5 (23 January 2011):

* Added the extended file cipher functions
[`AES128_FileExt`](#AES128_FileExt),
[`AES192_FileExt`](#AES192_FileExt),
[`AES256_FileExt`](#AES256_FileExt),
[`TDEA_FileExt`](#TDEA_FileExt),
[`DES_FileExt`](#DES_FileExt),
[`BLF_FileExt`](#BLF_FileExt),
and their associated  methods in .NET with the 
[`CipherFileOption`](#T_CipherFileOption) parameter.
The extended options 
(1) enable the IV to be embedded in the ciphertext file and 
(2) allow the padding to be left in place when decrypting.
See [Extensions to block cipher functions for files](#extensionsforfiles) for more details.
* Upgraded the [`API_ErrorCode`](#API_ErrorCode) function and 
	[`General.ErrorCode`](#M_General_ErrorCode)  method
	so they now return an error code after calling most functions. 
	This is useful to find the error when the .NET methods return an empty string.
* Removed all functions deprecated since version 4.0 and earlier to reduce bloat. 
These were functions deprecated in or before the year 2007. 
All have better equivalents in the latest version.

Changes in Version 4.4 (9 August 2010):

* Added a full set of `VB.NET` examples to this manual with cross references.
* Improved the level of detail for all [.NET Classes and Methods](#dotnetsummary) with full cross references to the
	new examples and the equivalent VB6/C functions.
* Added new .NET methods to handle base64 strings in a safe manner and to convert directly between hex and base64 encodings: 
	[Cnv.FromBase64](#M_Cnv_FromBase64),
	[Cnv.ToBase64](#M_Cnv_ToBase64_Byte),
	[Cnv.Base64Filter](#M_Cnv_Base64Filter),
	[Cnv.Base64FromHex](#M_Cnv_Base64FromHex),
	[Cnv.HexFromBase64](#M_Cnv_HexFromBase64), and
	[Cnv.StringFromBase64](#M_Cnv_StringFromBase64).
* Fixed issue with [CNV_HexFilter](#CNV_HexFilter) and non-ASCII characters,
* Improved the way the [Secure Random Number Generator](#rnginfo) gathers entropy across threads.

Changes in Version 4.3 (17 December 2009):

* All DLL executables are now signed with our code authentication certificate.
* Added functions to detect the platform of the underlying DLL. See [Detecting Win32 or X64 platform](#detectingplatform),
[General.IsWin64 Method](#M_General_IsWin64) and [General.Platform Method](#M_General_Platform).
* Various minor speed tweaks.
* Updated this manual with the [List of .NET Methods](#methodlist) and
	[Cross-reference between Functions and .NET Methods](#xrefdotnet).

Changes in Version 4.2 (19 March 2009):

* Compiled using VS2008 for both Win32 and X64, with legacy fix for older W9x and NT4 systems.
* Added Galois/Counter Mode (GCM) authenticated encryption and GMAC authentication. 
	See the [GCM](#GCMbyCat) functions; e.g. [`GCM_Encrypt`](#GCM_Encrypt).
* Added RIPEMD-160 message digest to generic [HASH](#HASHbyCat) and [HMAC](#MACbyCat) functions.
* Improved the performance of the [`WIPE_File`](#WIPE_File) function - up to three times faster for large files.
* New format CHM manual

Changes in Version 4.1 (11 July 2008):

* Added key wrap functions with AES and Triple DES.
* Added SHA-224 message digest to generic [HASH](#HASHbyCat) and [HMAC](#MACbyCat) functions.
* Upgraded password key derivation [PBKDF2](#PBEbyCat) functions to include SHA-2 hash functions 
	as per [PKCS#5 v2.1](#PKCS5).
* Includes executables compiled for Windows 64-bit (x64) computers.
* Carried out an expensive product rebrand (well, we changed the colour of the CryptoSys API logo).

Changes in Version 4.0 (12 September 2007):

* Added generic [HASH](#HASHbyCat) functions to provide SHA-384 and SHA-512 as well as existing hash digest functions.
* Added generic [MAC](#MACbyCat) functions to provide HMAC and CMAC message authentication code algorithms.
* Introduced new [random number generator](#RNGbyCat) to strict NIST SP800-90 specification.

Changes in Version 3.2 (22 July 2006):

* Added CFB, OFB and CTR modes for all block ciphers. See [Block Cipher Modes](#blockciphermodes).
* Added padding and unpadding functions for block ciphers. See [Padding Functions](#PADbyCat).
* Introduced the .NET class library as a more convenient and safer interface for C# and `VB.NET` programmers.
Interface source code in C# is included.
* Added hex version of password key derivation and RC4-compatible stream cipher functions 
[PBE_Kdf2Hex](#PBE_Kdf2Hex) and [PC1_Hex](#PC1_Hex).
* Added base64 support for block ciphers, e.g. [AES128_B64Mode](#AES128_B64Mode).
* Added base64 conversion functions [CNV_BytesFromB64Str](#CNV_BytesFromB64Str) and 
	[CNV_B64StrFromBytes](#CNV_B64StrFromBytes).
* Various minor speed tweaks and improvements in error handling and thread local storage.

Version 1.0 first published 13 September 2001.

[[Contents](#topofpage)] [[Index](#index)]

<a id="Conventions"></a>Conventions in this document
----------------------------------------------------

Code in classic Visual Basic (VB6/VBA) is shown shaded as follows:-

```

Dim strData As String
Dim nRet As Long
strData = "Hello world"
Debug.Print strData

```

Code in C/C++ is shown as:

```

char *str = "Hello world";
printf("%s\n", str);

```

Code in `VB.NET` (VB200x) is shown as:

```

Dim nDataLen As Integer
Dim abData() As Byte
If strData.Length = 0 Then Exit Function
abData = System.Text.Encoding.Default.GetBytes(strData)
nDataLen = abData.Length

```

Code in C# is shown as:

```

public static string ToHex(byte[] binaryData)
{
   int nBytes = binaryData.Length;
   Int32 nChars = 2 * nBytes;
   if (nBytes == 0) return String.Empty;
   StringBuilder sb = new StringBuilder(nChars);
   nChars = CNV_HexStrFromBytes(sb, nChars, binaryData, nBytes);
   return sb.ToString(0, nChars);
}

```

Code in VBScript/ASP is shown as:

```

Dim oGen
Set oGen = Server.CreateObject("diCryptOCX.gen")
Response.Write "Version=" & oGen.Version & Chr(13) & Chr(10)

```

Output from code samples is shown as:

```

Result=OK

```

All functions called directly in the CryptoSys API  begin with 3 or 4 capital letters
followed by an underscore "_", e.g.

```

nRet = API_ErrorLookup(strMsg, Len(strMsg), nCode)

```

For VBA users, there are some wrapper functions provided in the module `basCryptoSys.bas`
which avoid the complications of having to pre-dimension strings, etc. These
begin with lowercase letters and have no underscore. They are shown in our examples as follows:

```

strErrMsg = apiErrorLookup(nCode)

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="Copyright"></a>Copyright Notice
--------------------------------------

Except where otherwise noted, 
the CryptoSys API executables, sample source code and this 
manual were written by David Ireland
and are copyright (c) 2001-25 by DI Management Services Pty Limited, all rights reserved.
They may not be distributed or reproduced
separately by any means whatsoever without express permission.
Users holding a valid developer's licence are permitted to distribute the executable 
as part of a value-added application according to the terms of their licence.

You may obtain latest version of CryptoSys API 
from
<[https://cryptosys.net/](https://cryptosys.net/ "External link")>.

[[Contents](#topofpage)] [[Index](#index)]

<a id="Background"></a>Background Basics
----------------------------------------

* [Block ciphers](#blockcipher)
* [Block cipher modes](#blockciphermodes)
* [Padding](#padding)
* [Stream ciphers](#streamcipher)
* [One-way message digest (hash) functions](#hashfunctions)
* [Message authentication code (MAC) functions](#macfunctions)
* [The Poly1305 message authentication algorithm](#poly1305algorithm)
* [Authenticated Encryption with Associated Data (AEAD)](#aeadalgorithms)
* [The cipher suite ASCON](#ciphersuiteascon)
* [Data compression in cryptography](#compression)

There is no theory explained here. You are assumed to have a sufficient background knowledge of 
cryptography in order to use the tools and algorithms provided in this API.
We may give some guidance or make recommendations in this manual and in the example code.
These are made in good faith but may be out of date or incorrect.
Use any guidance or recommendations at your own risk and make whatever checks you deem necessary before relying on them.

For a good introduction
to the principles of cryptography refer to Bruce Schneier's *Applied Cryptography*
[[SCHN96](#SCHN96)] or William Stallings *Cryptography and Network Security*
[[STAL05](#STAL05)].
For a more advanced treatment, see
*Handbook of Applied Cryptography* by Menezes, van Oorschot and Vanstone
[[MENE97](#MENE97)]. 

### <a id="blockcipher"></a>Block cipher algorithms

All block cipher algorithms operate on a fixed-length block of data
to produce a seemingly-random output of the same size.
The security of the encryption process depends on a secret key,
the length of which depends on the particular algorithm.
It should be impossible (strictly, computationally infeasible) to
derive the plaintext from the resultant ciphertext without knowing the key.

The block and key lengths supported in the
CryptoSys API package
are as follows:

| Algorithm | Block length | Key length |
| --- | --- | --- |
| DES | 8 bytes (64 bits) | 8 bytes (only 56 bits used out of 64) |
| Triple DES (TDEA, 3DES) | 8 bytes (64 bits) | 24 bytes (only 168 bits used out of 192) |
| Blowfish | 8 bytes (64 bits) | up to 56 bytes (variable up to 448 bits) |
| AES | 16 bytes (128 bits) | 16 or 24 or 32 bytes (128/192/256 bits) |

### <a id="blockciphermodes"></a>Block Cipher Modes and Initialization Vectors

The block cipher confidentiality modes in this module comply with 
*Recommendation for Block Cipher Modes of Operation* [[SP80038A](#SP80038A)].
To quote from Section 5.3 of that document:

> The input to the encryption processes of the CBC, CFB, and OFB modes includes, in addition to 
> the plaintext, a data block called the initialization vector (IV), denoted IV.  The IV is used in an 
> initial step in the encryption of a message and in the corresponding decryption of the message. 
> 
>    
>  
> The IV need not be secret; however, for the CBC and CFB modes, the IV for any particular 
> execution of the encryption process must be unpredictable, and, for the OFB mode, unique IVs 
> must be used for each execution of the encryption process.

In Electronic Codebook (ECB) mode, each block is encrypted independently.
In Cipher Block Chaining (CBC) mode, an initialization vector (IV)
is added to the first block of plaintext before encryption and the resultant ciphertext
is added to the next block of plaintext before encryption, and so on. Decryption is the
reverse process. The IV does not need to be kept secret and must be communicated to the 
receiving party along with the ciphertext.

Block ciphers in ECB or CBC mode require their input to be an exact multiple of the block length.
Any odd bytes need to be padded to the next multiple. In general, this is the user's responsibility.
However, for encrypting files,
CryptoSys API
adds a padding string using the convention described in [Padding](#padding) below.

For all other encryption functions in this API, it is the user's responsibility to provide and handle
appropriate padding where necessary for ECB and CBC modes. 
See [Padding](#padding).

Cipher Feedback mode (CFB), Output Feedback mode (OFB) and Counter mode (CTR) do not require padding.
We include CFB and OFB modes here for completeness where users may need to communicate with a system that requires it.
We recommend using either CBC or CTR modes if you have the choice. 
CBC mode is supported in most encryption systems.

The CTR mode in this package treats the entire "IV" as a 64- or 128-bit "counter". So if the IV provided
is, say, `0xFFFFFFFFFFFFFFFD` for a 64-bit block cipher, then the counter values used will be:

```

fffffffffffffffd
fffffffffffffffe
ffffffffffffffff
0000000000000000
0000000000000001
...

```

It's up to the programmer to ensure that unique IV or counter values are provided for 
each message encrypted with the same key.
Using an IV generated each time with the [`RNG_NonceData`](#RNG_NonceData) or 
[`RNG_NonceDataHex`](#RNG_NonceDataHex) function should be perfectly adequate
as the odds against producing a duplicate value are billions to one.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="padding"></a>Padding

Before encrypting random-length plaintext with a block cipher algorithm in ECB or CBC mode it needs to be padded to an exact multiple
of the block length.

There are many padding rules used in practice.
The padding schemes supported in this library are described in the section
[Padding schemes for block ciphers](#paddingschemes).
It's up to you and your recipient which method you use, but you must agree on one method
and use it consistently.
If your data is always an exact multiple of the block length and the sender and the recipient agree
then you can omit the padding string.

The most common padding rule is known as "PKCS5Padding" originally from PKCS #5 [[PKCS5](#PKCS5)],
which in turn is from [[RFC1423](#RFC1423)] and is also the 
same as the padding rules in PKCS #7 [[PKCS7](#PKCS7)] and 
section 6.3 of RFC 5652 [[CMS](#CMS)]

The rules of the scheme are as follows:

> **For a 64-bit block size:**
> Append a padding string of between 1 and 8 bytes to make the total length an exact multiple of 8 bytes. 
> The value of each byte of the padding string is set to the number of bytes added; namely,
> 8 bytes of value 0x08, 7 bytes of value 0x07, ..., 2 bytes of 0x02, or one byte of value 0x01.
> The length of the plaintext to be encrypted thus will be an exact multiple of 8 bytes and it will
> be possible to recover the message unambiguously from the decrypted ciphertext.
> 
> 
> 
> 
> **For a 128-bit block size (e.g. AES):**
> Append a padding string of between 1 and 16 bytes to make the total length an exact multiple of 16 bytes. 
> The value of each byte of the padding string is set to the number of bytes added; namely,
> 16 bytes of value 0x10, 15 bytes of value 0x0F, ..., 2 bytes of 0x02, or one byte of value 0x01.
> The length of the plaintext to be encrypted thus will be an exact multiple of 16 bytes and it will
> be possible to recover the message unambiguously from the decrypted ciphertext.

See the functions
[`PAD_BytesBlock`](#PAD_BytesBlock),
[`PAD_UnpadBytes`](#PAD_UnpadBytes),
[`PAD_HexBlock`](#PAD_HexBlock) and
[`PAD_UnpadHex`](#PAD_UnpadHex).

The "Pad" functions will *always* return a longer string than the input. 
The "Unpad" functions will either return 
a shorter string (indicating a valid padding string was found and stripped) or will return a
DECRYPT_ERROR if no valid padding string was found.
Note that it is still possible to have a "valid" padding string at the end of incorrectly deciphered data
- just by coincidence -
so you may get a "valid" result from using the Unpad function, but the decrypted text is garbage.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="streamcipher"></a>Stream ciphers

A stream cipher operates on streams of plaintext one bit or byte at a time.
The output is always the same length as the input.
There is no 'decrypt' mode: to decipher just encrypt again with the same key.

*[New in v5.0]*
There are three stream ciphers available in this API: ARCFOUR, Salsa20 and ChaCha20.
All operate on input streams of bytes of any length.
ARCFOUR uses a key which can be any length (16 or 32 bytes are recommended). 
Salsa20 and ChaCha20 both require the key to be exactly 16 bytes (128 bits) or 32 bytes (256 bits) and require
a unique IV or nonce for each message encrypted with a given key. 
ChaCha20 also uses an optional 32-bit integer counter.
It is up to the user to provide a unique IV and to pass its value separately to the recipient.
It is an error to specify a key or IV of the wrong length for Salsa20 or ChaCha20. 

| Algorithm | Key length | IV required? | IV length | Counter |
| --- | --- | --- | --- | --- |
| ARCFOUR (RC4) | any | No | n/a | No |
| Salsa20 | 16/32 bytes | Yes | 8 bytes | No |
| ChaCha20 | 16/32 bytes | Yes | 8/12/16* bytes | Optional* |

* The default counter is zero. The counter is ignored if the IV length is 16 bytes.

*[Superseded in v5.0]*
In early versions, we used the made-up name "PC1" to describe the ARCFOUR algorithm in order to to avoid proprietary restrictions on the RC4 name.
The old PC1 functions 
PC1_Bytes, PC1_Hex and PC1_File 
are now superseded by 
`[CIPHER_StreamBytes](#CIPHER_StreamBytes)`,
`[CIPHER_StreamHex](#CIPHER_StreamHex)` and
`[CIPHER_StreamFile](#CIPHER_StreamFile)`,
respectively, using the more common algorithm name "ARCFOUR".

Note that there are known weaknesses with the ARCFOUR algorithm.
[[RFC4345](#RFC4345)] recommends dropping the first 1536 bytes in the keystream.
The implementation in this toolkit does *not* do that. 
To workaround, prefix your input with 1536 dummy bytes, then throw them away.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="hashfunctions"></a>One-way message digest (hash) functions

A message digest (or hash) function is a cryptographic primitive used for
digital signatures and password protection.
It maps a message of arbitrary length to a fixed-length hash value or "message digest".
The same input (message) will always result in the same output.

Note that the terms *hash function*, *hash algorithm* and *message digest algorithm* can be used interchangeably.
Similarly, the terms *message digest*, *hash value* and *digest value* mean the same thing.

A cryptographic hash function should be *one-way* and *collision-resistant*.

"One-way" means that it's easy to compute the digest output from the message input, but it's effectively impossible
to go backwards and find the input given the digest. 
More formally, it means that, given an n-bit hash value,
it should require work equivalent to about 2n hash computations to find
any message that hashes to that value. 

"Collision-resistant" means that it should be almost impossible to find two messages that hash to the same digest value (a *collison*).
Finding a collision for a given digest value should require work equivalent to about 2n/2 hash computations. 

SHA-1 is a 160-bit (20-byte) hash function specified in FIPS PUB 180
*Secure Hash Standard (SHS)* [[FIPS180](#FIPS180)].
It is no longer considered secure for digital signatures.

The SHA-2 family of hash functions, SHA-224, SHA-256, SHA-384 and SHA-512, are also specified in [[FIPS180](#FIPS180)],
and have digest lengths of
224, 256, 384 and 512 bits (28, 32, 48 and 64 bytes), respectively.
SHA-256 is intended as a companion for the Advanced Encryption Standard (AES) to provide a similar level of enhanced security as AES-128 (i.e. a security strength of 128 bits).
Similarly, SHA-512 is designed to have the same level of security as AES-256 (a security strength of 256 bits).

SHA-224 and SHA-384 are effectively just cut-down versions of SHA-256 and SHA-512, with exactly the same computational effort required, 
and are for use where the length of digest values needs to be kept to a minimum (at a cost of reduced security).

MD5 is an older, less-secure, but faster hash algorithm with a digest length of 128 bits. It is no longer recommended for use.
MD2 is even older and should not be used. We keep it in this library in case you need it for some legacy use.

The SHA-3 family of hash functions SHA3-224, SHA3-256, SHA3-384 and SHA3-512 are specified in [[FIPS202](#FIPS202)], published in 2015.
They have the same digest lengths as the SHA-2 family but are based on an entirely different algorithm, called Keccak.
The intention is to keep the SHA-3 family "in reserve" in case a vulnerability is found in the SHA-2 family.
See also [Notes on SHA-3](#sha3notes).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="sha3notes"></a>Notes on SHA-3

Note that the old SHA-3 implementation introduced in November 2012 [v4.6] and withdrawn in 2015 [v5.0] is not compatible with the latest release [v5.3].
The old implementation was based on the KECCAK specification that won the SHA-3 competition in 2012. 
However, the final specification of SHA-3 [[FIPS202](#FIPS202)] published by NIST in 2015 was different from the 2012 one.
While the changes were beneficial overall, it is unfortunate for people who jumped the gun (like us and anyone who used it).
Be assured that current SHA-3 implementation as of [v5.3] is fully compliant with the final 2015 NIST specification.

#### Converting bitstrings from NIST format to CryptoSys API format

The bit-oriented tests for SHA-3 (SHAVS-SHA3 CAVS 19.0) use a different convention for representing bitstrings than we do in this toolkit.
If the bitstring is an exact multiple of 8 (i.e. whole bytes) then no changes need be made.
Otherwise the last byte in the sequence need to be changed. For example:

```

bitlen = 21
Msg  = 9d4306  <= NIST representation in .rsp test file
Msg' = 9d4330  <= To use in [HASH_HexFromBits](#HASH_HexFromBits)

```

The algorithm is as follows:
1. Let "bitlen" be the length of the message in bits and let "Msg" be the NIST representation in hexadecimal.
2. Let n be the value of the last (rightmost) byte in "Msg".
3. Compute the shift, s = 8 - (bitlen % 8)
4. Compute n' = n << s (shift n to the left by s bits)
5. Replace the last byte in "Msg" with n'

Examples:

```

bitlen = 21
Msg  = 9d4306
n = 0x06
s = 8 - (21 % 8) = 8 - 5 = 3
n' = 0x06 << 3 = 0x30
Msg' = 9d4330

```

```

bitlen = 22
Msg  = 259028
n = 0x28
s = 8 - (22 % 8) = 8 - 6 = 2
n' = 0x28 << 2 = 0xA0
Msg' = 2590A0

```

[[Contents](#topofpage)] [[Index](#index)]

### <a id="macfunctions"></a>Message authentication code (MAC) functions

A message authentication code (MAC) is used to establish the authenticity and, hence, the
integrity of a message.
MACs have two functionally distinct
parameters, a message input (data, text) and a secret key known only to the message originator and intended receiver.

MACs based on cryptographic hash functions are known as HMACs.
The HMAC algorithm is described in
[[FIPS198](#FIPS198)] and RFC 2104
[[HMAC](#HMAC)].
HMACs can have a key of any length and produce a digest of the same length as the underlying message digest function.

The CMAC algorithm is based on a symmetric key block cipher and is equivalent to the one-key CBC MAC1 (OMAC1)
algorithm. CMAC is described in SP800-38B [[SP80038B](#SP80038B)].
CMAC uses either Triple DES or one of the three AES functions. The key length for CMAC is the same as the
underlying block cipher. The output is the same length as the block length: 64 bits for Triple DES and 128 bits
for AES.
It is permissible to truncate an HMAC or CMAC value, at a cost of reduced security.

See also [Poly1305](#poly1305algorithm) and [KMAC](#kmac).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="poly1305algorithm"></a>The Poly1305 message authentication algorithm

Poly1305 is a one-time authenticator that takes a 32-byte one-time key together with a message of any length,
and outputs a 16-byte authentication tag (i.e. a MAC).

*[New in v5.0]*
Use the `API_MAC_POLY1305` option in the [MAC](#MACbyCat) functions
and the `MacAlgorithm.Poly1305` option in the .NET [Mac Class](#mx_Mac) methods.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="kmac"></a>KMAC: KECCAK Message Authentication Code

The KECCAK Message Authentication Code (KMAC) algorithm is a variable-length keyed hash function described in NIST SP800-185 [[SP800185](#SP800185)]. 
It is based on KECCAK, the core SHA-3 algorithm. 

There are two variants, KMAC128 and KMAC256, which have expected security strengths of 128 and 256 bits, respectively.
The "standard" output lengths for KMAC128 and KMAC256 are 256 bits (32 bytes) and 512 bits (64 bytes), respectively. 

The KMAC algorithm can theoretically output an infinitely-long stream of bytes, so it can also be used as a Pseudorandom function (PRF).
Note that you *cannot* truncate a KMAC output value when used as a message authentication code.

*[New in v5.3]*
You can generate a fixed-length MAC of the "standard" length using the 
`API_KMAC_128` or `API_KMAC_256` options in the [MAC](#MACbyCat) functions and the 
`MacAlgorithm.Kmac128` or `MacAlgorithm.Kmac256` options in the .NET [Mac Class](#mx_Mac) methods.
If you require different output lengths, use [`PRF_Bytes`](#PRF_Bytes).

The KMAC algorithm also has an optional customization string parameter, by default the empty string (`""`).
To use a customization string with KMAC, use the [`PRF_Bytes`](#PRF_Bytes) function with a KMAC option.

*CAUTION:* the lengths of the key and customization string can theoretically be any length (including zero). 
To obtain the expected security strength you must use keys of length at least 128 and 256 bits respectively.
There are no reliable test vectors available for KMAC using non-standard key lengths or long customization strings (AFAWK in September 2018),
so be careful.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="xof"></a>XOF: eXtendable-Output Function

An extendable-output function (XOF) is a variable-length hash function on a message in which the output can be extended to any desired length.

*[New in v5.3]*
the [`XOF_Bytes`](#XOF_Bytes) function provides an XOF using the SHAKE128 and SHAKE256 algorithms from the SHA-3 Standard
[[FIPS202](#FIPS202)].

[[Contents](#topofpage)] [[Index](#index)]

### <a id="aeadalgorithms"></a>Authenticated Encryption with Additional Data (AEAD)

*Authenticated Encryption with Associated Data* (AEAD) provides both *authenticated encryption*
(confidentiality and authentication) and the ability to check the integrity and authentication of 
*additional authenticated data* (AAD) that is sent in the clear. 

**Authenticated encryption:** There are four inputs for authenticated encryption: the secret key, 
a nonce (sometimes called the initialization vector (IV)†), 
the plaintext itself, and optional additional authentication data (AAD). 
The nonce and AAD are passed in the clear. 
There are two outputs: the ciphertext, which is exactly the same length as the plaintext, 
and an authentication tag (the "tag").

**Authenticated decryption:** The authenticated decryption operation has five inputs: the secret key, 
a nonce, the ciphertext itself, 
the additional authentication data (AAD), which can be zero-length; and the tag. 
The nonce and AAD are passed in the clear. 
There is one output: the plaintext, which is exactly the same length as the plaintext. 
If the inputs are not authentic, the function returns a "FAIL" error code.

**MAC:** The AEAD encryption function can be used to compute a Message Authentication Code (MAC)
over the additional data by passing zero-length input for the plaintext. The output tag is the MAC.
Similarly, the MAC can be authenticated against the AAD using the AEAD decryption function 
by passing zero-length input for the ciphertext. Note that a nonce is required as well as the key.

<a id="aeadsecurity"></a>
**Security considerations:** It is critical that unique nonces are used for different messages encrypted with the same key.
Using the same nonce with the same key and different plaintexts seriously undermines security. 

For more information about using the AEAD functions in this library, see
[An interface for Authenticated Encryption with Additional Data (AEAD)](#aeadinterface).

† Some authors use the term "initialization vector" (IV) to mean the entire nonce value.
	Others use "IV" to mean a unique variable part to be combined with a "fixed" part to make the full nonce value. 
	If we use the term "IV" in relation to AEAD, we mean the full 12/16-octet nonce value.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="ciphersuiteascon"></a>The cipher suite ASCON

Ascon [[ASCON21]](#ASCON21) is a family of authenticated encryption and hashing algorithms designed to be lightweight and easy to implement.
 Ascon has been selected as the new standard for lightweight cryptography in the 
 [NIST Lightweight Cryptography competition](https://csrc.nist.gov/projects/lightweight-cryptography "External link") (2019–2023).
 We include here implementations of Ascon on a provisional basis - they may be changed in the final NIST specification.

The cipher suite Ascon provides authenticated
encryption with associated data (AEAD) and hashing functionality. 
The suite
consists of the authenticated ciphers Ascon-128 and Ascon-128a. 
Additionally, the suite consists of the hash
functions Ascon-Hash and Ascon-Hasha, and the extendable output functions
Ascon-Xof and Ascon-Xofa. 
The recommendation for NIST includes Ascon-128 combined with Ascon-Hash, 
or Ascon-128A combined with Ascon-Hasha.
All schemes provide 128-bit security.

For implementations in this toolkit, see [AEAD_EncryptWithTag](#AEAD_EncryptWithTag), [AEAD_DecryptWithTag](#AEAD_DecryptWithTag),
[HASH_Bytes](#HASH_Bytes), [HASH_HexFromHex](#HASH_HexFromHex), and [XOF_Bytes](#XOF_Bytes).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="compression"></a>Data Compression in Cryptography

Compressing data before encryption not only makes for shorter messages to be transmitted or 
stored, but also improves security by reducing the redundancy in the plaintext
and making cryptanalysis harder.

CryptoSys API includes compression ([`ZLIB_Deflate`](#ZLIB_Deflate)) 
and decompression ([`ZLIB_Inflate`](#ZLIB_Inflate))
functions based on Jean-loup Gailly's excellent zlib product.
Just remember to compress *before* encrypting.

[[Contents](#topofpage)] [[Index](#index)]

<a id="rnginfo"></a>Secure Random Number Generator
--------------------------------------------------

Many procedures use a random session key to encrypt the body of the message. If this key
is ever compromised - because the random numbers are predictable or can be manipulated before
being generated -
an opponent who has had access to your encrypted messages can decipher them at his leisure. 
You *never* use the standard VB6 `Rnd()` or C stdlib `rand()` 
functions to generate your keys!
For more examples of potential problems see [[GUTM](#GUTM)]
and [[KELS98](#KELS98)].

* [RNG Mechanisms](#rngmechanisms)
* [Techniques to add known security strength to the RNG process](#rngtechniques)
* [User-supplied entropy (seeds)](#rngentropy)

### <a id="rngmechanisms"></a>RNG Mechanisms

The random number generator used in the 
CryptoSys API 
is designed to conform to 
NIST Special Publication 800-90A
*Recommendation for Random Number Generation Using Deterministic Random Bit Generators* 
[[SP80090A](#SP80090A)].
Entropy is accumulated in "Fortuna" pools as described in
Ferguson and Schneier, *Practical Cryptography*, [[FERG03](#FERG03)].
Under any circumstances, this algorithm provides more secure random numbers than 
ANSI X9.31 Appendix A [[X9-31](#X9-31)].

The full technical details are published on our [web site](https://cryptosys.net/rng_algorithms.html "External link"). 

The underlying RNG functions use the algorithms recommended in NIST SP 800-90 
[[SP80090A](#SP80090A)] (the "DRBG Standard")
to provide a Deterministic Random Bit Generator (DRBG).
The HMAC_DRBG mechanism is used with SHA-512 as the underlying hash function.
This outputs a sequence of binary bits that appears to be
statistically independent and unbiased. The output is effectively random so long
as internal actions of the process are hidden from observation. In particular
the algorithm provides good Backtracking Resistance and, depending how it is
used, good Prediction Resistance.

Entropy is accumulated at startup and whenever certain functions in the library are called.
Only inobtrusive methods of collecting entropy are used, so you can use the API safely
in any application.
The "Fortuna" method of pooling is used to prevent certain attacks from someone who
controls some but not all of the entropy sources 
(see chapter 10 of [[FERG03](#FERG03)]). 
The more times your
application calls the functions in the library before needing some random data,
the more entropy will be accumulated. 
The user cannot control how or when the Fortuna entropy is added to the RNG process - this is by design.

The advantage of the Fortuna system is that the level of entropy does not need to be measured. 
There is, however, a period of vulnerability just after start up when there may not be sufficient entropy in the
pools. This can be overcome by initializing with a [seed file](#rngtechniques),
or *[New in v6.22.1]* getting entropy seeds from the [Intel(R) DRNG](#inteldrng) hardware-generated random values.

We strongly recommend that you use and initialize with a seed file wherever possible.

### <a id="inteldrng"></a>Intel(R) DRNG support

*[New in v6.22.1]*

The Digital Random Number Generator (DRNG) is an innovative hardware approach to high-quality, high-performance entropy and random number generation. 
It is composed of the new Intel 64 Architecture instructions RDRAND and RDSEED and an underlying DRNG hardware implementation
[[INTEL-DRNG](#INTEL-DRNG)].

If Intel(R) DRNG is supported on your machine, it will be called automatically the first time you call an RNG function, and will
add an estimated 256 bits of entropy using hardware-generated random values.

The output is used to seed and add entropy to the generator state and Fortuna accumulation pools. It is not used directly.

The availability of support can be checked using the [`RNG_Initialize`](#RNG_Initialize) function
(.NET [`Rng.InitializeEx Method`](#M_Rng_InitializeEx))
 and passing an empty `""` filename parameter.
If the return value is a positive number then Intel(R) DRNG is supported (1=RDRAND available, 2=RDSEED available, 3=both RDRAND and RDSEED available).
RDSEED will be preferred if available.
Support can also be explicitly turned off using the `API_RNG_NO_INTEL_DRNG` option.

### <a id="rngtechniques"></a>Techniques to add known security strength to the RNG process

1. Use the Intel(R) DRNG hardware-generated source of random seeds

:   If available on your system, calling the Intel(R) DRNG functions retrieves a hardware-generated random seed value which is added to our SP800-90A-compliant DRGB.
This is carried out automatically whenever any RNG function is called from our Toolkit. 
Even if an attacker can monitor the output from the Intel(R) DRNG  calls, they cannot predict the output from our RNG functions.
If not available, then it is ignored.

2. Use a seed file

:   Using a seedfile restores the entropy created during an earlier session and avoids any issues at startup of insufficient entropy in the pools.
Use the 
[`RNG_Initialize`](#RNG_Initialize)
function to specify a seedfile with a known minimum amount of entropy
to initialise the PRNG. This seed file is updated automatically when used. You
should call the 
[`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile)
from time to time in your
application to save any existing entropy, and use 
[`RNG_MakeSeedFile`](#RNG_MakeSeedFile)
to create a new one. 
The security of this
method is as good as the security you have over the seed file. If an attacker
controls the seed file, it does not mean they control the random output data; it
just means that using a seedfile does not increase the security strength of the PRNG.

3. Make the user enter random keystrokes

:   Use the 
[`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt) function 
when generating random data to force the user to
generate entropy using random keystrokes and mouse movements.
[`RNG_MakeSeedFile`](#RNG_MakeSeedFile)
 also uses such a prompt. 
This works provided you know the user's keyboard strokes and mouse movements are secure 
(e.g. are not being transmitted over a network).

4. Add your own entropy

:   If you have your own independent source of entropy (perhaps by monitoring the output of a radioactive isotope :-), add this "additional input"
to the RNG process as a "seed" when using the 
[`RNG_KeyBytes`](#RNG_KeyBytes) function.
If you assume zero security strength for the
internally-generated entropy and you add input with, say, 128 bits of security
strength, then the output from the RNG will have at least 128 bits of security
strength.

### <a id="rngentropy"></a>User-supplied entropy (seeds)

User-supplied entropy (a.k.a. a "seed") is added as "additional input" to the generation process.
It does not affect the accumulation pools and cannot be used
by an attacker to control the output.

Remember it's not how "random" your user-supplied entropy is, but how little an
attacker knows about it. Using the current time is of little use. If you can provide
16 bytes of data each selected randomly from the range 0 to 255 of which an attacker knows nothing and cannot later discover,
then you have added 128 bits of security strength. 

For more details on the security aspects of the random number generator, see 
the technical details published on our [web site](https://cryptosys.net/rng_algorithms.html "External link").

CryptoSys API also lets you generate **nonces** -
a term used in security engineering meaning "number used once".
Use a nonce where random but
not-necessarily-unpredictable numbers are required: e.g. for initialization vectors,
SSL cookies and random padding data. 

[[Contents](#topofpage)] [[Index](#index)]

<a id="cautionwithdefaults"></a>A caution about insecure default algorithms
---------------------------------------------------------------------------

**CAUTION:** Many of the default algorithms in this Toolkit (originally written 20 years ago) are no longer considered secure. 
You are recommended explicitly to use at least the following minimum-strength algorithms:

| Algorithm | Default | Minimum recommended | Option to use |
| --- | --- | --- | --- |
| Message digest | SHA-1 | SHA-256 | `API_HASH_SHA256` |
| HMAC | HMAC-SHA-1 | HMAC-SHA-256 | `API_HMAC_SHA256` |
| Symmetric encryption | Triple DES (TDEA) | AES-128/AES-128-GCM* | `API_BC_AES128/API_AEAD_AES_128_GCM` |

* Use the [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag) function or 
[`Aead.EncryptWithTag Method`](#M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) for AES-GCM.

[[Contents](#topofpage)] [[Index](#index)]

<a id="installation"></a>Installation
-------------------------------------

To install on a test or developer system, use the **install.exe** program provided with the distribution. 
This installs the core DLL(s) in your main windows system directory and creates copies of all other required files,
including this manual, in the directory 
`C:\Program Files\CryptoSys` (32-bit platforms) 
or `C:\Program Files (x86)\CryptoSys` (64-bit platforms).

To distribute a Licensed Version to your end users, please read the instructions in the file **distrib.txt**.
You do *not* use the `install.exe` program to distribute to end users.
Note that the core DLL file is completely different for the Trial and Developer versions.
All other files are the same.

**Important:** You *must* use the `install.exe` program to install the Trial version on your system
and you
*must* have administrator rights when installing or uninstalling this version.

To uninstall, use **Start > Settings > Control Panel > {Programs and Features}|{Add/Remove Programs} > CryptoSys API**
to remove the application and all associated files.

### Core executable DLL

The core executable is **`diCryptoSys.dll`** which is a native Windows DLL.
This file must
exist in the library search path on the user's system for all programming language interfaces.
The executable `diCryptoSys.dll` is *not* registered with RegSvr32 (it can't be). 
The VB6/VBA and C/C++ interfaces access this core executable directly.

### Wrapper DLLs

Two wrapper executables are provided to allow .NET and COM programming access to the core executable.
Both require the core native `diCryptoSys.dll` to exist in the library search path.

1. **`diCrSysAPINet.dll`** is a .NET Class Library which exposes various classes
to allow programming access from C# and `VB.NET` projects. 
This file is referenced from your .NET project. It is *not* registered.
It is installed by default in `C:\Program Files (x86)\CryptoSys\DotNet\` and is compiled for
all platforms (Win32 and X64). You will need to set a reference to it from your .NET projects.
2. **`diCryptOCX.dll`** is a 32-bit ActiveX DLL which exposes various classes to allow
programming access from ASP, VBScript and other 32-bit COM applications including VB6. 
Note it is *not* supported by 64-bit Microsoft Office.
The installation program [*as of v4.4*] now registers this automatically during installation. 
This file is installed by default in `C:\Program Files\CryptoSys\COM` or
`C:\Program Files (x86)\CryptoSys\COM` on a 64-bit machine.

    If you are distributing to end users you need to ensure this DLL is registered.  It does not self-register.
    To register manually, copy the `diCryptOCX.dll` to a convenient folder on the target machine, 
    open a command prompt 'as administrator',
    and type

    ```

    REGSVR32 myfolder\diCryptOCX.dll

    ```

    You must have administrative privileges. 
    With NSIS, use the `RegDLL` instruction but make sure the core `diCryptoSys.dll` is installed first.
    For more information on installation and possible errors, please read the file **ActiveXreadme.txt** in the COM folder of the distribution.

For more information on the executables, see [Technical Details](#technicaldetails).

### <a id="win64platform"></a>Win64 (X64) Platform

A separate version of **`diCryptoSys.dll`** is provided which is compiled for X64 platforms.
If it detects a 64-bit machine, the installation program will install both the Win32 and Win64 core DLLs in the correct system directories.
The default directory for all other files will be `C:\Program Files (x86)\CryptoSys`.
Copies of files specific for 64-bit platforms are installed in `C:\Program Files (x86)\CryptoSys\X64`.
Please refer to our web page [Using CryptoSys on a 64-bit system](https://cryptosys.net/64bit.html "External link") for more details.

The .NET Library DLL is compiled for both platforms. 
When compiling your .NET project in MS Visual Studio, make sure you set **Solution Platforms** to **Any CPU**.

The ActiveX DLL is only for Win32 platforms.

### <a id="detectingplatform"></a>Detecting Win32 or X64 platform

This test returns 1 if the core DLL is Win64 (X64) or 0 if Win32:

[`C#`]

```

int n = General.IsWin64();	

```

[`VB.NET`]

```

n = General.IsWin64()	

```

[VB6/VBA]

```

Dim nRet As Long
nRet = API_LicenceType(API_GEN_PLATFORM)

```

[C/C++]

```

long nRet;
nRet = API_LicenceType(API_GEN_PLATFORM);

```

To get the platform as a string, either `"Win32"` or `"X64"`, do this:

```

string s = General.Platform();	

```

```

s = General.Platform()

```

[VB6/VBA]

```

Dim nLen As Long
Dim strPlatform As String
nLen = API_ModuleName("", 0, API_GEN_PLATFORM)
strPlatform = String(nLen, " ")
nLen = API_ModuleName(strPlatform, Len(strPlatform), API_GEN_PLATFORM)

```

```

char buf[6];
nRet = API_ModuleName(buf, sizeof(buf)-1, API_GEN_PLATFORM);

```

Remember, the "platform" these tests show is the platform of the core DLL that the system is using. 
WoW64 (*Windows-on-Windows 64-bit*) manages 64-bit and 32-bit applications transparently on a Windows 64-bit operating system.

[[Contents](#topofpage)] [[Index](#index)]

<a id="vb6vsvbdotnet"></a>Visual Basic or Visual Basic: VB6 vs `VB.NET`
-----------------------------------------------------------------------

When we refer to "Visual Basic" in this document we probably mean the old "classic" Visual Basic, VB6. 
This language, although very popular but now dropped by MS, is almost completely compatible with Visual Basic for Applications (VBA) 
that still comes with Microsoft Office products like MS Access and Excel.

When we refer to "`VB.NET`" we mean "Visual Basic .NET" or "Visual Basic 2010" or later. 
This is the one with the 20+ MB runtime instead of the 5 MB one for the old VB6.
Everything we do here in `VB.NET` *should* be compatible in principle with every version since it was introduced in 2002.
The .NET interface is compiled for NET 4.0 and is upwardly compatible. 

It would have been less confusing if MS had chosen a completely different name for the `VB.NET` version instead of "Visual Basic" (like, er, "Java").
The two "Visual Basic" languages look similar (too similar!), but programs need to be approached in a completely different manner, at least when using our stuff.

In CryptoSys API there is a completely different set of `VB.NET` (VB2010+) methods 
that can be called using the `VB.NET` wrapper
`diCrSysAPINet.dll`. See the sections marked **.NET Equivalent** under each function
and the [.NET Help File](#dotnethelp).

In general, the function **`FOO_DoThis`** in VB6 is replaced by a method **`Foo.DoThis`** in `VB.NET`.
The arguments and type of return value will be probably be different - there will be fewer arguments and the result is usually just returned directly
without any pre-dimensioning requirements.
Similarly, the same function **`FOO_DoThis`** in C/C++ is replaced by a method **`Foo.DoThis`** in C# 
which is identical to the `VB.NET` method. For a quick guide, see [Converting VB6 to `VB.NET`](#vb6tovbnet).

[[Contents](#topofpage)] [[Index](#index)]

<a id="vbain64bitoffice"></a>VBA in 64-bit versions of Office
-------------------------------------------------------------

**Note:** As of version 6.20 all the required 32- and 64-bit declarations are included in the one file module `basCryptoSys.bas`.

To use the VBA functions in this API with a 64-bit version of Microsoft Office you need to use the "PtrSafe" attribute in a declaration statement
as in this example:

```

Public Declare Function API_Version Lib "diCryptoSys.dll" () As Long   ' Original 32-BIT

```

```

Public Declare PtrSafe Function API_Version Lib "diCryptoSys.dll" () As Long   ' New 64-BIT

```

That is, add the keyword `PtrSafe` between `Public Declare` and `Function`.
	There are *no* other changes to make. 

You can use the **VBA7** conditional compilation constant, if you wish. For example.

```

#If VBA7 Then 
  Public Declare PtrSafe Function API_Version Lib "diCryptoSys.dll" () As Long
#Else 
  Public Declare Function API_Version Lib "diCryptoSys.dll" () As Long
#End If	

```

This is what we now do. In some IDEs, like the old VB6, one set may appear red. It's unsightly, but does not prevent compilation.

AFAWK there is no need to use the **Win64** constant.
You *do not* change any types to `LongLong` or `LongPtr`.	

For more information, see the Microsoft Developer Network page
[Compatibility Between the 32-bit and 64-bit Versions of Office 2010](https://msdn.microsoft.com/en-us/library/ee691831 "External link").

[[Contents](#topofpage)] [[Index](#index)]

<a id="generalprogramming"></a>General Programming Issues
---------------------------------------------------------

* [Storing and representing ciphertext](#storingciphertext)
* [Converting strings to bytes and vice versa](#stringstobytes)
* [Hexadecimal versus Bytes](#hexvsbytes)
* [Return Values](#ReturnValues)

### <a id="storingciphertext"></a>Storing and representing ciphertext

> Ciphertext is not text!

The input to and output from an encryption function is, strictly speaking, a **bit string**.
A `bit string' is an ordered sequence of `bits', each of value either `0' or `1'.
There isn't a convenient `bit string' type in the usual programming languages so we use
an ordered sequence of `bytes' instead, 8 bits to one **byte**, 
and we almost always choose to work with values that are
an exact multiple of 8 like 64 bits or 256 bits to make life easier.

The input to an encryption function is usually a representation of a text string like "Hello world!".
Different systems store text in different ways. You need to convert the text to an unambiguous sequence of
bytes before you encrypt it. For ECB and CBC modes you need to add padding bytes as well to ensure the input block
is an exact multiple of the cipher block size.

> Do not store ciphertext bytes in a string.

Once encrypted, the output is another sequence of bytes known as **ciphertext**. This sequence of bytes
is generally not printable - it shows up as garbage. 
You can safely save this sequence of bytes directly to a binary file. It's often more convenient to encode the
ciphertext bytes into a hexadecimal or base64 string, which is much easier to handle.
But you *do not* convert the ciphertext back to text. It won't work.

When decrypting, after you've deciphered the ciphertext back to **plaintext**, you still have a sequence of bytes. 
You need to convert these bytes back to a string of text before you can read it, provided your decryption was successful.

Use the functions below to convert a string of text to an unambiguous array of bytes and vice versa.

### <a id="stringstobytes"></a>Converting strings to bytes and vice versa

In **VB6/VBA**, use the `StrConv` function.

```

Dim abData() As Byte
Dim Str As String
Dim i As Long
Str = "Hello world!"
' Convert string to bytes
abData = StrConv(Str, vbFromUnicode)
For i = 0 To UBound(abData)
    Debug.Print Hex(abData(i)); "='" & Chr(abData(i)) & "'"
Next
' Convert bytes to string
Str = StrConv(abData, vbUnicode)
Debug.Print "'" & Str & "'"

```

```

48='H'
65='e'
6C='l'
6C='l'
6F='o'
20=' '
77='w'
6F='o'
72='r'
6C='l'
64='d'
21='!'
'Hello world!'

```

In **`VB.NET`** use `System.Text.Encoding`.

```

Dim abData() As Byte
Dim Str As String
Dim i As Long
Str = "Hello world!"
' Convert string to bytes
abData = System.Text.Encoding.Default.GetBytes(Str)
For i = 0 To UBound(abData)
    Console.WriteLine(Hex(abData(i)) & "='" & Chr(abData(i)) & "'")
Next
' Convert bytes to string
Str = System.Text.Encoding.Default.GetString(abData)
Console.WriteLine("'" & Str & "'")

```

You could be more explicit by replacing `.Default` with `.GetEncoding(1252)`,
and then use the appropriate code page for your character set (1252 is Western European).

In **C#**, use `System.Text.Encoding`, which has identical behaviour to the function in `VB.NET`.

```

byte[] abData;
string Str;
int i;
Str = "Hello world!";
// Convert string to bytes
abData = System.Text.Encoding.Default.GetBytes(Str);
for (i = 0; i < abData.Length; i++)
{
	Console.WriteLine("{0:X}", abData[i]);
}
// Convert bytes to string
Str = System.Text.Encoding.Default.GetString(abData);
Console.WriteLine("'{0}'", Str);

```

In **C and C++**, the distinction between a string and an array of bytes is often blurred.
A string is a zero-terminated sequence of `char` types and
bytes are stored in the `unsigned char` type. 
A string needs an extra character for the null terminating character; 
a byte array does not, but it needs its length to be stored in a separate variable.

```

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static void pr_hexbytes(const unsigned char *bytes, int nbytes)
/* Print bytes in hex format + newline */
{
   int i;
   for (i = 0; i < nbytes; i++)
     printf("%02X ", bytes[i]);
   printf("\n");
}

int main()
{
   char szStr[] = "Hello world!";
   unsigned char *lpData;
   long nbytes;
   char *lpszCopy;

   /* Convert string to bytes */
   /* (a) simply re-cast */
   lpData = (unsigned char*)szStr;
   nbytes = strlen(szStr);
   pr_hexbytes(lpData, nbytes);

   /* (b) make a copy */
   lpData = malloc(nbytes);
   memcpy(lpData, (unsigned char*)szStr, nbytes);
   pr_hexbytes(lpData, nbytes);

   /* Convert bytes to a zero-terminated string */
   lpszCopy = malloc(nbytes + 1);
   memcpy(lpszCopy, lpData, nbytes);
   lpszCopy[nbytes] = '\0';
   printf("'%s'\n", lpszCopy);

   free(lpData);
   free(lpszCopy);

   return 0;
}
```

```

48 65 6C 6C 6F 20 77 6F 72 6C 64 21
48 65 6C 6C 6F 20 77 6F 72 6C 64 21
'Hello world!'

```

The types `char` and `unsigned char`
might be identical on your system, or they might not be.
We strongly recommend that you explictly distinguish between strings and byte arrays in your code by using
the correct type and consistently treating them differently.

If your string is a Unicode string, then it consists of a sequence of `wchar_t` types.
Converting wide-character strings to a sequence of bytes in C is more problematic.
You can either convert the Unicode string directly to a string of bytes (in which case every second byte will be zero for
US-ASCII characters), 
or use the stdlib `wcstombs` function or the Windows `WideCharToMultiByte` function
to convert to a sequence of multi-byte characters (some will be one byte long, some two)
and then convert the multi-byte string to bytes (you can do this with a simple cast).
Each party encrypting and decrypting must agree on which way to do it.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="hexvsbytes"></a>Hexadecimal versus Bytes

Most of the functions in CryptoSys API have a `Bytes' and a `Hex' version.
The **Bytes** version expects its input as an array of bytes (`unsigned char*` in C/C++) 
together with another variable that specifies the length.
The **Hex** version expects its input as a hexadecimal-encoded string consisting only of the characters [0-9A-Fa-f]
where two hex characters represent an 8-bit byte.

In all these cryptographic algorithms, the underlying operations are carried out on 8-bit **bytes** 
(sometimes referred to as **octets**).
See [Storing and representing ciphertext](#storingciphertext).

In practice, especially with VB and VBScript, you may find it more convenient to use the 'Hex' versions and pass all your data to the
API functions as hexadecimal-encoded strings. 

* Hexadecimal strings are more convenient to transfer between different operating systems without errors,
and to send in emails.
* They are easier to print.
* They can be quickly inspected when debugging.
* Most tests for cryptographic algorithms are specified in hexadecimal format.
* The Hex versions are stricter in checking the length of the input data and are safer to use 
(see [Common problems when encrypting](#commonproblems)).

Use the [`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr) 
and [`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes) functions to
convert between bytes and hexadecimal strings. 
Use the Visual Basic `StrConv` function to convert between a `String`
and an array of `Byte` values. 

See [Converting strings to bytes and vice versa](#stringstobytes).

Note that the `CNV_BytesFromHexStr` function will - by design - filter invalid hex characters 
and return the resulting bytes from whatever is left without error. 
The hex versions of the encryption functions are stricter 
and will fail if any invalid hex characters are found in the input.

If your input data is in Unicode or UTF-16 format (e.g. your operating system is set up for CJK characters),
then you are strongly recommended to convert your input data to unambiguous hexadecimal format before trying to 
use the functions in this API. 
Do not try and use the Visual Basic `String` type or it will end in tears.

For various historical reasons the Hex encryption functions return their results in **upper case** and
the hash digest functions in **lower case**. 
Just be careful if you use the case-sensitive `strcmp()` function in the C `string.h` library
or if your Visual Basic options are set to `Option Compare Binary`.

It's your decision which way you do it, but please be consistent.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="ReturnValues"></a>Return Values

All the core VB6/C functions in this API return a 32-bit signed integer value, 
that is a `Long` in VB6/VBA and a `long` in C/C++, but an `Integer` in `VB.NET`
and an `int` in C#.
The wrapper functions provided in the [.NET](#dotnetmethods) and [ActiveX](#activexmethods) 
interfaces behave differently (and more conveniently) - please
refer to the detailed documentation on those interfaces.

Functions either 

1. return zero to indicate success or a non-zero error code; or
2. return a positive value to indicate, say, a required length or CRC value, or a negative error code.

The exception is the set of `_Init` functions which return a non-zero context handle on success or *zero* if an
error has occurred. Always check the return value before continuing.
Use the `_InitError`
function to find out the code for the error that has occurred.
The value itself of the context handle is unimportant, but do *not* change its value.

[[Contents](#topofpage)] [[Index](#index)]

<a id="UsingWithVB"></a>Using with Classic Visual Basic and VBA
---------------------------------------------------------------

To call the CryptoSys API functions
from a classic Visual Basic project or VBA application, 
just add the module `basCryptoSys.bas` to your project
(VBA users should delete the first line `Attribute VB_Name = "basCryptoSys"`).

The VB6/VBA functions work in the same way as you would call the Win32 API functions from VB6.
You must use the correct variable types and must pre-dimension strings and byte arrays that are to receive
output or you will suffer the wrath of the great god Gee-pee-eff.

For examples, see the test code provided in the distribution.

The module `basCryptoSys.bas` and distribution test code will be found in the VB6 sub-directory of the installation folder, typically
`C:\Program Files (x86)\CryptoSys\VB6` (or `C:\Program Files\CryptoSys\VB6` on a 32-bit machine). 

To find the installation folder, use **Start > All Programs > CryptoSysAPI > CryptoSys API Example Files**.

### <a id="predimensioning"></a>Pre-dimensioning for VB

To create a string of, say, length 40 characters, do either:

```

Dim sData As String * 40

```

or

```

Dim sData As String
sData = String(40, " ")

```

If you know the output string needs to be the same size as the input, do this:

```

Dim strInput As String
Dim strOutput As String
strInput = "......"
strOutput = String(Len(strInput), " ")

```

To create a byte array of a given length:

```

Dim abData() As Byte
Dim nLen As Long
nLen = 40
ReDim abData(nLen - 1)

```

Note that byte arrays in VBA are indexed from 0 to `nLen - 1`, but an array dimensioned as 
`abData(nLen - 1)` actually has `nLen` elements.

To create a byte array of the same length as an existing array, do this:

```

Dim lpOutput() As Byte
ReDim lpOutput(Ubound(abInput))

```

To find the length of an existing byte array:

```

nLen = UBound(abData) - LBound(abData) + 1

```

Be careful, as this will cause a run-time error if `abData()` has not been ReDim'd.
See the function `cnvBytesLen` in the VBA wrappers for a better and safer way to find the length.

### <a id="zerolengthbytearrays"></a>Zero-length byte arrays in VB6/VBA

To create a byte array with zero length do this

```

Dim abData() As Byte
abData = vbNullString	

```

There is no simple way to redimension a dynamic array that might have a zero length without risking a runtime error. 
The best you can do is as follows.

```

Dim abData() As Byte
Dim nLen as Long
' Compute required length in bytes...
nLen = ComputeLength()  ' returns length, possibly zero
If nLen > 0 Then
    ReDim Preserve abData(nLen - 1)
Else
    abData = vbNullString
End If

```

### <a id="passemptybytearray"></a>Passing a reference to an empty byte array in VB6/VBA

The equivalent in VBA/VB6 of passing a `NULL` argument in C is to use `ByVal 0&`.
Do *not* use `vbNull`. `vbNull` is not the VBA equivalent of `NULL` in C§.

For example, given the following definition 

```

Public Declare Function FOO_Bar Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ...) As Long

```

the correct way to pass a "NULL" pointer for parameter *lpOutput* is as follows

```

nRet = FOO_Bar(ByVal 0&, 0, ...)	' Strictly correct	

```

In this library, it is generally sufficient to set *nOutBytes* to be 0 and the corresponding *lpOutput* argument will be ignored.
So the following is sufficient.

```

nRet = FOO_Bar(0, 0, ...)	' OK

```

§ We admit we have used `vbNull` in examples for years, believing it to be the equivalent of `NULL` in C.
Fortunately none of the examples caused a problem because if the length is also set to zero then it is ignored.
This manual has now been edited to suit.	

**Note:** Passing a null (empty) array to a VBA *wrapper* function is different, e.g. [`cipherEncryptBytes`](#VB_cipherEncryptBytes),
where the parameter is of type `lpInput() As Byte`.
See [Empty byte arrays](#emptybytearrays) for VBA wrappers below.

### <a id="vb6vbaotherissues"></a>Other Issues For VB6/VBA Users

* VB6/VBA 16-bit **`Integer`** and 64-bit **`LongLong`** types are *never* used in CryptoSys API.
Only 32-bit **`Long`** types are used.
* If you get an error of the form

    ```

    Compile error: ByRef argument type mismatch

    ```

    it means you have omitted the "(0)" after a Byte parameter, e.g.

    ```

    Dim abData() As Byte
    ' ...
    nRet = CRC_Bytes(abData, nBytes, 0)    ' WRONG: compile error

    ```

    ```

    nRet = CRC_Bytes(abData(0), nBytes, 0) ' CORRECT

    ```

[[Contents](#topofpage)] [[Index](#index)]

### <a id="notesonvbawrapperfunctions"></a>Notes on VBA wrapper functions

Use the [VBA wrapper functions](#vbawrapperfunctions) to avoid the pre-dimensioning issues for functions that output to a string or byte array.

*New in [v6.20]:* All VBA wrapper functions and definitions are now in the one file `basCryptoSys.bas`.
The file `basCryptoSysWrappers.bas` is withdrawn and must not be used with v6.20 and above.

No need to make a first pass to find the required length, or pre-dimension the output variable using `String(nChars, " ")` or `ReDim lpOutput(nBytes-1)`,
and then call again (a potentially dangerous sequence of events).
The wrapper functions do it all in one line.

```

Dim nChars As Long
Dim strModuleName As String

' The old long way...
nChars = API_ModuleName("", 0, 0)
Debug.Assert nChars > 0
strModuleName = String(nChars, " ")
nChars = API_ModuleName(strModuleName, nChars, 0)
Debug.Print strModuleName   ' C:\WINDOWS\SYSTEM32\diCryptoSys.dll

' The new one-liner with a wrapper function
strModuleName = apiModuleName()
Debug.Assert Len(strModuleName) > 0

```

If the core VBA function name is `FOO_FuncName()`, then the wrapper function will be `fooFuncName()`.

The function `fooFuncName()` will return the output as a string or byte array directly.

If an error occurs, the result will be a zero-length string or array.
Use the [`API_ErrorCode`](#API_ErrorCode) function to get more information.

#### Byte array variables

Wrapper functions that output to a byte array return the array directly. No need to ReDim. Input byte arrays are passed directly *without needing the `(0)`*
and without needing to compute the length beforehand.

```

' The old way - we need all the byte array lengths
Dim lpKey() As Byte
Dim lpIV() As Byte
Dim lpPlain() As Byte
Dim lpCipher() As Byte
Dim nBytes As Long
Dim nDataLen As Long
Dim nKeyLen As Long
Dim nIvLen As Long
' Set values for lpPlain, lpKey, lpIV [cut]
nDataLen = cnvBytesLen(lpPlain)
nKeyLen = cnvBytesLen(lpKey)
nIvLen = cnvBytesLen(lpIV)
nBytes = CIPHER_EncryptBytes(ByVal 0&, 0, lpPlain(0), nDataLen, lpKey(0), nKeyLen, lpIV(0), nIvLen, "Aes128/CBC/OneAndZeroes", 0)
Debug.Assert nBytes > 0
ReDim lpCipher(nBytes - 1)
nBytes = CIPHER_EncryptBytes(lpCipher(0), nBytes, lpPlain(0), nDataLen, lpKey(0), nKeyLen, lpIV(0), nIvLen, "Aes128/CBC/OneAndZeroes", 0)

```

With wrapper function:

```

lpCipher = cipherEncryptBytes(lpPlain, lpKey, lpIV, "Aes128/CBC/OneAndZeroes", 0)

```

That's 4 extra variables we don't need, and seven lines of code is reduced to one. 
Note the `(0)` needed in the raw function, e.g. `lpPlain(0)`, is *not* required with the wrapper function.

#### <a id="emptybytearrays"></a>Empty byte arrays

```

' To pass a "null" (empty) byte array, assign `vbNullString` to the variable.
Dim lpIV() As Byte
lpIV = vbNullString   ' Set to empty array
lpCipher = cipherEncryptBytes(lpPlain, lpKey, lpIV, "Aes128/ECB", 0)

```

**Note:** you *must* use a proper variable to pass an empty array with a wrapper function. And if you need to pass two empty arrays, you must use two independent variables.
For example:

```

' Separate independent empty arrays
lpPT = vbNullString  
lpAAD = vbNullString
lpCT = aeadEncryptWithTag(lpPT, lpKey, lpNonce, lpAAD, API_AEAD_ASCON_128A)

```

To pass an empty **String** variable you can simply use either the empty string `""` or `vbNullString`.

```

' To pass a "null" IV in hex, just use the empty string
strCipherHex = cipherEncryptHex(strPlainHex, strKeyHex, "", "Aes128/ECB", 0)

```

```

' Or pass vbNullString directly
strCipherHex = cipherEncryptHex(strPlainHex, strKeyHex, vbNullString, "Aes128/ECB", 0)

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="UsingWithC"></a>Using with ANSI C
----------------------------------------

To use the "core" ANSI C interface, include the `diCryptoSys.h` file with your source code
and link with the `diCryptoSys.lib` library. The only non-ANSI C requirement
is that your complier supports the `__stdcall`  
calling convention to call native API functions from a Windows native DLL. 
The sample C code `TestAPI.c` provided in the distribution (formerly `API_Examples.c`) carries out a variety
of tests using known test vectors. There are examples given for each function.

The "core" VB6/VBA functions and ANSI C functions are identical in form. 
The function names are identical, the arguments are the same 
(even though we may have used different parameter names in the VBA and C syntaxes),
and the same warnings given in the Remarks section apply to both.
Just be careful to add an extra character for output string types in C.

### <a id="typeconversions"></a>Type Conversions

The following type conversions apply:-

| Visual Basic | C/C++ |
| --- | --- |
| `ByVal x As String` | `char *x` |
| `ByRef x As Byte` | `unsigned char *x` |
| `ByVal x As Long` | `long x` |

Earlier versions used the `Boolean` type for the *bEncrypt* variable. This has been
changed [*Version 4.0*] in the Declarations to take a 32-bit `Long` type, 
which still works in VB6 even if the variable passed has been dimensioned as a `Boolean` type,
so this should not break any existing code.
We recommend that you use the defined constants `ENCRYPT` and `DECRYPT` in your VB6 and C code.

### <a id="compilingwithc"></a>Compiling with C

Here is some minimal code:-

```

/* myapisource.c */
#include <stdio.h>
#include "diCryptoSys.h"
int main()
{	
  char *message = "abc";
  long ret;
  char digest[API_SHA1_CHARS + 1]; 
  ret = SHA1_StringHexHash(digest, message);
  printf("SHA1(%s)=\t%s\n", message, digest);
  printf("Correct =\t%s\n", "a9993e364706816aba3e25717850c26c9cd0d89d");
  return 0;
}

```

To create myapisource.exe with MSVC++:

```

cl myapisource.c diCryptoSys.lib

```

Running this program should result in

```

SHA1(abc)=      a9993e364706816aba3e25717850c26c9cd0d89d
Correct =       a9993e364706816aba3e25717850c26c9cd0d89d

```

### <a id="borlandc"></a>Using With Borland C++

The lib file distributed with the program is made using MSVC. With Borland you need to generate
a new .lib file directly from the DLL using the IMPLIB utility:

```

implib diCryptoSys.lib diCryptoSys.dll

```

To compile with Borland C++:

```

bcc32 myapisource.c diCryptoSys.lib

```

### <a id="cautionsforcusers"></a>Cautions for C/C++ Users

* Apply the same rules to these API functions as you would when calling Win32 API functions.
* As a C programmer, you'll be familiar with dimensioning your output variables correctly before 
writing to them or suffering the consequences.
The same rules apply here.
* Remember that output `char` strings require an *extra* char for the NUL terminating
character, so add one more to the size a VB programmer would use

    (see [C/C++ users must add one to this value](#cusersaddone))

    For example

    ```

    char sDigest_sha1[41]; /* SHA-1 digest is 40 hex chars plus NUL */
    char sDigest_sha2[65]; /* SHA-256 digest is 64 hex chars plus NUL */

    ```

    or

    ```

    #include <stdlib.h>
    char *buf;
    buf = malloc(API_MAX_HASH_CHARS + 1);
    /* ... */
    free(buf);

    ```

We recommend using the defined constants like `API_SHA1_CHARS`
and `API_SHA1_BYTES` rather than hard-coded numbers, e.g.

```

char sDigest_sha1[API_SHA1_CHARS + 1]; 

```

See the constants in `diCryptoSys.h`.

For examples, see the test code `TestAPI.c.c` and `APICheck.c`
provided in the distribution.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="cusersaddone"></a>ANSI C users must add one to this value...

The VBA examples in this manual use the VBA String() function to pre-dimension a string output buffer,
where `nChars` is number of characters to be written to the output string.

```

Dim strOutput As String          ' VBA string type
strOutput = String(nChars, " ")  ' Len(strOutput) = nChars

```

> **IMPORTANT:** *ANSI C users must add one to this value when allocating memory.*

```

char *szOutput;                 // C string type
// nChars = number of characters required in output string
szOutput = malloc(nChars + 1);  // add one to the number of characters

```

Note that this is only for a C **string** type (`char *szOutput`). 
For **byte** arrays, (`unsigned char *lpOutput`), use the exact number of bytes in your C/C++ code.

```

Dim lpOutput() As Byte      ' VBA byte array type
ReDim lpOutput(nBytes - 1)  ' VBA array of exactly nBytes (0..nBytes-1)

```

```

unsigned char *lpOutput;    // C byte array type
// nBytes = number of bytes required in output byte array
lpOutput = malloc(nBytes);  // exact number of bytes

```

<a id="UsingWithCpp"></a>Using with C++ (STL)
---------------------------------------------

The C++ (STL) interface to the CryptoSys API is an interface to `diCryptoSys.dll` for C++ programmers using STL (C++11 or above).

Required files to compile in a C++ project:

```

crsysapi.hpp
diCryptoSys.h
crsysapi.cpp
  #include "diCryptoSys.h"
  #include "crsysapi.hpp"
{main}.cpp
  #include "crsysapi.hpp"
  int main() { ... }

```

You must link to `diCryptoSys.lib`. In MSVC++ IDE, use `Project > Properties > Linker > Input > Additional Dependencies`
 and add the full path to `diCryptoSys.lib`. E.g.

```
Additional Dependencies = $(OutDir)diCryptoSys.lib;%(AdditionalDependencies)

```

Using the command-line with MSVC:

```
CL test.cpp crsysapi.cpp /link ..\Debug\diCryptoSys.lib

```

Using GCC (make sure the DLL has been compiled for target X64):

```
g++ -std=c++11 test.cpp crsysapi.cpp "C:\fullpath\to\x64\Debug\diCryptoSys.lib"

```

Here is a simple C++ (STL) program for testing.

```

#include <iostream>
#include "crsysapi.hpp"
int main()
{
    std::cout << "Gen::Version=" << crsysapi::Gen::Version() << std::endl;
}

```

See the  detailed on-line [programmer's reference](https://cryptosys.net/cppapi/html/index.html "External link").

**Note:** Almost all C++ methods are static and can be called directly without creating any object. 
Those few methods that do need an object only use them to keep state between Init/Update/Final calls.
These objects are not intended to be used for inheritance or any other clever OO stuff. Only create and use one at a time.

<a id="UsingWithDotNet"></a>Using with .NET: C# and `VB.NET`
------------------------------------------------------------

To use the .NET interface with C# and `VB.NET` (VB2010+):

1. Copy the dotnet `diCrSysAPINet.dll` library file into a convenient folder.
2. In your application, add a reference to the library:

    1. **Project** > **Add Reference**.
        2. In the .NET tab, click on the **Browse** button to find and select the library file 
        			`diCrSysAPINet.dll`.

        3. Click on **OK** and the wizard will add the reference of the class library to your project.
3. Add the line (for C#)

    ```

    using CryptoSysAPI;

    ```

    or (for `VB.NET`)

    ```

    Imports CryptoSysAPI

    ```

    to your code.

4. Call the methods in the various classes.
Note that the methods in the .NET interface may have different parameters and return values 
to the functions in the core VB6/C DLL.

    * See the [List of .NET Methods](#methodlist) for details of syntax and usage.
        * More complete details are in the supplementary [.NET Help File](#dotnethelp).
        * To find the equivalent .NET method for a VB6 function, see [Cross-reference between Functions and .NET Methods](#xrefdotnet).
        * For a quick guide to converting VB6 code to `VB.NET`, see [Converting VB6 to `VB.NET`](#vb6tovbnet)

Alternatively, with C#, you can just include the source code module `CryptoSysAPI.cs` in your project
and there is no need to reference or use the class library DLL.

Note that you must also have the core Win32 (or X64) executable `diCryptoSys.dll` installed on your system
for the .NET interface to work. If not, it will throw an exception immediately:

```

Unhandled Exception: System.DllNotFoundException: 
Unable to load DLL 'diCryptoSys.dll': 
The specified module could not be found. 
(Exception from HRESULT: 0x8007007E)

```

If you are working on a 64-bit system, Visual Studio will go looking for the 64-bit core DLL in the Windows system folder 
(usually `C:\Windows\System32`). 
Make sure you set the **Solution Platform** to be **Any CPU**.

The .NET class library `diCrSysAPINet.dll` is compiled for all platforms (Win32 and X64) and 
requires at least .NET 4.0 and should be upwardly compatible with all later .NET versions.
This means that you must be using VS2010 or later.

There are two different types of methods used in the .NET interface:-

1. A simple static method. These carry out the cryptographic operation with the
given parameters and return the result in a "one-off" operation. These are the simplest
methods to use and are recommended in all environments if you know in advance what
your data consists of.
2. An "incremental" interface using object-oriented Init/Update/Dispose methods that create an instance and allow
the user to add data continuously in blocks of any (valid) length. 
Use these methods when your data is not available in one chunk and you need to operate on streaming data.

 
We recommend that you use the static "one-off" methods unless you really have to deal with streaming data of unknown length.

For examples, see the test code `TestAPIcsharp.cs` and `TestAPIvbnet.vb`
provided in the distribution.

If you need to convert existing VB6 code, see [Converting VB6 to `VB.NET`](#vb6tovbnet).

### <a id="bitwiseoptions"></a>Combining bitwise options

To combine bitwise options in .NET, use the bitwise OR operator.

With VB use `Or`

```

CipherFileOption.PrefixIV Or CipherFileOption.LeavePadding

```

With C# use `|`

```

CipherFileOption.PrefixIV | CipherFileOption.LeavePadding

```

[[Contents](#topofpage)] [[Index](#index)]

### <a id="vb6tovbnet"></a>Converting VB6 to `VB.NET`

To use CryptoSys API in `VB.NET`, you call .NET methods instead of VB6 functions.
In almost all cases, a VB6 function like `FOO_Barbaz` is replaced by the .NET method `Foo.Barbaz`.
The .NET methods generally have fewer parameters and different return values than the equivalent VB6 function.
See the [List of .NET Methods](#methodlist) and 
[Cross-reference between Functions and .NET Methods](#xrefdotnet).

`Long` types in VB6 *must* be changed to `Integer` in `VB.NET`. 
All integers in CryptoSys API are 32-bit signed integers.
You will get an exception or garbage results if you use a `VB.NET` `Long` type.

Functions that in VB6 would have output to a pre-dimensioned string or byte array will return that string or byte array directly in `VB.NET`.
For such methods in `VB.NET`, an error condition is indicated by returning an empty string or byte array. 

VB6/VBA

```

ReDim abDigest(API_MAX_HASH_BYTES - 1)
nRet = HASH_Bytes(abDigest(0), API_MAX_HASH_BYTES, abMessage(0), nMsgLen, API_HASH_MD5)

```

`VB.NET`

```

abDigest = Hash.BytesFromBytes(abMessage, HashAlgorithm.Md5)

```

Annotated example:

VB6/VBA

```

 1 Debug.Print "Testing HASH_HexFromHex ..."
 2 Dim strDigest As String
 3 Dim nRet As Long
 4 Dim strData As String
 5 strDigest = String(API_SHA1_CHARS, " ")
 6 strData = "616263"
 7 nRet = HASH_HexFromHex(strDigest, Len(strDigest), strData, API_HASH_SHA1)
 8 Debug.Print strDigest

```

Comments:

* *Line 5:* Need to pre-dimension the output string `strDigest` or else!
* *Line 7:* Integer error code is returned: `nRet = 0` indicates success (for this function).
* *Line 7:* Use `API_HASH_SHA1` flag to specify hash algorithm option.

Output

```

Testing HASH_HexFromHex ...
a9993e364706816aba3e25717850c26c9cd0d89d

```

`VB.NET`

```

 1 Console.WriteLine("Testing HASH_HexFromHex ...")
 2 Dim strDigest As String
 3 ''Dim nRet As Integer
 4 Dim strData As String
 5 ''strDigest = String(API_SHA1_CHARS, " ")
 6 strData = "616263"
 7 strDigest = Hash.HexFromHex(strData, HashAlgorithm.Sha1)
 8 Console.WriteLine(strDigest)

```

Comments:

* *Line 3:* Integer error code is not used.
* *Line 5:* No need to pre-dimension the output string.
* *Line 7:* Output is returned directly as a string: `strDigest.Length > 0` indicates success.
* *Line 7:* Use `HashAlgorithm` property to specify hash algorithm option.

Most methods in `VB.NET` are "all-in-one" stateless methods and so do not require the creation of an object. 
These are called in a one-off manner.
The incremental stateful functions in VB6 that use a context handle (those created by an Init function and closed by a Final function) 
are replaced in `VB.NET` by objects that must be instantiated and then disposed of.
Be careful with error conditions because the VB6 Init functions return zero on error, 
but the `VB.NET` Init methods return either True or zero on success.

VB6/VBA

```

Dim hContext as Long
hContext = FOO_Init(...)
If hContext = 0 Then
    nError = FOO_InitError()
    ...
End If
For i = 1 To n
    nRet = FOO_Update(hContext, abBlock(0), nBlockLen)
Next
nRet = FOO_Final(hContext)

```

`VB.NET`

```

Dim oFoo As Foo = Foo.Instance()
nRet = oFoo.InitEncrypt(...)
If nRet <> 0
    nError = oFoo.ErrCode
    ...
End If
For i = 1 To n
    abBlock = oFoo.Update(abBlock)
End If
oFoo.Dispose()

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="UsingWithASP"></a>Using with COM/ASP
-------------------------------------------

The file `diCryptOCX.dll` is a ActiveX wrapper for 32-bit platforms that provides an interface to most functions in the
CryptoSys API.
Strictly it's an ActiveX DLL, not an OCX, but we think three-letter acronyms with an "X" in them are cool.

The ActiveX DLL must be registered on the system. If not, you will receive a
"Run-time error '429': ActiveX component can't create object" error.
For more information, see the [Installation](#installation) section under the heading "Wrapper DLLs".

In a VB6 project set a reference to `diCryptOCX.dll`
(Project>References>Browse...) then

```

Dim oGen = New diCryptoOCX.gen
Debug.Print "Version=" & oGen.Version

```

In a 32-bit Office VBA module

```

Dim oGen As Object
Set oGen = CreateObject("diCryptOCX.gen")
Debug.Print "Version=" & oGen.Version

```

In an ASP page

```

Dim oGen
Set oGen = Server.CreateObject("diCryptOCX.gen")
Response.Write "Version=" & oGen.Version

```

Refer to the syntax and details of the [classes and methods of the ActiveX interface](#activexmethods).

**Note:** Almost all the COM/ASP methods require the data to be encoded in hexadecimal. 
Handling byte array types in VBScript is fraught with problems so we don't even offer the option.

For examples, see the test code `apiocxtests.asp` and other ASP test pages 
provided in the distribution (look in the folder `C:\Program Files\CryptoSys\COM`).

[[Contents](#topofpage)] [[Index](#index)]

<a id="helloworld"></a>"Hello world" programs
---------------------------------------------

The equivalent of the "Hello world" program for CryptoSys API is to call the
`[API_Version](#API_Version)` function or [`General.Version`](#M_General_Version) method. 
If this works, it demonstrates that the API is properly installed.
Here is some example source code in VB6, C, C#, `VB.NET` and ASP, respectively.

```

Public Sub ShowVersion()
   Dim nRet As Long
   nRet = API_Version()
   Debug.Print "Version=" & nRet
End Sub

```

```

#include <stdio.h>
#include "diCryptoSys.h"
int main(void) 
{
   long version;
   version = API_Version();
   printf("Version=%ld\n", version);
   return 0;
}

```

```

#include <iostream>
#include "crsysapi.hpp"
int main()
{
  std::cout << "Gen::Version=" << crsysapi::Gen::Version() << std::endl;
}

```

```

using System;
using CryptoSysAPI;
class Program {
  static void Main() {
    int n = General.Version();
    Console.WriteLine("Version = {0}", n);
  }
}

```

```

Imports CryptoSysAPI
Module Module1
  Sub Main()
    Dim n As Integer
    n = General.Version()
    Console.WriteLine("Version = {0}", n)
  End Sub
End Module

```

```

<%
   Dim oGen
   Set oGen = Server.CreateObject("diCryptOCX.gen")
   Response.Write "Version=" & oGen.Version & Chr(13) & Chr(10)
%>

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="commonproblems"></a>Common problems when encrypting
----------------------------------------------------------

The requirements for input to the block encipher functions (AES, DES, Triple DES and Blowfish) are quite strict.

**Input Data:** Input data to the block encipher functions in ECB or CBC mode
*must* be an exact multiple of the block length (16 bytes for AES, 8 bytes for the others)
or the functions will return an error. It is the user's responsibility to provide padding where necessary and 
to remove the padding after decryption. Failure to do this will result in a `BAD_LENGTH_ERROR`:-

```

Data not a valid length
Input not multiple of 8 bytes long
Input not multiple of block size

```

See [Padding](#padding) for more guidance on preparing your plaintext for encryption.

This rule on input lengths does not apply to the file encryption functions which automatically provide their own padding. 

**Keys and IV:** All the keys and initialization vectors provided in hex format *must* be of the exact required length 
or the function will return a `BAD_KEY_LEN_ERROR` or `BAD_IV_ERROR`:-

```

Invalid key length
Invalid initialization vector
Invalid IV length

```

There are no checks made on the lengths of keys and IVs provided in byte format for most of the block cipher functions; 
it is assumed you have done it correctly.
So please make sure you provide byte arrays of the correct lengths. The result is "undefined behaviour" if you don't, where
"undefined behaviour" has the lovely meaning used in the ANSI standard for C; 
namely, it might be ignored, do something unpredicatable, or your program may crash.
"Nuffink to do wiv us, mate." 
Either way, you will not get the output you expected.

Note also that the `CNV_BytesFromHexStr` function will - by design - filter invalid hex characters and return
the resulting bytes from whatever is left without error. The hex versions of the encryption functions are stricter and will
fail if *any* invalid hex characters are found in the input parameters. 
See [Hexadecimal versus Bytes](#hexvsbytes) for more details of the hex conversion functions.

[[Contents](#topofpage)] [[Index](#index)]

<a id="cipheralgmode"></a>Specifying the algorithm and mode for generic block cipher functions
----------------------------------------------------------------------------------------------

The generic block cipher functions allow the block cipher algorithm and
mode to be specified 
*either* by a *szAlgAndMode* string *or* by using the *nOptions* flags, but not both.
The algorithm-and-mode parameter string combines the name of the block cipher algorithm and the mode, for example `"tdea-cbc"`
or `"aes128-ctr"`. Only Triple DES (TDEA) and the three AES algorithms (AES-128, AES-192 and AES-256) are provided with 
the generic cipher functions.

Valid algorithm names are:

| Value | Algorithm | Option |
| --- | --- | --- |
| `tdea` | Triple DES, a.k.a. 3DES, des-ede3 | `API_BC_TDEA` |
| `aes128` | AES-128 | `API_BC_AES128` |
| `aes192` | AES-192 | `API_BC_AES192` |
| `aes256` | AES-256 | `API_BC_AES256` |

Valid mode names are:

| Value | Mode | Option |
| --- | --- | --- |
| `ecb` | Electronic Code Book mode (default) | `API_MODE_ECB` |
| `cbc` | Cipher Block Chaining mode | `API_MODE_CBC` |
| `ofb` | Output Feedback mode | `API_MODE_OFB` |
| `cfb` | 64-bit Cipher Feedback mode | `API_MODE_CFB` |
| `ctr` | Counter mode | `API_MODE_CTR` |

Some examples of valid string values for the *szAlgAndMode* parameter are:

| strAlgAndMode | Description | Alternative Option value |
| --- | --- | --- |
| `tdea-cbc` | Triple DES in CBC mode | `API_BC_TDEA+API_MODE_CBC` |
| `tdea-ecb` | Triple DES in ECB mode | `API_BC_TDEA+API_MODE_ECB` |
| `tdea` | ditto (ECB is default mode) | `API_BC_TDEA` |
| `aes128/cbc` | AES-128 in CBC mode | `API_BC_AES128+API_MODE_CBC` |
| `aes256:ctr` | AES-256 in Counter mode | `API_BC_AES2568+API_MODE_CTR` |

Punctuation and space characters and upper- and lower-case are ignored in the *szAlgAndMode* string, so 
"`tdea-cbc`",
"`TDeA---cBc`",
"`tdea cbc`", and
"`TDEACBC`" are equivalent 
(as indeed is 
"`t*D$e^A c@b!C!!`").
You can use the synonyms "3des", "des-ede" or "des-ede3" in place of "tdea".

It is an error to use both the *szAlgAndMode* and *nOptions* parameters to specify the algorithm and mode.
The cipher algorithm must be explicitly specified: there is no default algorithm. 
The default cipher mode is ECB mode, which is not recommended because of security issues. 
It is recommended to use either CBC or CTR mode with an IV value that is unique each time it is used with a given key.
Even better, use [Authenticated Encryption](#aeadalgorithms) .

### Padding

For the functions

[`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes),
[`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes),
[`CIPHER_EncryptHex`](#CIPHER_EncryptHex), and
[`CIPHER_DecryptHex`](#CIPHER_DecryptHex),

you can specify padding as well as the algorithm and mode. 
If the padding is not given, default padding will be assumed which depends on the cipher mode. 

Valid padding names are:

| Value | Padding | Option |
| --- | --- | --- |
| `nopad[ding]` | No padding is added | `API_PAD_NOPAD` |
| `pkcs5[padding]` | The padding scheme described in PKCS#5 [[PKCS5](#PKCS5)] | `API_PAD_PKCS5` |
| `oneandzeroes[padding]` | Pads with 0x80 followed by as many zero bytes necessary to fill the block | `API_PAD_1ZERO` |
| `ansix923[padding]` | The padding scheme described in ANSI X9.23 [[X9-23](#X9-23)] | `API_PAD_AX923` |
| `w3c[padding]` | The padding scheme described in W3C Recommendation for XML encryption [[XMLENC](#XMLENC)] | `API_PAD_W3C` |

So, for example, both `nopad` and `nopadding` are accepted, and so are `pkcs5` and `pkcs5padding`.

Remember that punctuation characters and case in the *szAlgModePad* string are ignored. 
The keywords must be in the correct order *algorithm-mode-padding*.
Some valid examples:

| szAlgModePad | Alternative Option value |
| --- | --- |
| `tdea/cbc/pkcs5` | `API_BC_TDEA+API_MODE_CBC+API_PAD_PKCS5` |
| `tdea/cbc/pkcs5padding` | `API_BC_TDEA+API_MODE_CBC+API_PAD_PKCS5` |
| `tdeacbcpkcs5` | `API_BC_TDEA+API_MODE_CBC+API_PAD_PKCS5` |
| `aes128-ecb-oneandzeroes` | `API_BC_AES128+API_MODE_ECB+API_PAD_1ZERO` |

[[Contents](#topofpage)] [[Index](#index)]

<a id="paddingschemes"></a>Padding schemes for block ciphers
------------------------------------------------------------

To perform encryption with a block cipher in ECB or CBC mode the length of the input to be encrypted 
*must* be an exact multiple of the block length *B* in bytes. 
For Triple DES the block length *B* is 8 bytes (64 bits) and for all AES variants it is 16 bytes (128 bits).
If the length of the data to be encrypted is not an exact multiple of *B*, it must be padded to make it so. 
After decrypting, the padding needs to be removed.

For other modes of encryption, such as "counter" mode (CTR) or OFB or CFB, padding is not required. In these cases
the ciphertext is always the same length as the plaintext, and a padding method is not applicable.

There are many, many conventions for padding. It is up to the sender and receiver of encrypted data to agree on the convention used.

The most popular is "PKCS5" padding, described in section 6.1.1 of [[PKCS5](#PKCS5)], 
which is the same as the padding method in section 6.3 of [[CMS](#CMS)], 
section 10.3 of [[PKCS7](#PKCS7)] 
and para 1.1 of [[RFC1423](#RFC1423)].

### PKCS5 Padding

If the block length is *B* then add *N* padding bytes of value *N* to make the input length 
up to the next exact multiple of *B*.
If the input length is already an exact multiple of *B* then add *B* bytes of value *B*. 
Thus padding of length *N* between one and *B* bytes is *always* added in an unambiguous manner. 
After decrypting, check that the last *N* bytes of the decrypted data all have value *N* with `1 < N ≤ B`.
If so, strip *N* bytes, otherwise throw a decryption error.

Examples of PKCS5 padding for block length *N* = 8:

```

3 bytes: FDFDFD           --> FDFDFD0505050505
7 bytes: FDFDFDFDFDFDFD   --> FDFDFDFDFDFDFD01
8 bytes: FDFDFDFDFDFDFDFD --> FDFDFDFDFDFDFDFD0808080808080808

```

### OneAndZeroes Padding

For "OneAndZeroes" Padding add a byte of value 0x80 followed by as many zero bytes as is necessary 
to fill the input to the next exact multiple of *B*.
Like PKCS5 padding, this method *always* adds padding of length between one and *B* bytes to the input before encryption. 
It is easily removed in an unambiguous manner after decryption.

The "OneAndZeroes" term comes from the fact that this method appends a 'one' bit to the input followed by as many 'zero' bits as is necessary.
The byte 0x80 is `10000000` in binary form. Note the spelling of "Zeroes", which is what everyone else seems to use.

Examples of OneAndZeroes padding for block length *B* = 8:

```

3 bytes: FDFDFD           --> FDFDFD8000000000
7 bytes: FDFDFDFDFDFDFD   --> FDFDFDFDFDFDFD80
8 bytes: FDFDFDFDFDFDFDFD --> FDFDFDFDFDFDFDFD8000000000000000

```

### ANSI X9.23 Padding

If *N* padding bytes are required (`1 < N ≤ B`) set the last byte as *N*
and all the preceding `N-1` padding bytes as zero.

Examples of AnsiX923 padding for block length *B* = 8:

```

3 bytes: FDFDFD           --> FDFDFD0000000005
7 bytes: FDFDFDFDFDFDFD   --> FDFDFDFDFDFDFD01
8 bytes: FDFDFDFDFDFDFDFD --> FDFDFDFDFDFDFDFD0000000000000008

```

### W3C Padding

As described in section 5.2.1 of the W3C Recommendation for XML encryption [[XMLENC](#XMLENC)].
If *N* padding bytes are required (`1 < N ≤ B`) set the last byte as *N*
and the preceding `N-1` padding bytes as arbitrary byte values. 

We include this method for completeness. It is similar to ISO10126 padding. 
This method is not recommended since only one padding byte is ever checked when decrypting
and this opens up security vulnerabilities. 
Note we actually use PKCS5 padding when encrypting, which is valid because the other padding bytes are 
specified as "arbitrary" and using *N* is just as arbitrary as any other value, isn't it? 

Examples of W3C padding for block length *B* = 8, where 'xy' is an arbitrary byte:

```

3 bytes: FDFDFD           --> FDFDFDxyxyxyxy05
7 bytes: FDFDFDFDFDFDFD   --> FDFDFDFDFDFDFD01
8 bytes: FDFDFDFDFDFDFDFD --> FDFDFDFDFDFDFDFDxyxyxyxyxyxyxy08

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="blockciphersizes"></a>Valid key and block sizes for block cipher algorithms
----------------------------------------------------------------------------------

| Algorithm | Key size (bytes) | Block size (bytes) | IV size (bytes) | Valid ECB/CBC data lengths |
| --- | --- | --- | --- | --- |
| Triple DES | 24 | 8 | 8 | 8, 16, 24, 32, ..., 8k, ... bytes |
| AES-128 | 16 | 16 | 16 | 16, 32, 48, 64, ..., 16k, ... bytes |
| AES-192 | 24 | 16 | 16 | 16, 32, 48, 64, ..., 16k, ... bytes |
| AES-256 | 32 | 16 | 16 | 16, 32, 48, 64, ..., 16k, ... bytes |

[[Contents](#topofpage)] [[Index](#index)]

<a id="extensionsforfiles"></a>Extensions to block cipher functions for files
-----------------------------------------------------------------------------

*[New in v4.5]* 
We have added two options to the file block cipher functions to (1) enable the IV to be embedded in the ciphertext file and (2) to allow 
the padding to be ignored when decrypting. The former option removes the requirement to send the IV separately when using
CBC, CFB, OFB or CTR modes.
The latter option can be used as a fudge to decrypt a file that has been padded in a non-standard
manner. These options are available with the *[all new in v4.5]* functions :

* [`AES128_FileExt`](#AES128_FileExt)
* [`AES192_FileExt`](#AES192_FileExt)
* [`AES256_FileExt`](#AES256_FileExt)
* [`BLF_FileExt`](#BLF_FileExt)
* [`DES_FileExt`](#DES_FileExt)
* [`TDEA_FileExt`](#TDEA_FileExt)

### Prefixing the IV

The usual behaviour of the block cipher functions that encrypt files 
(e.g. [`TDEA_File`](#TDEA_File), 
[`AES128_File`](#AES128_File), etc. and their hex variants) is just to write out the ciphertext in binary format.
All modes except ECB require a unique Initialization Vector (IV) to be used as part of the encryption process.
The IV must be of the same block length as the algorithm: 16 bytes for AES and 8 for the others.
It is the responsibility of the sender to communicate the IV used to the recipient separately by some other means.
The IV does not need to be kept secret and can be sent in the clear. 
Provided it is unique each time it is used, an IV provides extra security against cryptanalysis for similar messages encrypted with the same key.
The usual method is generate the IV at random.

An alternative convention to sending the IV by a separate channel is to prepend the IV to the ciphertext bytes in the file. 
The recipient can then extract the value of the
IV from the file itself and use this together with the secret key to decrypt the remainder. 
This relies on the sender and recipient both agreeing to use this convention.
Given the recipient knows the cipher algorithm, he can extract the correct number of bytes for the IV
(16 for AES, 8 for the others) from the beginning of the file.

```

+--------------------+---------------------------------------+
| IV (8 or 16 bytes) | Ciphertext bytes (variable length)... |
+--------------------+---------------------------------------+

```

To use this convention, add the option `API_IV_PREFIX` (or `CipherFileOption.PrefixIV` in .NET).
It must be used both when encrypting and when decrypting.

### Decrypting with non-standard padding

Files encrypted in ECB or CBC mode are automatically padded with between 1 and 8 (or 16) padding bytes to make the final length a multiple
of the block size (16 bytes for AES, 8 for the others). This form of padding is known variously as PKCS#5, PKCS#7 or CMS (see
[Padding](#padding)). It provides an unambiguous method of removing the padding when decrypting as well as a
check that the decryption has succeeded 
(if you don't find `n` bytes all of value `n` between 1 and 8 (or 16) at the end, decryption has failed).

If you need to decrypt a file that has been encrypted using a different form of padding (and there are many varieties), you should use
the `API_PAD_LEAVE` option (`CipherFileOption.LeavePadding` in .NET). 
This will leave any padding in place in the decrypted file and will prevent the usual checks being carried out on their values. 
It's then up to you to deal with any extraneous bytes you find at the end of your document.
This option only works when decrypting in ECB or CBC mode. It is ignored in all other cases.

### Example

We are encrypting the 19-byte text file containing the 19 ASCII characters "Now is the time for" using Triple DES (TDEA) in CBC mode.

```

KEY=   0123456789ABCDEFFEDCBA987654321089ABCDEF01234567
IV=    1234567890ABCDEF
PT=    N o w   i s   t h e   t i m e   f o r
PT=    4E6F77206973207468652074696D6520666F72
INPUT= 4E6F77206973207468652074696D6520666F720505050505
CIPHER=204011F986E35647199E47AF391620C5D6D85A7D8D2784CC

```

Using the default behaviour when encrypting in CBC mode, the function [`TDEA_FileExt`](#TDEA_FileExt)  
will create an output file containing the 24 bytes

```

204011F986E35647199E47AF391620C5D6D85A7D8D2784CC

```

Using the `API_IV_PREFIX` option with [`TDEA_FileExt`](#TDEA_FileExt), 
the resulting file will be the 32 bytes starting with the 8-byte IV

```

1234567890ABCDEF204011F986E35647199E47AF391620C5D6D85A7D8D2784CC

```

Doing default decryption, the output file will be
the original 19 bytes of plaintext

```

4E6F77206973207468652074696D6520666F72

```

But if we use the `API_PAD_LEAVE` option, the "plaintext" file will be the 24 bytes

```

4E6F77206973207468652074696D6520666F720505050505

```

with the 5 padding bytes (in this case each of value 0x05) left in place.
This is useful if the sender has used non-standard padding.

[[Contents](#topofpage)] [[Index](#index)]

<a id="aeadinterface"></a>An interface for Authenticated Encryption with Associated Data (AEAD)
-----------------------------------------------------------------------------------------------

The [AEAD](#AEADbyCat) functions and [Aead Class](#mx_Aead) methods 
provide [AEAD encryption and decryption](#aeadalgorithms) based on [[RFC5116](#RFC5116)].

The following AEAD algorithms are provided: 

* `AEAD_AES_128_GCM` [[NIST Special Publication 800-38D](#SP80038D)] uses Galois/Counter mode designed by McGrew and Viega [[MCGR05](#MCGR05)] with AES-128
* `AEAD_AES_256_GCM` - ditto but uses AES-256
* `AEAD_CHACHA20_POLY1305` [[RFC7539](#RFC7539)] uses the ChaCha20 stream cipher and the [Poly1305 authenticator](#poly1305algorithm).

The functions `[AEAD_Encrypt](#AEAD_Encrypt)` and `[AEAD_Decrypt](#AEAD_Decrypt)` 
provide a simple, stateless interface to do one-off computations. These two functions deal with the authenticated tag separately. 
The functions `[AEAD_EncryptWithTag](#AEAD_EncryptWithTag)` and `[AEAD_DecryptWithTag](#AEAD_DecryptWithTag)` provide one-off AEAD encryption
but append the tag to the end of the output.

If you need to process a large quantity of data in chunks, use the stateful, incremental functions 
`[AEAD_InitKey](#AEAD_InitKey)`,
`[AEAD_SetNonce](#AEAD_SetNonce)`, ...,
`[AEAD_Destroy](#AEAD_Destroy)`. 
The correct sequence to call these functions is described [below](#aeadsequence).

Note also that the `AEAD_AES_xxx_GCM` algorithms only support 128- and 256-bit AES keys
	and the IV (nonce) must be exactly 12 bytes long. If you want to use AES-GCM with AES-192 or an IV of a different length,
	use the older [GCM](#GCMbyCat) functions.

Table of parameters as defined in Section 4 of [[RFC5116](#RFC5116)] (all values in octets):

| Parameter | AES_128_GCM | AES_256_GCM | CHACHA20_POLY1305 | Description |
| --- | --- | --- | --- | --- |
| `K_LEN` | 16 | 32 | 32 | Fixed key length |
| `P_MAX` | 2^36 - 31 | 2^36 - 31 | 2^38 - 64 | Max plaintext length |
| `A_MAX` | 2^61 - 1 | 2^61 - 1 | 2^64 - 1 | Max AAD length |
| `N_MIN` | 12 | 12 | 12 | Min nonce length |
| `N_MAX` | 12 | 12 | 12 | Max nonce length |
| `C_MAX` | 2^36 - 15 | 2^36 - 15 | 2^38 - 48 | Max ciphertext length |

The tag length for all supported algorithms is 16 octets. 
Note that the maximum length of a byte array in this toolkit is limited to `2^32 - 1`.

### <a id="aeadsequence"></a>Correct sequence for AEAD incremental functions

* denotes zero or more repeats.

#### Incremental encryption pseudocode

```

InitKey(key)
{ For each packet do:
   SetNonce(nonce)
   { AddAAD(aad-chunk) }*
   StartEncrypt()
   { ciphertext-chunk <-- Update(plaintext-chunk) }*
   tag <-- FinishEncrypt()
}*
Destroy()

```

#### Incremental decryption pseudocode

```

InitKey(key)
{ For each packet do:
   SetNonce(nonce)
   { AddAAD(aad-chunk) }*
   StartDecrypt(tag-to-check)
   { plaintext-chunk <-- Update(ciphertext-chunk) }*
   (OK|FAIL) <-- FinishDecrypt()
}*
Destroy()

```

Notes on incremental mode:

* AAD data must be added in its entirety before starting to encrypt or decrypt
* When decrypting in an incremental manner, the deciphered plaintext is output in chunks as the ciphertext chunks are added.
Treat this plaintext as suspect until the `[AEAD_FinishDecrypt](#AEAD_FinishDecrypt)`
returns either `OK` or `FAIL` and throw it all away if `FAIL` is returned.
* All AEAD incremental functions return zero on success (except AEAD_InitKey). 
Using an incremental function out of sequence will return a `MISUSE_ERROR` error code.
* Calling `[AEAD_InitKey](#AEAD_InitKey)` at any time will delete any existing state ready to start again with the same key.
`[AEAD_Destroy](#AEAD_Destroy)` is similar except all state including the key is destroyed.

[[Contents](#topofpage)] [[Index](#index)]

<a id="filenamesinternational"></a>Filenames with "International" characters
----------------------------------------------------------------------------

All functions in this Toolkit that pass a filename as an argument only support filenames in single-byte "ANSI" encoding.
So ASCII and Latin-1 filenames like `abcdef.txt` and `México.xml` are OK, but a Chinese filename like 
`你好.txt` will fail.

To solve this, use a little-known hack on Windows that retrieves the short path name of a file, `GetShortPathName`. 
This was originally designed to provide an MS-DOS-compatible form of a file path where each folder name and filename is 8 characters or fewer.
So, for example, the long name 

```

C:\Test\Documents and Settings\My Documents\ForEmailWithALongNameLikeThisFolderHas\helloFileWithaLongNameToo.txt

```

reduces to something like

```

C:\Test\DOCUME~1\MYDOCU~1\FOREMA~1\HELLOF~1.TXT

```

where each component of the path name is 8 characters or fewer.

It turns out that this function will provide an ASCII-character equivalent of the name of a file in any Windows "International" UTF-16 characters.
The short name is safe to use with any function in this Toolkit that requires a filename parameter. 

Use the function [`CNV_ShortPathName`](#CNV_ShortPathName) to get a ASCII filename that will work with any function in this Toolkit. Examples:

| System Filename | ShortPathName |
| --- | --- |
| 你好.txt | `FC0F~1.TXT` |
| こんにちは世界.txt | `C001~1.TXT` |
| Приветмир.txt | `E173~1.TXT` |

The exact short path name may be different on your system. 

The file path must exist, though. So if you want to *output* to a file with a name in, say, Japanese or Chinese characters, then you must create a dummy file of the required name, get
its short path name, and then output to a file of that name, which will automatically overwrite the original dummy file.

[[Contents](#topofpage)] [[Index](#index)]

<a id="SecurityIssues"></a>Security Issues
------------------------------------------

1. The functions and methods in this toolkit provide cryptographic primitives 
intended to be used as part of a security-related application. 
It is up to you the programmer to ensure that keys, passwords and other private data are kept secret,
and to ensure that appropriate security policies and procedures are followed by end users.
2. CryptoSys API is a 32-bit (or 64-bit) dynamically linked library (DLL) 
that provides encryption services to 
applications running on Microsoft Windows® operating systems.
On Windows, it is designed for and supports multi-threaded operation.
3. In FIPS 140-2 terms, CryptoSys API is a multi-chip standalone module, 
consisting of the file `diCryptoSys.dll`.  It is intended to meet FIPS 140-2 security level 1. 
The cryptographic boundary for CryptoSys API 
is defined as the enclosure of the computer on which the cryptographic module is installed. 
As a pure software product, CryptoSys API provides no physical security by itself. 
The computer itself must be appropriately physically secured.
4. Functions that advertise that they create files will overwrite
any existing file of the same name without warning.
5. No other files, temporary or permanent, are *ever* created by this toolkit.
6. There is no communications functionality whatsoever in this module.
It will never attempt to "dial home" or make any attempt to create a communications socket.
If your firewall tells you there is an attempt
to create an internet connection, you have a virus or trojan of some sort unrelated to the
CryptoSys API module.
7. The Developer Edition makes no attempts to read or write to the Windows Registry whatsoever
under normal operations. 
However, [optional registry settings](#registrysettings) may be made 
and will be read and acted on in the unlikely event that a critical error occurs.
8. The Trial Edition creates and updates registry entries in `HKCU\Software\DI Management` 
and reads entries created in `HKLM\Software\DI Management`. 
Do not attempt to change these entries.
9. Developer Editions distributed to end users do *not* require any registry entries on the user's machine
(but see [optional registry settings](#registrysettings)).
10. The DLL carries out [self-tests](#selftests) when it is first attached to the parent Windows process including
a check on the integrity of the software module, i.e. the DLL file itself. If this fails, the module will exit the process. 
This should only happen if someone has tampered with the DLL file.
11. To check you have a valid version of the CryptoSys API executable, please check the
CRC and hash digests published on our web site.
12. VB6/VBA/C functions that write output to a string or byte array require the output to be "pre-dimensioned" first. 
Make sure any specified length matches the size of the string or a
GPF error will result. It is recommended to write simple wrapper functions to prevent such problems.
Examples are given in the Visual Basic 6 declarations modules and in the source code for the COM interface.

[[Contents](#topofpage)] [[Index](#index)]

<a id="selftests"></a>Self-Tests
--------------------------------

The module performs power-up self-tests and conditional self-tests to ensure that it is functioning properly.
*Power-up self-tests* are performed when the module is powered up, i.e. when the DLL is first attached to the 
parent Windows process. *Conditional self-tests* are performed when certain security functions are invoked.

### Power-up Self-Tests

The following power-up self-tests are performed:-

#### Cryptographic algorithm test:

* AES-128/192/256 known-answer tests
* Triple DES known-answer test
* Blowfish known-answer test
* SHA-1/224/256/384/512 known-answer tests
* MD5 known-answer test
* HMAC known-answer tests for SHA-1/224/256/384/512 and MD5
* CMAC known-answer tests for Triple DES (TDEA, DES-EDE) and AES-128/192/256
* Health check for SP800-90 RNG algorithm

#### Software integrity test:

The integrity of the software module is tested using a 32-bit error detection code (EDC). The value of this
EDC is set and stored when the module is created. 
On testing, the EDC is re-computed for the DLL module file being used and compared
with the stored value. If the values do not match, the test fails.

In addition to this automatic software integrity test, 
the integrity of the entire DLL file can be
independently verified by the user using published SHA-1 and MD5 message digest and CRC-32 values
before and after installation. 

### Conditional Tests

The following conditional tests are performed:-

#### Continuous random number generator test

When the module is first loaded or instantiated in a new thread, the RNG generates a 64-bit block which 
not used but is saved in thread-safe memory for comparison with
the next 64-bit block to be generated. Each subsequent generation of a 64-bit block is
compared with the previously generated block. The test fails if any two compared 64-bit
blocks are equal.
In addition, each time the RNG function is called it compares the first 64-bit block 
generated with the first 64-bit block generated on the previous call. The test fails if these blocks
are equal. No blocks are saved that have actually been previously output by the generator.

### Action if a self-test fails

Any failure of a power-up test or conditional test will cause the following actions to take place:

1. An error message will be logged to the event log (NT+ systems only).
2. The system will (try to) save the error message in a log file* in the same directory as the calling process
executable.
3. A message box will display on the screen.
4. The DLL will terminate the process to prevent further use of cryptographic functions.

* The error log file will be given a filename "apierr.log". If the
process does not have permissions to write to that directory, no log file will be created.

You can make settings in the machine's registry to prevent the message box displaying and to change the
destination directory of the log file. See [Optional Registry Settings](#registrysettings).
It is not possible to prevent the DLL from exiting if a critical error happens.

The user may call the power-up self-tests on demand with the [`API_PowerUpTests`](#API_PowerUpTests)
function. In the event that such an "on demand" test fails, the module will log the error event and return an error
code but will not terminate the process.

Note that the automatic self-tests fail only in exceptional circumstances. You should never see one
in practice unless the software module has been tampered with. 

[[Contents](#topofpage)] [[Index](#index)]

<a id="registrysettings"></a>Optional Registry Settings
-------------------------------------------------------

The following optional registry settings may be made to change the behaviour of the module if a critical error
occurs. 

### 

> **Disclaimer** Modifying the registry can cause serious problems that may require 
> you to reinstall your operating system. 
> We cannot guarantee that problems resulting from the incorrect use of the registry can be solved. 
> Use the information provided at your own risk.

#### Disable message boxes if a critical error occurs

The default behaviour is to display a pop-up MessageBox if a critical error occurs. 
Users running the toolkit on an unattended server or within an IIS application can disable pop-ups to prevent
problems (IIS gets a bit upset if an application displays a pop-up).
Set the value to '1' to disable pop-up messages from appearing.
Note that this will not prevent the 'first user' or expiry dialogs appearing with the Test Version.

**Key:** `[HKEY_LOCAL_MACHINE\Software\DI Management\CryptoSys\Options]`  

**Value Name:** `NoMessageBox`  

**Data Type:** REG_DWORD  

**Data:** 1 = MessageBoxes disabled, 0 = MessageBoxes enabled (default)

#### Set directory to write error log file after a critical error

The default behaviour if a critical error occurs is to try to write to an error log file in the same directory 
as the parent executable file that called the DLL. To change this directory create a REG_SZ value
of 'ErrorLogDir' in the key below and set the value to the directory you want, e.g. "C:\myfolder\subdir". 
The directory name should not have a trailing slash character.

**Key:** `[HKEY_LOCAL_MACHINE\Software\DI Management\CryptoSys\Options]`  

**Value Name:** `ErrorLogDir`  

**Data Type:** REG_SZ

#### Disable creation of error log file if a critical error occurs

To disable the creation of an error log file altogether, create
 a REG_DWORD value of 'NoErrorLog' in the key below. Set the value to '1' to disable.

**Key:** `[HKEY_LOCAL_MACHINE\Software\DI Management\CryptoSys\Options]`  

**Value Name:** `NoErrorLog`  

**Data Type:** REG_DWORD  

**Data:** 1 = Error log file disabled, 0 = Error log file enabled (default)

#### Record event log messages properly

The following registry entry is required for the Event Log messages to be recorded properly.
If this entry is not present, or the path to the DLL is wrong, the event log entries will be
of the form:

> The description for Event ID ( 8xxx ) in Source ( diCryptoSys ) cannot be found. 
> The local computer may not have the necessary registry information or message 
> DLL files to display messages from a remote computer.

For correct formatting of the message, create the REG_SZ and REG_DWORD values in the key below.
The message will still be recorded even if this entry is not present.

**Key:** `[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application\diCryptoSys]`  

**Value Name:** `EventMessageFile`  

**Data Type:** REG_SZ  

**Data:** Full path to DLL file, e.g. "C:\WINNT\system32\diCryptoSys.dll"  

   

**Value Name:** `TypesSupported`  

**Data Type:** REG_DWORD  

**Data:** 7 (0x7)

[[Contents](#topofpage)] [[Index](#index)]

<a id="technicaldetails"></a>Technical Details
----------------------------------------------

The core executable **`diCryptoSys.dll`** is a native Windows **DLL** 
compiled using Microsoft Visual C++ for both Win32 (x86) and X64 platforms (there are separate DLL files for each platform).
This type of file used to be called a **Win32 DLL**.
All programming language interfaces require this core native DLL to exist in the library search path of the user's system.
The core cryptographic functions are written in pure ANSI C with extensive internal checks for memory leaks and overflow issues.
The executable `diCryptoSys.dll` is compatible with *all* versions of Windows XP and above.
It does not require any other special libraries to work apart from the standard Win32 libraries available in *all*
modern versions of Windows. 
It is totally independent of the Microsoft Cryptographic API.

The wrapper executable **`diCrSysAPINet.dll`** is a **.NET Class Library** 
created with Microsoft Visual C# set to target Microsoft .NET Framework 4.0 and above. 
It is compiled for all target platforms: Win32 and X64. 
This requires at least .NET 4.0 and should be upwardly compatible with all later .NET versions.
It can be called from programs written in C# and `VB.NET` (aka VB2008/VB20xx). 
The .NET class library calls the functions in the core Win32 DLL using `System.Runtime.InteropServices`.
The source code for this wrapper DLL is provided in the distribution, which you can use directly in your C# projects instead of referencing the .NET DLL.
For more details on its use, see [Using with .NET](#UsingWithDotNet).

The wrapper executable **`diCryptOCX.dll`** is an **ActiveX DLL** 
created with Microsoft Visual Basic 6.0 SP6. This is for Win32 platforms only.
It calls the functions in the core Win32 DLL via `diCryptoSys.tlb`, which
is available in the ActiveX source code. The source code for this wrapper DLL is provided in the distribution.
The executable `diCryptOCX.dll` must be registered on the end-user's system using `REGSVR32.EXE`.
This is now old technology and will not be updated.
For more details on its use, see [Using with COM/ASP](#UsingWithASP).

[[Contents](#topofpage)] [[Index](#index)]

<a id="Compliance"></a>Compliance
---------------------------------

AES complies with:

* FIPS PUB 197 *Advanced Encryption Standard (AES)*
[[FIPS197](#FIPS197)].
* *AES Proposal: Rijndael*, Joan Daemen and Vincent Rijmen,
[[RIJN](#RIJN)].

Triple DES (TDEA, 3DES, des-ede3) complies with:

* NIST Special Publication 800-67
*Recommendation for the Triple Data Encryption Algorithm
(TDEA) Block Cipher* [[SP80067](#SP80067)]
* NIST Special Publication 800-20
*Modes of Operation Validation System for the Triple Data
Encryption Algorithm* [[SP80020](#SP80020)]
* ANSI X9.52-1998
*Triple Data Encryption Algorithm Modes Of Operation* [[X9-52](#X9-52)]

DES complies with these now-withdrawn standards:

* FIPS PUB 46-3,
*Data Encryption Standard (DES)*,
[[FIPS46](#FIPS46)].
* FIPS PUB 74,
*Guidelines for Implementing and Using the NBS Data Encryption Standard*,
[[FIPS74](#FIPS74)].
* FIPS PUB 81,
*DES Modes of Operation*,
[[FIPS81](#FIPS81)].

The block cipher modes of operation comply with

* NIST Special Publication 800-38A *Recommendation for Block Cipher Modes of Operation*,
[[SP80038A](#SP80038A)].

AES-GCM complies with:

* NIST Special Publication 800-38D 
*Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC*
[[SP80038D](#SP80038D)].
* *The Galois/Counter Mode of Operation (GCM)*, David A. McGrew and John Viega,
[[MCGR05](#MCGR05)].

The SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 algorithms comply with:

* FIPS PUB 180-4 *Secure Hash Standard*,
[[FIPS180](#FIPS180)].

The MD5 algorithm complies with:

* RFC 1321 *The MD5 Message-Digest Algorithm*,
[[RFC1321](#RFC1321)].

The CMAC algorithms comply with:

* NIST Special Publication 800-38B
 *Recommendation for Block
Cipher Modes of Operation:
The CMAC Mode for
Authentication*,
[[SP80038B](#SP80038B)].

The PBKDF2 algorithm complies with:

* PKCS #5 v2.1: *Password-Based Cryptography Standard*,
RSA Laboratories,
5 October 2006
[[PKCS5](#PKCS5)].

The random number generator conforms to

* NIST Special Publication 800-90A 
*Recommendation for Random Number Generation Using Deterministic Random Bit Generators* 
[[SP80090A](#SP80090A)]
* FIPS PUB 140-2, *Security Requirements For Cryptographic Modules*
[[FIPS140](#FIPS140)]
(as updated on 3 December 2002)

[[Contents](#topofpage)] [[Index](#index)]

<a id="refs"></a>References
---------------------------

* <a id="ASCON21"></a>**[ASCON21]**
*Lightweight Authenticated Encryption & Hashing*,

    <[https://ascon.iaik.tugraz.at/index.html](https://ascon.iaik.tugraz.at/index.html "External link")>
    (accessed May 2023)
* **<a id="AESAVS"></a>[AESAVS]**
Lawrence E. Bassham III,
*The Advanced Encryption Standard
Algorithm Validation Suite (AESAVS)*,
National Institute of Standards and Technology, 15 November 2002.
* <a id="AES-WRAP"></a>**[AES-WRAP]**
*AES Key Wrap Specification*,
National Institute of Standards and Technology,
16 November 2001, 
<http://csrc.nist.gov/groups/ST/toolkit/documents/kms/key-wrap.pdf>.
* **<a id="ANDE01"></a>[ANDE01]**
Ross Anderson,
*Security Engineering*,
Wiley, 2001.
* **<a id="BALE05"></a>[BALE05]**
Francesco Balena and Giuseppe Dimauro,
*Practical Guidelines and Best Practices for Microsoft Visual Basic and Visual C# Developers*,
Microsoft Press, 2005, 
ISBN 0735621721.
* **<a id="CHACHA"></a>[CHACHA]**
	 Daniel J. Bernstein, *ChaCha, a variant of Salsa20*, January 2008, <http://cr.yp.to/chacha/chacha-20080120.pdf>.
* **<a id="CHACHA-TESTS"></a>[CHACHA-TESTS]**
*Test Vectors for the Stream Cipher ChaCha*,
draft-strombergson-chacha-test-vectors-02, J. Strombergson,
<https://github.com/secworks/chacha_testvectors>, (work in progress), December 2013.
* **<a id="CHAN"></a>[CHAN]**
Mahesh Chand,
*Tutorial: Creating C# Class Library (DLL) Using Visual Studio .NET*,
<http://www.dotnetheaven.com/Uploadfile/mahesh/pr1202172006014101AM/pr12.aspx> (accessed March 2009).
* **<a id="CMS"></a>[CMS]**
[RFC 5652](https://tools.ietf.org/html/rfc5652 "External link") *Cryptographic Message Syntax (CMS)*,
R. Housley, July 2009 (formerly [RFC 3852](https://tools.ietf.org/html/rfc3852 "External link"), [RFC 3369](https://tools.ietf.org/html/rfc3369 "External link") and [RFC 2630](https://tools.ietf.org/html/rfc2630 "External link")).
* **<a id="CRCALGS"></a>[CRCALGS]**
Ross N. Williams,
*A Painless Guide To Crc Error Detection Algorithms*, 
<ftp.adelaide.edu.au/pub/rocksoft/crc_v3.txt>, 1993.
* **<a id="DRBGVS"></a>[DRBGVS]**
Timothy A. Hall,
*The NIST SP 800-90A Deterministic Random Bit Generator Validation System (DRBGVS)*,
National Institute of Standards and Technology, Updated 29 October 2015,
[DRBGVS.pdf](https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/drbg/DRBGVS.pdf "External link")
* **<a id="FERG03"></a>[FERG03]**
Niels Ferguson and Bruce Schneier,
*Practical Cryptography*,
John Wiley, 2003.
* **<a id="FIPS46"></a>[FIPS46]**
Federal Information Processing Standard (FIPS) 46-3,
*Data Encryption Standard (DES)*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
25 October 1999 (now withdrawn).
* **<a id="FIPS74"></a>[FIPS74]**
Federal Information Processing Standard 74 (FIPS PUB 74),
*Guidelines for Implementing and Using the NBS Data Encryption Standard*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
1 April 1981 (now withdrawn).
* **<a id="FIPS81"></a>[FIPS81]**
Federal Information Processing Standard (FIPS 81),
*DES Modes of Operation*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
2 December 1980 (now withdrawn).
* **<a id="FIPS140"></a>[FIPS140]**
Federal Information Processing Standards Publication
FIPS PUB 140-2 *Security Requirements for Cryptographic Modules*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
25 May 2001, updated 3 December 2002.
* **<a id="FIPS140IG"></a>[FIPS140IG]**
*Implementation Guidance for
FIPS PUB 140-2 and the Cryptographic
Module Validation Program*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
updated 26 July 2007.
* **<a id="FIPS140XC"></a>[FIPS140XC]**
*Annex C:
Approved Random Number Generators
for FIPS PUB 140-2,
Security Requirements for
Cryptographic Modules*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
19 March 2007.
* **<a id="FIPS180"></a>[FIPS180]**
Federal Information Processing Standard,
[FIPS PUB 180-4](http://dx.doi.org/10.6028/NIST.FIPS.180-4 "External link")
*Secure Hash Standard (SHS)*,
U.S. Department Of Commerce/National Institute of Standards and Technology, August 2015.
* **<a id="FIPS197"></a>[FIPS197]**
Federal Information Processing Standards Publication
[FIPS PUB 197](http://dx.doi.org/10.6028/NIST.FIPS.197 "External link")
*Advanced Encryption Standard (AES)*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
26 November 2001.
* **<a id="FIPS198"></a>[FIPS198]**
Federal Information Processing Standards Publication
FIPS PUB 198 *The Keyed-Hash Message Authentication Code (HMAC)*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
6 March 2002.
* **<a id="FIPS202"></a>[FIPS202]**
Federal Information Processing Standards Publication
[FIPS PUB 202](http://dx.doi.org/10.6028/NIST.FIPS.202 "External link")
*SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions*,
U.S. Department Of Commerce/National Institute of Standards and Technology,
August 2015.
* **<a id="FIPSSHS"></a>[FIPSSHS]**
Draft Federal Information Processing Standard,
*Descriptions of SHA-256, SHA-384, and SHA-512*,
<http://csrc.nist.gov/cryptval/shs.html>, 12 October 2000.
* **<a id="GUTM"></a>[GUTM]**
 Peter Gutmann, *Software Generation of Practically Strong
Random Numbers* presented at the 1998 Usenix Security Symposium, and the updated version
dated June 2000, both available from
<http://www.cs.auckland.ac.nz/~pgut001/>.
* **<a id="HMAC"></a>[HMAC]**
[RFC 2104](https://tools.ietf.org/html/rfc2104 "External link") *HMAC: Keyed-Hashing for Message
Authentication*, Krawczyk, Bellare and Canetti, February 1997.
* <a id="INTEL-DRNG"></a>**[INTEL-DRNG]**
Intel Corporation,
*Intel Digital Random Number Generator (DRNG) Software Implmentation Guide*, ID 658356,
Revision 2.1, October 17, 2018
([link](https://www.intel.com/content/www/us/en/developer/articles/guide/intel-digital-random-number-generator-drng-software-implementation-guide.html "External link") accessed December 2023).
* <a id="KELS98"></a>**[KELS98]**
John Kelsey, Bruce Schneier, David Wagner, Chris Hall, 
*Cryptanalytic Attacks on Pseudorandom Number Generators*, March 1998, 
available from
<http://www.schneier.com/paper-prngs.html>.
* **<a id="KOBL94"></a>[KOBL94]**
Neal Koblitz,
*A Course in Number Theory and Cryptography*,
Second Edition, Springer-Verlag, 1994.
* **<a id="MCGR05"></a>[MCGR05]**
David A. McGrew and John Viega, *The Galois/Counter Mode of Operation (GCM)*,
Revised specification, 31 May 2005,
<http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf>
(accessed March 2009).
* **<a id="MENE97"></a>[MENE97]**
 Menezes, van Oorschot and Vanstone,
*Handbook of Applied Cryptography*,
CRC Press LLC, 1997.
* **<a id="MOVS"></a>[MOVS]**
NIST Special Publication 800-17,
*Modes of Operation Validation System
(MOVS): Requirements and Procedures*,
National Institute of Standards and Technology, February 1998.
* **<a id="NISPOM"></a>[NISPOM]**
DOD 5220.22-M,
*National Industry Security Program Operating Manual (NISPOM)*,
US Department of Defense, January 1995.
* <a id="PKCS1"></a>**[PKCS1]**
PKCS #1,
*RSA Cryptography Standard*,
RSA Laboratories, Version 2.2, October 2012 (republished as [[RFC8017](#RFC8017)]).
* **<a id="PKCS5"></a>[PKCS5]**
PKCS #5,
*Password-Based Encryption Standard*,
RSA Laboratories, Version 2.1, October 2006.
See also [[RFC2898](#RFC2898)].
* **<a id="PKCS7"></a>[PKCS7]**
PKCS #7,
*Cryptographic Message Syntax Standard*,
RSA Laboratories, Version 1.5, November 1993.
See also [[RFC2315](#RFC2315)].
* **<a id="POLY1305"></a>[POLY1305]**
	Daniel J. Bernstein, *The Poly1305-AES message-authentication code*, March 2005, <http://cr.yp.to/mac/poly1305-20050329.pdf>.
* **<a id="RFC1319"></a>[RFC1319]**
[RFC 1319](https://tools.ietf.org/html/rfc1319 "External link")
*The MD2 Message-Digest Algorithm*, R. Rivest, RSA Data Security, Inc., April 1992.
* **<a id="RFC1321"></a>[RFC1321]**
[RFC 1321](https://tools.ietf.org/html/rfc1321 "External link")
*The MD5 Message-Digest Algorithm*, R. Rivest, RSA Data Security, Inc., April 1992.
* <a id="RFC1423"></a>**[RFC1423]**
[RFC 1423](https://tools.ietf.org/html/rfc1423 "External link"), 
 *Privacy Enhancement for Internet Electronic Mail: Part III: Algorithms, Modes, and Identifiers*, 
 D. Balenson, February 1993.
* **<a id="RFC1950"></a>[RFC1950]**
[RFC 1950](https://tools.ietf.org/html/rfc1950 "External link") *ZLIB Compressed Data Format Specification version 3.3*,
P.Deutsch and J-L Gailly, May 1996.
* **<a id="RFC1951"></a>[RFC1951]**
[RFC 1951](https://tools.ietf.org/html/rfc1951 "External link") *DEFLATE Compressed Data Format Specification version 1.3*,
P.Deutsch, May 1996.
* **<a id="RFC2315"></a>[RFC2315]**
[RFC 2315](https://tools.ietf.org/html/rfc2315 "External link") *Cryptographic Message Syntax Version 1.5*,
B. Kaliski, March 1998.
* **<a id="RFC2630"></a>[RFC2630]**
[RFC 2630](https://tools.ietf.org/html/rfc2630 "External link") *Cryptographic Message Syntax*,
R. Housley, June 1999. (Superseded by 
[[CMS](#CMS)] and 
[[RFC3370](#RFC3370)]).
* **<a id="RFC2898"></a>[RFC2898]**
[RFC 2898](https://tools.ietf.org/html/rfc2898 "External link") *PKCS #5: Password-Based Cryptography Specification Version 2.0*,
B. Kalinski, September 2000.
* **<a id="RFC3369"></a>[RFC3369]**
[RFC 3369](https://tools.ietf.org/html/rfc3369 "External link") *Cryptographic Message Syntax (CMS)*,
R. Housley, August 2002. (Superseded by [[CMS](#CMS)]).
* **<a id="RFC3370"></a>[RFC3370]**
[RFC 3370](https://tools.ietf.org/html/rfc3370 "External link") *Cryptographic Message Syntax (CMS) Algorithms*,
R. Housley, August 2002.
* **<a id="RFC4106"></a>[RFC4106]**
[RFC 4106](https://tools.ietf.org/html/rfc4106 "External link") *The Use of Galois/Counter Mode (GCM)
             in IPsec Encapsulating Security Payload (ESP)*,
J. Viega, D. McGrew, June 2005.
* **<a id="RFC4345"></a>[RFC4345]**
[RFC 4345](https://tools.ietf.org/html/rfc4345 "External link") *Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol*,
B. Harris, January 2006.
* <a id="RFC4648"></a>**[RFC4648]**
[RFC 4648](https://tools.ietf.org/html/rfc4648 "External link"), 
 *The Base16, Base32, and Base64 Data Encodings*, 
 S. Josefsson, October 2006.
* **<a id="RFC5116"></a>[RFC5116]**
[RFC 5116](https://tools.ietf.org/html/rfc5116 "External link") *An Interface and Algorithms for Authenticated Encryption*,
D. McGrew, January 2008.
* **<a id="RFC6229"></a>[RFC6229]**
[RFC 6229](https://tools.ietf.org/html/rfc6229 "External link") *Test Vectors for the Stream Cipher RC4*,
J. Strombergson, May 2011.
* **<a id="RFC7539"></a>[RFC7539]**
[RFC 7539](https://tools.ietf.org/html/rfc7539 "External link") *ChaCha20 and Poly1305 for IETF Protocols*.
Y. Nir, A. Langley. May 2015.
* **<a id="RFC7914"></a>[RFC7914]**
[RFC 7914](https://tools.ietf.org/html/rfc7914 "External link") *The scrypt Password-Based Key Derivation Function*.
C. Percival, S. Josefsson. 2016.
* <a id="RFC8017"></a>**[RFC8017]**
[RFC 8017](https://tools.ietf.org/html/rfc8017 "External link")
*PKCS #1: RSA Cryptography Specifications Version 2.2*.
K. Moriarty, Ed., B. Kaliski, J. Jonsson, A. Rusch. November 2016.
* **<a id="RFC8878"></a>[RFC8878]**
[RFC 8878](https://tools.ietf.org/html/rfc8878 "External link") *Zstandard Compression and the 'application/zstd' Media Type*.
Y. Collet, M. Kucherawy, Ed. Facebook. February 2021.
* **<a id="RIJN"></a>[RIJN]**
Joan Daemen and Vincent Rijmen, *AES Proposal: Rijndael*,
Document Version 2, 3 September 1999.
* **<a id="RIJNVALS"></a>[RIJNVALS]**
AES Candidate Algorithm Submissions,
*Rijndael Test values: Known Answer Tests and Monte Carlo Tests*,
<http://csrc.nist.gov/CryptoToolkit/aes/rijndael/rijndael-vals.zip>,
update 17 Feb 1998.
* **<a id="RMD"></a>[RMD]**
Antoon Bosselaers, *The RIPEMD-160 Page*,
<http://homes.esat.kuleuven.be/~bosselae/ripemd160.html>, last updated 25 August 2004.
* **<a id="SALSA20"></a>[SALSA20]**
Daniel J. Bernstein, *Salsa20 specification*, <http://cr.yp.to/snuffle/spec.pdf>.
* **<a id="SCHN96"></a>[SCHN96]**
Bruce Schneier,
*Applied Cryptography - Protocols, Algorithms and Source Code in C*,
second edition, John Wiley, 1996.
* **<a id="SHA3"></a>[SHA3]**
National Institute of Standards and Technology, U.S. Department of Commerce,
*SHA-3 Standard - Permutation- Based Hash and Extendable-Output Functions*,
[FIPS PUB 202](http://dx.doi.org/10.6028/NIST.FIPS.202 "External link")
August 2015.
* **<a id="SIMO97"></a>[SIMO97]**
Richard J Simon,
*Windows NT Win32 API SuperBible*,
Waite Group Press, 1997.
* **<a id="SP80020"></a>[SP80020]**
NIST Special Publication 800-20,
*Modes of Operation Validation System for the Triple Data
Encryption Algorithm (TMOVS): Requirements and Procedures*, 
National Institute of Standards and Technology, April 2000.
* **<a id="SP80038A"></a>[SP80038A]**
NIST Special Publication 800-38A,
*Recommendation for Block Cipher Modes of Operation: Methods and Techniques*, 
National Institute of Standards and Technology, December 2001.
* **<a id="SP80038B"></a>[SP80038B]**
NIST Special Publication 800-38B,
*Recommendation for Block
Cipher Modes of Operation:
The CMAC Mode for
Authentication*, 
National Institute of Standards and Technology, May 2005.
* **<a id="SP80038B-UX"></a>[SP80038B-UX]**
NIST Special Publication 800-38B,
*Updated CMAC Examples*, 
National Institute of Standards and Technology,
<http://csrc.nist.gov/publications/nistpubs/800-38B/Updated_CMAC_Examples.pdf>
(accessed August 2007).
* **<a id="SP80038D"></a>[SP80038D]**
NIST Special Publication 800-38D,
*Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC*,
National Institute of Standards and Technology, 
November 2007.
* <a id="SP80067"></a>**[SP80067]**
NIST Special Publication 800-67,
*Recommendation for the Triple
Data Encryption Algorithm
(TDEA) Block Cipher*,
National Institute of Standards and Technology, Version 1.1, Revised May 2008.
* <a id="SP80090A"></a>**[SP80090A]**
NIST Special Publication 800-90A,
*Recommendation for Random Number Generation Using Deterministic Random Bit Generators*,
Elaine Barker and John Kelsey,
National Institute of Standards and Technology, June 2015.
[NIST.SP.800-90Ar1](http://dx.doi.org/10.6028/NIST.SP.800-90Ar1 "External link").
* <a id="SP800185"></a>**[SP800185]**
NIST Special Publication 800-185,
*SHA-3 Derived Functions: cSHAKE, KMAC, TupleHash and ParallelHash*,
John Kelsey, Shu-jen Chang, Ray Perlner,
National Institute of Standards and Technology, December 2016.
[NIST.SP.800-185.pdf](https://doi.org/10.6028/NIST.SP.800-185 "External link").
* **<a id="STAL05"></a>[STAL05]**
William Stallings,
*Cryptography and Network Security: Principles and Practice*,
4th edition, Prentice Hall, 2005, ISBN 0131873164.
* **<a id="VIEG03"></a>[VIEG03]**
John Viega and Matt Messier, 
*Secure Programming Cookbook for C and C++*,
O'Reilly, 2003.
* <a id="WRAP-3DES"></a>**[WRAP-3DES]**
[RFC 3217](https://tools.ietf.org/html/rfc3217 "External link"), 
*Triple-DES and RC2 Key Wrapping*, 
R. Housley, December 2001.
* <a id="X9-23"></a>**[X9-23]**
ANSI X9.23-1998,
*Financial Institution Encryption of Wholesale Financial Messages*,
American National Standards Institute, 1998.
* **<a id="X9-31"></a>[X9-31]**
ANSI X9.31-1998
*Digital Signatures using Reversible
Public Key Cryptography for the Financial Services Industry (rDSA)*,
Appendix A,
American National Standards Institute,
1998.
* **<a id="X9-52"></a>[X9-52]**
ANSI X9.52 
*Triple Data Encryption Algorithm Modes Of Operation*, X9.52 -
1998, Accredited Standards Committee X9, American National
Standards Institute, 1998.
* <a id="XMLENC"></a>**[XMLENC]**
W3C Recommendation, 
*XML Encryption Syntax and Processing Version 1.1*, 
<https://www.w3.org/TR/xmlenc-core1/>, 11 April 2013.

[[Contents](#topofpage)] [[Index](#index)]

<a id="vb6funcsummary"></a>VBA/C Function Summary
-------------------------------------------------

These are the "raw" functions called directly by VBA/C programs. For the .NET method equivalents, see
the [List of .NET Methods](#methodlist) and
[Cross-reference between Functions and .NET Methods](#xrefdotnet).

Index:  
[AEAD](#AEADbyCat) |
[AES](#AESbyCat) |
[Block Ciphers](#CIPHERbyCat) |
[Blowfish](#BLFbyCat) |
[Conversion](#CNVbyCat) |
[Compression](#COMPRbyCat) |
[CRC](#CRCbyCat) |
[DES](#DESbyCat) |
[Hash](#HASHbyCat) |
[GCM](#GCMbyCat) |
[General](#GENbyCat) |
[MAC](#MACbyCat) |
[MD5](#MD5byCat) |
[Padding](#PADbyCat) |
[PBE](#PBEbyCat) |
[PC1 (RC4)](#PC1byCat) |
[RNG](#RNGbyCat) |
[SHA-1](#SHA1byCat) |
[SHA-256](#SHA2byCat) |
[SHA-3](#SHA3byCat) |
[Stream Ciphers](#STREAMbyCat) |
[Triple DES (TDEA)](#TDEAbyCat) |
[WIPE](#WIPEbyCat) |

### <a id="AEADbyCat"></a>AEAD functions

[`AEAD_Encrypt`](#AEAD_Encrypt)  

[`AEAD_Decrypt`](#AEAD_Decrypt)  

[`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)  

[`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)  

[`AEAD_InitKey`](#AEAD_InitKey)  

[`AEAD_SetNonce`](#AEAD_SetNonce)  

[`AEAD_AddAAD`](#AEAD_AddAAD)  

[`AEAD_StartEncrypt`](#AEAD_StartEncrypt)  

[`AEAD_StartDecrypt`](#AEAD_StartDecrypt)  

[`AEAD_Update`](#AEAD_Update)  

[`AEAD_FinishEncrypt`](#AEAD_FinishEncrypt)  

[`AEAD_FinishDecrypt`](#AEAD_FinishDecrypt)  

[`AEAD_Destroy`](#AEAD_Destroy)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="AESbyCat"></a>Advanced Encryption Standard (AES) functions

The AES functions have a separate set of functions for each of the three key sizes.
All operate with a block size of 16 bytes. All expect a key of the respective length to be provided.

| [`AES128_Hex`](#AES128_Hex) [`AES128_HexMode`](#AES128_HexMode) [`AES128_Bytes`](#AES128_Bytes) [`AES128_BytesMode`](#AES128_BytesMode) [`AES128_B64Mode`](#AES128_B64Mode) [`AES128_File`](#AES128_File) [`AES128_FileExt`](#AES128_FileExt) [`AES128_FileHex`](#AES128_FileHex) [`AES128_Init`](#AES128_Init) [`AES128_InitHex`](#AES128_InitHex) [`AES128_InitError`](#AES128_InitError) [`AES128_Update`](#AES128_Update) [`AES128_UpdateHex`](#AES128_UpdateHex) [`AES128_Final`](#AES128_Final) | [`AES192_Hex`](#AES192_Hex) [`AES192_HexMode`](#AES192_HexMode) [`AES192_Bytes`](#AES192_Bytes) [`AES192_BytesMode`](#AES192_BytesMode) [`AES192_B64Mode`](#AES192_B64Mode) [`AES192_File`](#AES192_File) [`AES192_FileExt`](#AES192_FileExt) [`AES192_FileHex`](#AES192_FileHex) [`AES192_Init`](#AES192_Init) [`AES192_InitHex`](#AES192_InitHex) [`AES192_InitError`](#AES192_InitError) [`AES192_Update`](#AES192_Update) [`AES192_UpdateHex`](#AES192_UpdateHex) [`AES192_Final`](#AES192_Final) | [`AES256_Hex`](#AES256_Hex) [`AES256_HexMode`](#AES256_HexMode) [`AES256_Bytes`](#AES256_Bytes) [`AES256_BytesMode`](#AES256_BytesMode) [`AES256_B64Mode`](#AES256_B64Mode) [`AES256_File`](#AES256_File) [`AES256_FileExt`](#AES256_FileExt) [`AES256_FileHex`](#AES256_FileHex) [`AES256_Init`](#AES256_Init) [`AES256_InitHex`](#AES256_InitHex) [`AES256_InitError`](#AES256_InitError) [`AES256_Update`](#AES256_Update) [`AES256_UpdateHex`](#AES256_UpdateHex) [`AES256_Final`](#AES256_Final) |
| --- | --- | --- |

[[Contents](#topofpage)] [[Index](#index)]

### <a id="CIPHERbyCat"></a>Block cipher functions

[`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes)  

[`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes)  

[`CIPHER_EncryptHex`](#CIPHER_EncryptHex)  

[`CIPHER_DecryptHex`](#CIPHER_DecryptHex)  

[`CIPHER_FileEncrypt`](#CIPHER_FileEncrypt)  

[`CIPHER_FileDecrypt`](#CIPHER_FileDecrypt)  

[`CIPHER_Init`](#CIPHER_Init)  

[`CIPHER_InitHex`](#CIPHER_InitHex)  

[`CIPHER_Update`](#CIPHER_Update)  

[`CIPHER_UpdateHex`](#CIPHER_UpdateHex)  

[`CIPHER_Final`](#CIPHER_Final)  

[`CIPHER_KeyWrap`](#CIPHER_KeyWrap)  

[`CIPHER_KeyUnwrap`](#CIPHER_KeyUnwrap)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="BLFbyCat"></a>Blowfish functions

Blowfish can have a key of variable length from one to 56 bytes (448 bits).
The `Byte` variants need you to specify the key length, but the
`Hex` variants will use whatever length is provided in the key hex
string.
The block and IV are always 8 bytes long.

[`BLF_Hex`](#BLF_Hex)  

[`BLF_HexMode`](#BLF_HexMode)  

[`BLF_Bytes`](#BLF_Bytes)  

[`BLF_BytesMode`](#BLF_BytesMode)  

[`BLF_B64Mode`](#BLF_B64Mode)  

[`BLF_File`](#BLF_File)  

[`BLF_FileExt`](#BLF_FileExt)  

[`BLF_FileHex`](#BLF_FileHex)  

[`BLF_Init`](#BLF_Init)  

[`BLF_InitHex`](#BLF_InitHex)  

[`BLF_InitError`](#BLF_InitError)  

[`BLF_Update`](#BLF_Update)  

[`BLF_UpdateHex`](#BLF_UpdateHex)  

[`BLF_Final`](#BLF_Final)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="CNVbyCat"></a>Conversion functions

These functions carry out conversions between bytes and hexadecimal-encoded strings, 
and bytes and base64-encoded strings. 

[`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr)  

[`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes)  

[`CNV_HexFilter`](#CNV_HexFilter)  

[`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str)  

[`CNV_B64StrFromBytes`](#CNV_B64StrFromBytes)  

[`CNV_B64Filter`](#CNV_B64Filter)  

[`CNV_ShortPathName`](#CNV_ShortPathName)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="CRCbyCat"></a>Cyclic Redundancy Check functions

These functions compute a CRC-32 checksum of some given data.
They all return the value of the checksum directly as a 32-bit integer.

[`CRC_Bytes`](#CRC_Bytes)  

[`CRC_File`](#CRC_File)  

[`CRC_String`](#CRC_String)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="DESbyCat"></a>Data Encryption Standard (DES) functions

The key for DES is always 8 bytes (64 bits) long; the block length is 8 bytes.
There is no need to specify the key length when calling
the DES functions: you must provide exactly 8 bytes.
The parity bits in the key are ignored. (NB single DES is no longer considered secure and is recommended only for legacy systems)

[`DES_Hex`](#DES_Hex)  

[`DES_HexMode`](#DES_HexMode)  

[`DES_Bytes`](#DES_Bytes)  

[`DES_BytesMode`](#DES_BytesMode)  

[`DES_B64Mode`](#DES_B64Mode)  

[`DES_File`](#DES_File)  

[`DES_FileExt`](#DES_FileExt)  

[`DES_FileHex`](#DES_FileHex)  

[`DES_Init`](#DES_Init)  

[`DES_InitHex`](#DES_InitHex)  

[`DES_InitError`](#DES_InitError)  

[`DES_Update`](#DES_Update)  

[`DES_UpdateHex`](#DES_UpdateHex)  

[`DES_Final`](#DES_Final)  

[`DES_CheckKey`](#DES_CheckKey)  

[`DES_CheckKeyHex`](#DES_CheckKeyHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="HASHbyCat"></a>Message Digest Hash functions

[`HASH_Bytes`](#HASH_Bytes)  

[`HASH_File`](#HASH_File)  

[`HASH_HexFromBytes`](#HASH_HexFromBytes)  

[`HASH_HexFromFile`](#HASH_HexFromFile)  

[`HASH_HexFromHex`](#HASH_HexFromHex)  

[`HASH_HexFromBits`](#HASH_HexFromBits)  

[`HASH_Init`](#HASH_Init)  

[`HASH_AddBytes`](#HASH_AddBytes)  

[`HASH_Final`](#HASH_Final)  

[`HASH_Reset`](#HASH_Reset)  

[`HASH_DigestLength`](#HASH_DigestLength)  

[`HASH_Length`](#HASH_Length)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="GCMbyCat"></a>GCM functions

@superseded by the [AEAD](#AEADbyCat) functions (unless you need to use a 
non-standard key or IV length).

[`GCM_Encrypt`](#GCM_Encrypt)  

[`GCM_Decrypt`](#GCM_Decrypt)  

[`GCM_InitKey`](#GCM_InitKey)  

[`GCM_NextEncrypt`](#GCM_NextEncrypt)  

[`GCM_NextDecrypt`](#GCM_NextDecrypt)  

[`GCM_FinishKey`](#GCM_FinishKey)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="GENbyCat"></a>General functions

These functions allow you to check the version and other module details, 
and carry out the self-tests on demand.

[`API_CompileTime`](#API_CompileTime)  

[`API_ErrorCode`](#API_ErrorCode)  

[`API_ErrorLookup`](#API_ErrorLookup)  

[`API_LicenceType`](#API_LicenceType)  

[`API_ModuleInfo`](#API_ModuleInfo)  

[`API_ModuleName`](#API_ModuleName)  

[`API_Platform`](#API_Platform)  

[`API_PowerUpTests`](#API_PowerUpTests)  

[`API_Version`](#API_Version)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="MACbyCat"></a>Message Authentication Code functions

[`MAC_Bytes`](#MAC_Bytes)  

[`MAC_HexFromBytes`](#MAC_HexFromBytes)  

[`MAC_HexFromHex`](#MAC_HexFromHex)  

[`MAC_Init`](#MAC_Init)  

[`MAC_AddBytes`](#MAC_AddBytes)  

[`MAC_Final`](#MAC_Final)  

[`MAC_Reset`](#MAC_Reset)  

[`MAC_CodeLength`](#MAC_CodeLength)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="MD5byCat"></a>MD5 Hash Algorithm functions

The MD5 functions are identical in syntax and usage to their SHA-1 equivalents, except
the string to receive the message digest must be set to a minimum of
**32** characters (33 in a C program).
See [Pre-dimensioning a string](#predimensioning).

[`MD5_StringHexHash`](#MD5_StringHexHash)  

[`MD5_BytesHexHash`](#MD5_BytesHexHash)  

[`MD5_BytesHash`](#MD5_BytesHash)  

[`MD5_FileHexHash`](#MD5_FileHexHash)  

[`MD5_Init`](#MD5_Init)  

[`MD5_AddBytes`](#MD5_AddBytes)  

[`MD5_AddString`](#MD5_AddString)  

[`MD5_HexDigest`](#MD5_HexDigest)  

[`MD5_Reset`](#MD5_Reset)  

[`MD5_Hmac`](#MD5_Hmac)  

[`MD5_HmacHex`](#MD5_HmacHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="PADbyCat"></a>Padding functions

These functions add and remove padding required for ECB and CBC block cipher encryption modes.
The outputs from the padding functions are *always* longer than the input,
and the outputs from the 'Unpad' functions are *always* shorter.
The 'Unpad' functions return a "decryption error" if the padding is not valid.

[`PAD_BytesBlock`](#PAD_BytesBlock)  

[`PAD_UnpadBytes`](#PAD_UnpadBytes)  

[`PAD_HexBlock`](#PAD_HexBlock)  

[`PAD_UnpadHex`](#PAD_UnpadHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="PBEbyCat"></a>Password-based encryption functions

[`PBE_Kdf2`](#PBE_Kdf2)  

[`PBE_Kdf2Hex`](#PBE_Kdf2Hex)  

[`PBE_Scrypt`](#PBE_Scrypt)  

[`PBE_ScryptHex`](#PBE_ScryptHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="PC1byCat"></a>PC1 Stream Cipher functions

PC1 is a variable-key-size stream cipher. It produces identical output
to the proprietary RC4 (TM) stream cipher (aka ARCFOUR). It operates on individual bytes. 
To decrypt, just encrypt again with the same key.

Deprecated - use the [stream cipher](#STREAMbyCat) functions.

[`PC1_Bytes`](#PC1_Bytes)  

[`PC1_File`](#PC1_File)  

[`PC1_Hex`](#PC1_Hex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="PRFbyCat"></a>Pseudorandom functions (PRF)

[`PRF_Bytes`](#PRF_Bytes)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="RNGbyCat"></a>Secure Random Number Generator (RNG) functions

[`RNG_KeyBytes`](#RNG_KeyBytes)  

[`RNG_KeyHex`](#RNG_KeyHex)  

[`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt)  

[`RNG_HexWithPrompt`](#RNG_HexWithPrompt)  

[`RNG_NonceData`](#RNG_NonceData)  

[`RNG_NonceDataHex`](#RNG_NonceDataHex)  

[`RNG_Number`](#RNG_Number)  

[`RNG_Initialize`](#RNG_Initialize)  

[`RNG_MakeSeedFile`](#RNG_MakeSeedFile)  

[`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile)  

[`RNG_Test`](#RNG_Test)  

[`RNG_TestDRBGVS`](#RNG_TestDRBGVS)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="SHA1byCat"></a>Secure Hash Algorithm (SHA-1) functions

All the SHA-1 functions (except SHA1_BytesHash) output the message digest as a `String`
in hexadecimal format. You must set the length of the output string to a minimum of
**40** characters before calling the digest functions (41 characters in a C program).
See [Pre-dimensioning a string](#predimensioning)
for instructions on how to do this.

[`SHA1_StringHexHash`](#SHA1_StringHexHash)  

[`SHA1_BytesHexHash`](#SHA1_BytesHexHash)  

[`SHA1_BytesHash`](#SHA1_BytesHash)  

[`SHA1_FileHexHash`](#SHA1_FileHexHash)  

[`SHA1_Init`](#SHA1_Init)  

[`SHA1_AddBytes`](#SHA1_AddBytes)  

[`SHA1_AddString`](#SHA1_AddString)  

[`SHA1_HexDigest`](#SHA1_HexDigest)  

[`SHA1_Reset`](#SHA1_Reset)  

[`SHA1_Hmac`](#SHA1_Hmac)  

[`SHA1_HmacHex`](#SHA1_HmacHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="SHA2byCat"></a>Secure Hash Algorithm (SHA-256) functions

The SHA-256 functions are identical in syntax and usage to their SHA-1 equivalents, except
the string to receive the message digest must be set to a minimum of
**64** characters (65 in a C program).
See [Pre-dimensioning a string](#predimensioning).

[`SHA2_StringHexHash`](#SHA2_StringHexHash)  

[`SHA2_BytesHexHash`](#SHA2_BytesHexHash)  

[`SHA2_BytesHash`](#SHA2_BytesHash)  

[`SHA2_FileHexHash`](#SHA2_FileHexHash)  

[`SHA2_Init`](#SHA2_Init)  

[`SHA2_AddBytes`](#SHA2_AddBytes)  

[`SHA2_AddString`](#SHA2_AddString)  

[`SHA2_HexDigest`](#SHA2_HexDigest)  

[`SHA2_Reset`](#SHA2_Reset)  

[`SHA2_Hmac`](#SHA2_Hmac)  

[`SHA2_HmacHex`](#SHA2_HmacHex)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="SHA3byCat"></a>Secure Hash Algorithm (SHA-3) functions

Stateful functions added back in [v5.3]. For stateless functions like _BytesHexHash, etc, use [HASH_](#HASHbyCat) or [MAC_](#MACbyCat)
with appropriate SHA3 option.

[`SHA3_Init`](#SHA3_Init)  

[`SHA3_AddBytes`](#SHA3_AddBytes)  

[`SHA3_AddString`](#SHA3_AddString)  

[`SHA3_HexDigest`](#SHA3_HexDigest)  

[`SHA3_Reset`](#SHA3_Reset)  

[`SHA3_LengthInBytes`](#SHA3_LengthInBytes)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="STREAMbyCat"></a>Stream cipher functions

Stream ciphers operate on input streams of bytes of any length. To decrypt, just encrypt the ciphertext with the same key.

[`CIPHER_StreamBytes`](#CIPHER_StreamBytes)  

[`CIPHER_StreamHex`](#CIPHER_StreamHex)  

[`CIPHER_StreamFile`](#CIPHER_StreamFile)  

[`CIPHER_StreamInit`](#CIPHER_StreamInit)  

[`CIPHER_StreamUpdate`](#CIPHER_StreamUpdate)  

[`CIPHER_StreamFinal`](#CIPHER_StreamFinal)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="TDEAbyCat"></a>Triple Data Encryption Algorithm (Triple DES) functions

The key for TDEA is always 24 bytes long; the block length is 8 bytes.
There is no need to specify the key length when calling
the TDEA functions, because you must provide exactly 24 bytes.
The parity bits in the key are ignored.

[`TDEA_Hex`](#TDEA_Hex)  

[`TDEA_HexMode`](#TDEA_HexMode)  

[`TDEA_Bytes`](#TDEA_Bytes)  

[`TDEA_BytesMode`](#TDEA_BytesMode)  

[`TDEA_B64Mode`](#TDEA_B64Mode)  

[`TDEA_File`](#TDEA_File)  

[`TDEA_FileExt`](#TDEA_FileExt)  

[`TDEA_FileHex`](#TDEA_FileHex)  

[`TDEA_Init`](#TDEA_Init)  

[`TDEA_InitHex`](#TDEA_InitHex)  

[`TDEA_InitError`](#TDEA_InitError)  

[`TDEA_Update`](#TDEA_Update)  

[`TDEA_UpdateHex`](#TDEA_UpdateHex)  

[`TDEA_Final`](#TDEA_Final)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="WIPEbyCat"></a>Wipe functions

These functions allow you to wipe data and files in a secure manner.

[`WIPE_Data`](#WIPE_Data)  

[`WIPE_File`](#WIPE_File)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="XOFbyCat"></a>Extendable-output functions (XOF)

[`XOF_Bytes`](#XOF_Bytes)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="COMPRbyCat"></a>Compression functions

Remember what happens to a football - you *deflate* it to make it smaller,
and *inflate* it to make it bigger again.
See also [Data compression in cryptography](#compression).

[`COMPR_Compress`](#COMPR_Compress)  

[`COMPR_Uncompress`](#COMPR_Uncompress)  

[`ZLIB_Deflate`](#ZLIB_Deflate)  

[`ZLIB_Inflate`](#ZLIB_Inflate)  

[[Contents](#topofpage)] [[Index](#index)]

### <a id="activexinterface"></a>ActiveX Interface

See [ActiveX Classes and Methods](#activexmethods).

### <a id="deprecatedfunctions"></a>Deprecated Functions

The following functions all deprecated since version 4.0 have been removed in version 4.5.

`AES_Bytes`  

`AES_BytesMode`  

`AES_Ecb`  

`AES_EcbHex`  

`AES_File`  

`AES_FileHex`  

`AES_Final`  

`AES_Hex`  

`AES_HexMode`  

`AES_Init`  

`AES_InitError`  

`AES_InitHex`  

`AES_Update`  

`AES_UpdateHex`  

`bf_BlockDec`  

`bf_BlockEnc`  

`bf_FileDec`  

`bf_FileEnc`  

`bf_Final`  

`bf_Init`  

`bf_StringDec`  

`bf_StringEnc`  

`BLF_Ecb`  

`BLF_EcbHex`  

`RAN_DESKeyGenerate`  

`RAN_DESKeyGenHex`  

`RAN_KeyGenerate`  

`RAN_KeyGenHex`  

`RAN_Long`  

`RAN_Nonce`  

`RAN_NonceHex`  

`RAN_Seed`  

`RAN_TDEAKeyGenerate`  

`RAN_TDEAKeyGenHex`  

`RAN_Test`  

`RNG_KeyGenerate`  

`RNG_KeyGenHex`  

`RNG_Long`  

[[Contents](#topofpage)] [[Index](#index)]

<a id="functionlist"></a>List of Functions
------------------------------------------

Index:  
[AEAD](#AEADbyCat) |
[AES](#AESbyCat) |
[Block Ciphers](#CIPHERbyCat) |
[Blowfish](#BLFbyCat) |
[Conversion](#CNVbyCat) |
[Compression](#COMPRbyCat) |
[CRC](#CRCbyCat) |
[DES](#DESbyCat) |
[Hash](#HASHbyCat) |
[GCM](#GCMbyCat) |
[General](#GENbyCat) |
[MAC](#MACbyCat) |
[MD5](#MD5byCat) |
[Padding](#PADbyCat) |
[PBE](#PBEbyCat) |
[PC1 (RC4)](#PC1byCat) |
[PRF](#PRFbyCat) |
[RNG](#RNGbyCat) |
[SHA-1](#SHA1byCat) |
[SHA-256](#SHA2byCat) |
[SHA-3](#SHA3byCat) |
[Stream Ciphers](#STREAMbyCat) |
[Triple DES (TDEA)](#TDEAbyCat) |
[WIPE](#WIPEbyCat) |
[XOF](#XOFbyCat)

<a id="AEAD_AddAAD"></a>AEAD_AddAAD
-----------------------------------

Add a chunk of additional authenticated data (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_AddAAD Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long) As Long`

`nRet = AEAD_AddAAD(hContext, abAAD(0), nAadLen)`

### C/C++ Syntax

`long __stdcall  AEAD_AddAAD(long hContext, const unsigned char *lpAAD, long nAadLen);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

*lpAAD*
:   [in]  array containing the chunk of Additional Authenticated Data (AAD) to add.

*nAadLen*
:   [in] equal to length of the AAD chunk in bytes.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.AddAAD Method](#M_Aead_AddAAD)  

### Remarks

May be repeated to add additional data in chunks. 
Must eventually be followed by either 
[`AEAD_StartEncrypt`](#AEAD_StartEncrypt) or 
[`AEAD_StartDecrypt`](#AEAD_StartDecrypt). 
Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_Decrypt"></a>AEAD_Decrypt
-------------------------------------

Decrypt and authenticate input using specified AEAD algorithm in one-off operation.
All the input and output parameters are in byte arrays. The authentication tag is specified separately.

### VBA/VB6 Syntax

`Public Declare Function AEAD_Decrypt Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpNonce As Byte, ByVal nNonceLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByRef lpTag As Byte, ByVal nTagLen As Long, ByVal nOptions As Long) As Long`

`nRet = AEAD_Decrypt(lpOutput(0), nOutLen, abData(0), nDataLen, 
	abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, abTag(0), nTagLen, nOptions)`

### C/C++ Syntax

`long __stdcall  AEAD_Decrypt(unsigned char *lpOutput, long nOutLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpNonce, long nNonceLen,const unsigned char *lpAAD, long nAadLen, const unsigned char *lpTag, long nTagLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte array of sufficient length to receive the plaintext output (at least as long as the input).

*nOutLen*
:   [in] length in bytes of the output array.

*lpData*
:   [in] byte array containing the input data.

*nDataLen*
:   [in] length of the input data in bytes.

*lpKey*
:   [in] byte array containing the key of exact length for given algorithm (currently either 16 or 32 bytes).

*nKeyLen*
:   [in] length of the key in *bytes*.

*lpNonce*
:   [in] containing the nonce of exact length for the given algorithm (currently always 12 bytes).

*nNonceLen*
:   [in] length of the nonce in bytes.

*lpAAD*
:   [in] byte array containing the optional Additional Authenticated Data (AAD).

*nAadLen*
:   [in] length of the AAD in bytes.

*lpTag*
:   [in] byte array containing the tag.

*nTagLen*
:   [in] length of the tag in bytes.

*nOptions*
:   [in] option flags.
Select one of the following:  

`API_AEAD_AES_128_GCM` to use the AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_AES_256_GCM` to use the AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_CHACHA20_POLY1305` to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539)

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.Decrypt Method](#M_Aead_Decrypt)  

### Remarks

This is a one-off, stateless function. 
The output plaintext is always exactly the same length as the input ciphertext (excluding any IV or tags in the input).
If the inputs are not authentic, the function returns the non-zero error code `AUTH_FAILED_ERROR` 
and the decrypted output should be rejected.
Note that the term "IV" is used here to mean exactly the same as "nonce". 
For more details of AEAD see [Authenticated Encryption with Additional Data (AEAD)](#aeadalgorithms).

### Example

This is from Appendix A.5 of [[RFC7539](#RFC7539)].

```

' Ref: RFC 7539 Appendix A.5
Dim abKey() As Byte
Dim abNonce() As Byte
Dim abAAD() As Byte
Dim abPT() As Byte
Dim abCT() As Byte
Dim abTag() As Byte

Dim nRet As Long
Dim nKeyLen As Long
Dim nNonceLen As Long
Dim nAadLen As Long
Dim nDataLen As Long
Dim nTagLen As Long
Dim strPTOK As String

Debug.Print "RFC7739 ChaCha20_Poly1305 Appendix A.5:"
' Set byte arrays from hex strings
abKey = cnvBytesFromHexStr("1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0")
abNonce = cnvBytesFromHexStr("000000000102030405060708")
abAAD = cnvBytesFromHexStr("f33388860000000000004e91")
abCT = cnvBytesFromHexStr("64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb24c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c8559797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523eaf4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a1049e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29a6ad5cb4022b02709b")
abTag = cnvBytesFromHexStr("eead9d67890cbb22392336fea1851f38")

strPTOK = "496e7465726e65742d4472616674732061726520647261667420646f63756d656e74732076616c696420666f722061206d6178696d756d206f6620736978206d6f6e74687320616e64206d617920626520757064617465642c207265706c616365642c206f72206f62736f6c65746564206279206f7468657220646f63756d656e747320617420616e792074696d652e20497420697320696e617070726f70726961746520746f2075736520496e7465726e65742d447261667473206173207265666572656e6365206d6174657269616c206f7220746f2063697465207468656d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67726573732e2fe2809d"

' Set lengths of input byte arrays
nKeyLen = UBound(abKey) + 1
nNonceLen = UBound(abNonce) + 1
nAadLen = UBound(abAAD) + 1
nDataLen = UBound(abCT) + 1
nTagLen = UBound(abTag) + 1

' Dimension arrays for output (we are decrypting CT->PT)
ReDim abPT(nDataLen - 1)

' Display input
Debug.Print "K: " & cnvHexStrFromBytes(abKey)
Debug.Print "N: " & cnvHexStrFromBytes(abNonce)
Debug.Print "A: " & cnvHexStrFromBytes(abAAD)
Debug.Print "C: " & cnvHexStrFromBytes(abCT)
Debug.Print "T: " & cnvHexStrFromBytes(abTag)

' Do authenticated decryption using AEAD_CHACHA20_POLY1305
nRet = AEAD_Decrypt(abPT(0), nDataLen, abCT(0), nDataLen, _
    abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, abTag(0), nTagLen, API_AEAD_CHACHA20_POLY1305)
Debug.Print "AEAD_Decrypt returns " & nRet & " (expected 0)"
Debug.Print "P: " & cnvHexStrFromBytes(abPT)
Debug.Print "OK " & strPTOK
' Show plaintext as string (note the UTF-8 double quotation marks do not decode in VB6)
Debug.Print "   " & StrConv(abPT, vbUnicode)

```

This should result in output as follows - note the VB6 display of the UTF-8-encoded double quotation marks characters (U+201C and U+201D):

```

RFC7739 ChaCha20_Poly1305 Appendix A.5:
K: 1C9240A5EB55D38AF333888604F6B5F0473917C1402B80099DCA5CBC207075C0
N: 000000000102030405060708
A: F33388860000000000004E91
C: 64A0861575861AF460F062C79BE643BD5E805CFD345CF389F108670AC76C8CB24C6CFC18755D43EEA09EE94E382D26B0BDB7B73C321B0100D4F03B7F355894CF332F830E710B97CE98C8A84ABD0B948114AD176E008D33BD60F982B1FF37C8559797A06EF4F0EF61C186324E2B3506383606907B6A7C02B0F9F6157B53C867E4B9166C767B804D46A59B5216CDE7A4E99040C5A40433225EE282A1B0A06C523EAF4534D7F83FA1155B0047718CBC546A0D072B04B3564EEA1B422273F548271A0BB2316053FA76991955EBD63159434ECEBB4E466DAE5A1073A6727627097A1049E617D91D361094FA68F0FF77987130305BEABA2EDA04DF997B714D6C6F2C29A6AD5CB4022B02709B
T: EEAD9D67890CBB22392336FEA1851F38
AEAD_Decrypt returns 0 (expected 0)
P: 496E7465726E65742D4472616674732061726520647261667420646F63756D656E74732076616C696420666F722061206D6178696D756D206F6620736978206D6F6E74687320616E64206D617920626520757064617465642C207265706C616365642C206F72206F62736F6C65746564206279206F7468657220646F63756D656E747320617420616E792074696D652E20497420697320696E617070726F70726961746520746F2075736520496E7465726E65742D447261667473206173207265666572656E6365206D6174657269616C206F7220746F2063697465207468656D206F74686572207468616E206173202FE2809C776F726B20696E2070726F67726573732E2FE2809D
OK 496e7465726e65742d4472616674732061726520647261667420646f63756d656e74732076616c696420666f722061206d6178696d756d206f6620736978206d6f6e74687320616e64206d617920626520757064617465642c207265706c616365642c206f72206f62736f6c65746564206279206f7468657220646f63756d656e747320617420616e792074696d652e20497420697320696e617070726f70726961746520746f2075736520496e7465726e65742d447261667473206173207265666572656e6365206d6174657269616c206f7220746f2063697465207468656d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67726573732e2fe2809d
   Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as /â€œwork in progress./â€?

```

### See Also

[`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)
[`AEAD_Encrypt`](#AEAD_Encrypt)
[`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_DecryptWithTag"></a>AEAD_DecryptWithTag
---------------------------------------------------

Decrypt and authenticate input using specified AEAD algorithm in one-off operation.
All the input and output parameters are in byte arrays. The authentication tag is expected to be appended to the input ciphertext.

### VBA/VB6 Syntax

`Public Declare Function AEAD_DecryptWithTag Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpNonce As Byte, ByVal nNonceLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByVal nOptions As Long) As Long`

`nRet = AEAD_DecryptWithTag(lpOutput(0), nOutLen, abInput(0), nInputLen, 
	abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, nOptions)`

### C/C++ Syntax

`long __stdcall  AEAD_DecryptWithTag(unsigned char *lpOutput, long nOutLen, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpNonce, long nNonceLen,const unsigned char *lpAAD, long nAadLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] buffer of sufficient length to receive the plaintext output.

*nOutLen*
:   [in] length in bytes of the output buffer.

*lpInput*
:   [in] byte array containing the input data.

*nInputLen*
:   [in] length of the input data in bytes.

*lpKey*
:   [in] byte array containing the key of exact length for given algorithm (currently either 16 or 32 bytes).

*nKeyLen*
:   [in] length of the key in *bytes*.

*lpNonce*
:   [in] (optional) initialization vector (IV), a.k.a. nonce, if not provided in input.

*nNonceLen*
:   [in] length of the nonce in bytes.

*lpAAD*
:   [in] byte array containing the optional Additional Authenticated Data (AAD).

*nAadLen*
:   [in] length of the AAD in bytes.

*nOptions*
:   [in] option flags.
Select one of the following:  

`API_AEAD_AES_128_GCM` to use the AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_AES_256_GCM` to use the AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_CHACHA20_POLY1305` to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539)  

`API_AEAD_ASCON_128` to use the ASCON-128 authentication scheme (see [ASCON](#ciphersuiteascon)) (provisional, subject to NIST final approval)  

`API_AEAD_ASCON_128A` to use the ASCON-128A authentication scheme (provisional, subject to NIST final approval)  

and optionally add:
`API_IV_PREFIX` to expect the IV (nonce) to be prepended at the start of the input.

### Returns (VBA/C)

If successful, the return value is the number of bytes in or required in the output
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [aeadDecryptWithTag](#VB_aeadDecryptWithTag)(lpData() As Byte, lpKey() As Byte, lpNonce() As Byte, lpAAD() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Aead.DecryptWithTag Method](#M_Aead_DecryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm)  

[Aead.DecryptWithTag Method](#M_Aead_DecryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)  

### C++ (STL) Equivalent

`static crsysapi::bvec_t [crsysapi::Aead::DecryptWithTag](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_aead.html#af96c2083b84e175688404aa5b6f35a33 "External link") (const bvec_t &data, const bvec_t &key, const bvec_t &iv, const bvec_t &aad, Alg alg, Opts opts=Opts::Default)`

### Python Equivalent

`static [Aead.decrypt_with_tag](https://cryptosys.net/pydocapi/class-stubs/Aead.html#crsysapi.Aead.decrypt_with_tag "External link")(input, key, iv, aeadalg, aad=None, opts=Opts.DEFAULT)`

### Remarks

This is a one-off, stateless function. 

The input is expected to be the ciphertext with a 16-byte tag appended `ciphertext||Tag`, or, if the `API_IV_PREFIX` option is set, 
then the same but with the 12/16-byte IV (nonce) prepended `IV||ciphertext||Tag`, where `||` denotes concatenation.
If the IV is not prepended to the input, then it must be provided in the *lpNonce* argument.
The length of the nonce/IV must be exactly 16 bytes for `API_AEAD_ASCON_128`, otherwise exactly 12 bytes. 
Note that the term "IV" is used here to mean exactly the same as "nonce".
If additional authentication data (AAD) was provided during encryption then the exact same AAD data must be provided here.

*Sizes in bytes*

| Algorithm | keyLen | ivLen | tagLen |
| `API_AEAD_AES_128_GCM` | 16 | 12 | 16 |
| `API_AEAD_AES_256_GCM` | 32 | 12 | 16 |
| `API_AEAD_CHACHA20_POLY1305` | 32 | 12 | 16 |
| `API_AEAD_ASCON_128` | 16 | 16 | 16 |
| `API_AEAD_ASCON_128A` | 16 | 16 | 16 |

The output plaintext is always exactly the same length as the input ciphertext (excluding any IV or tags in the input).
If *nOutBytes* is set to zero or *lpOutput* set to 0 (or `NULL` in C or `ByVal 0&` in VBA), 
the required number of bytes will be returned. 
This will be either exactly 16 bytes shorter than the length of the input, or 28/32 bytes shorter if the `API_IV_PREFIX` option is used.

If the inputs are not authentic, the function returns the error code `AUTH_FAILED_ERROR` 
and the decrypted output should be rejected.

The output buffer *lpOutput* **must not** be the same as or overlap with the input *lpInput*.

### Example (VBA core function)

See the example in [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag).

### Example (VBA wrapper function)

See the example for VBA wrapper `aeadEncryptWithTag` in [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag).

### See Also

[`AEAD_Decrypt`](#AEAD_Decrypt)
[`AEAD_Encrypt`](#AEAD_Encrypt)
[`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_Destroy"></a>AEAD_Destroy
-------------------------------------

Closes the AEAD context and destroys the key (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_Destroy Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = AEAD_Destroy(hContext)`

### C/C++ Syntax

`long __stdcall  AEAD_Destroy(long hContext);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.Dispose Method](#M_Aead_Dispose)  

### Remarks

### Example

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_Encrypt"></a>AEAD_Encrypt
-------------------------------------

Encrypt input using specified AEAD algorithm in one-off operation.
All the input and output parameters are in byte arrays.
The authentication tag is output separately.

### VBA/VB6 Syntax

`Public Declare Function AEAD_Encrypt Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpTagOut As Byte, ByVal nTagLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpNonce As Byte, ByVal nNonceLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByVal nOptions As Long) As Long`

`nRet = AEAD_Encrypt(lpOutput(0), nOutLen, abTagOut(0), nTagLen, abData(0), nDataLen, 
	abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, nOptions)`

### C/C++ Syntax

`long __stdcall  AEAD_Encrypt(unsigned char *lpOutput, long nOutLen, unsigned char *lpTagOut, long nTagLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, long nKeyLen,const unsigned char *lpNonce, long nNonceLen, const unsigned char *lpAAD, long nAadLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte array of sufficient length to receive the output.

*nOutLen*
:   [in] length in bytes of the output buffer.

*lpTagOut*
:   [out] byte array of sufficient length to receive the tag (currently 16 bytes for all supported algorithms).

*nTagLen*
:   [in] length in bytes of the tag array.

*lpData*
:   [in] byte array containing the input data.

*nDataLen*
:   [in] length in bytes of the input data.

*lpKey*
:   [in] byte array containing the key of exact length for given algorithm (currently either 16 or 32 bytes).

*nKeyLen*
:   [in] length of the key in *bytes*.

*lpNonce*
:   [in] containing the nonce (IV) of exact length for the given algorithm (currently always 12 bytes).

*nNonceLen*
:   [in] length of the nonce in bytes.

*lpAAD*
:   [in] byte array containing the optional Additional Authenticated Data (AAD).

*nAadLen*
:   [in] length of the AAD in bytes.

*nOptions*
:   [in] option flags.
Must be one of the following:  

`API_AEAD_AES_128_GCM` to use the AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_AES_256_GCM` to use the AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_CHACHA20_POLY1305` to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539)

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.Encrypt Method](#M_Aead_Encrypt)  

### Remarks

This is a one-off, stateless function. 
The output buffer *lpOutput* must be at least as long as the input.
The ciphertext is always the same length as the plaintext and the authentication tag is always exactly 16 bytes long.
Note this function does *not* concatenate the tag after the ciphertext as suggested in [[RFC5116](#RFC5116)]:
for that behaviour, use [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag).

#### MAC

To compute a message authentication code (MAC) over the additional data (AAD), 
pass zero values for both *nOutLen* and *nDataLen* 
(*lpOutput* and *lpData* are ignored and may be NULL).
The "message" is passed in the AAD parameter and the MAC value is output in *lpTagOut*.
A nonce is still required.

### Example

```

' IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:
Dim abKey() As Byte
Dim abNonce() As Byte
Dim abAAD() As Byte
Dim abPT() As Byte
Dim abCT() As Byte
Dim abTag() As Byte

Dim nRet As Long
Dim nKeyLen As Long
Dim nNonceLen As Long
Dim nAadLen As Long
Dim nDataLen As Long
Dim nTagLen As Long
Dim strCTOK As String
Dim strTagOK As String

Debug.Print "IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:"
' Set byte arrays from hex strings
abKey = cnvBytesFromHexStr("071b113b 0ca743fe cccf3d05 1f737382")
abNonce = cnvBytesFromHexStr("f0761e8d cd3d0001 76d457ed")
abAAD = cnvBytesFromHexStr("e20106d7 cd0df076 1e8dcd3d 88e54c2a 76d457ed")
abPT = cnvBytesFromHexStr("08000f10 11121314 15161718 191a1b1c 1d1e1f20 21222324 25262728 292a2b2c 2d2e2f30 31323334 0004")

strCTOK = "13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3"
strTagOK = "d6a5284f4a6d3fe22a5d6c2b960494c3"

' Set lengths of byte arrays
nKeyLen = UBound(abKey) + 1
nNonceLen = UBound(abNonce) + 1
nAadLen = UBound(abAAD) + 1
nDataLen = UBound(abPT) + 1
nTagLen = API_AEAD_TAG_MAX_BYTES

' Dimension arrays for output
ReDim abCT(nDataLen - 1)
ReDim abTag(nTagLen - 1)

' Display input
Debug.Print "K: " & cnvHexStrFromBytes(abKey)
Debug.Print "N: " & cnvHexStrFromBytes(abNonce)
Debug.Print "A: " & cnvHexStrFromBytes(abAAD)
Debug.Print "P: " & cnvHexStrFromBytes(abPT)

' Do authenticated encryption using AEAD_AES_128_GCM
nRet = AEAD_Encrypt(abCT(0), nDataLen, abTag(0), nTagLen, abPT(0), nDataLen, _
    abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, API_AEAD_AES_128_GCM)
Debug.Print "AEAD_Encrypt returns " & nRet & " (expected 0)"
Debug.Print "C: " & cnvHexStrFromBytes(abCT)
Debug.Print "OK " & strCTOK
Debug.Print "T: " & cnvHexStrFromBytes(abTag)
Debug.Print "OK " & strTagOK

' Do authenticated decryption overwriting input CT buffer
nRet = AEAD_Decrypt(abCT(0), nDataLen, abCT(0), nDataLen, abKey(0), nKeyLen, _
    abNonce(0), nNonceLen, abAAD(0), nAadLen, abTag(0), nTagLen, API_AEAD_AES_128_GCM)
Debug.Print "AEAD_Decrypt returns " & nRet & " (0 => OK)"
Debug.Print "P':" & cnvHexStrFromBytes(abCT)

' Do authenticated encryption using AEAD_AES_128_GCM, overwriting input with output
nRet = AEAD_Encrypt(abCT(0), nDataLen, abTag(0), nTagLen, abCT(0), nDataLen, _
    abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, API_AEAD_AES_128_GCM)
Debug.Print "AEAD_Encrypt returns " & nRet & " (expected 0)"
Debug.Print "C: " & cnvHexStrFromBytes(abCT)
Debug.Print "OK " & strCTOK
Debug.Print "T: " & cnvHexStrFromBytes(abTag)
Debug.Print "OK " & strTagOK

```

This should result in output as follows:

```

IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:
K: 071B113B0CA743FECCCF3D051F737382
N: F0761E8DCD3D000176D457ED
A: E20106D7CD0DF0761E8DCD3D88E54C2A76D457ED
P: 08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004
AEAD_Encrypt returns 0 (expected 0)
C: 13B4C72B389DC5018E72A171DD85A5D3752274D3A019FBCAED09A425CD9B2E1C9B72EEE7C9DE7D52B3F3
OK 13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3
T: D6A5284F4A6D3FE22A5D6C2B960494C3
OK d6a5284f4a6d3fe22a5d6c2b960494c3
AEAD_Decrypt returns 0 (0 => OK)
P':08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004
AEAD_Encrypt returns 0 (expected 0)
C: 13B4C72B389DC5018E72A171DD85A5D3752274D3A019FBCAED09A425CD9B2E1C9B72EEE7C9DE7D52B3F3
OK 13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3
T: D6A5284F4A6D3FE22A5D6C2B960494C3
OK d6a5284f4a6d3fe22a5d6c2b960494c3

```

This example carries out packet authentication

```

' IEEE P802.1 MACsec 2.5.2 65-byte Packet Authentication Using GCM-AES-256:
Dim abKey() As Byte
Dim abNonce() As Byte
Dim abAAD() As Byte
Dim abTag() As Byte

Dim nRet As Long
Dim nKeyLen As Long
Dim nNonceLen As Long
Dim nAadLen As Long
Dim nTagLen As Long
Dim strTagOK As String

Debug.Print "IEEE P802.1 MACsec 2.5.2 65-byte Packet Authentication Using GCM-AES-256:"
' Set byte arrays from hex strings
abKey = cnvBytesFromHexStr("83C093B58DE7FFE1C0DA926AC43FB3609AC1C80FEE1B624497EF942E2F79A823")
abNonce = cnvBytesFromHexStr("7CFDE9F9E33724C68932D612")
abAAD = cnvBytesFromHexStr("84C5D513D2AAF6E5BBD2727788E523008932D6127CFDE9F9E33724C608000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F0005")

strTagOK = "6ee160e8faeca4b36c86b234920ca975"

' Set lengths of byte arrays
nKeyLen = UBound(abKey) + 1
nNonceLen = UBound(abNonce) + 1
nAadLen = UBound(abAAD) + 1
nTagLen = API_AEAD_TAG_MAX_BYTES

' Dimension arrays for output
ReDim abTag(nTagLen - 1)

' Display input
Debug.Print "K: " & cnvHexStrFromBytes(abKey)
Debug.Print "N: " & cnvHexStrFromBytes(abNonce)
Debug.Print "A: " & cnvHexStrFromBytes(abAAD)

' Do authenticated encryption using AEAD_AES_256_GCM
' Note that CT and PT are empty => just computing a MAC over the AAD
nRet = AEAD_Encrypt(0, 0, abTag(0), nTagLen, 0, 0, _
    abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, API_AEAD_AES_256_GCM)
Debug.Print "AEAD_Encrypt returns " & nRet & " (expected 0)"
Debug.Print "T: " & cnvHexStrFromBytes(abTag)
Debug.Print "OK " & strTagOK

' Do authenticated decryption
' Note that CT and PT are empty => just authenticating the tag over the AAD
nRet = AEAD_Decrypt(0, 0, 0, 0, abKey(0), nKeyLen, _
    abNonce(0), nNonceLen, abAAD(0), nAadLen, abTag(0), nTagLen, API_AEAD_AES_256_GCM)
Debug.Print "AEAD_Decrypt returns " & nRet & " (0 => OK)"

```

```

IEEE P802.1 MACsec 2.5.2 65-byte Packet Authentication Using GCM-AES-256:
K: 83C093B58DE7FFE1C0DA926AC43FB3609AC1C80FEE1B624497EF942E2F79A823
N: 7CFDE9F9E33724C68932D612
A: 84C5D513D2AAF6E5BBD2727788E523008932D6127CFDE9F9E33724C608000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F0005
AEAD_Encrypt returns 0 (expected 0)
T: 6EE160E8FAECA4B36C86B234920CA975
OK 6ee160e8faeca4b36c86b234920ca975
AEAD_Decrypt returns 0 (0 => OK)

```

### See Also

[`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)
[`AEAD_Decrypt`](#AEAD_Decrypt)
[`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_EncryptWithTag"></a>AEAD_EncryptWithTag
---------------------------------------------------

Encrypt input using specified AEAD algorithm in one-off operation with the authentication tag appended to output.

### VBA/VB6 Syntax

`Public Declare Function AEAD_EncryptWithTag Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpNonce As Byte, ByVal nNonceLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByVal nOptions As Long) As Long`

`nRet = AEAD_EncryptWithTag(lpOutput(0), nOutLen, abInput(0), nInputLen, abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, nOptions)`

### C/C++ Syntax

`long __stdcall  AEAD_EncryptWithTag(unsigned char *lpOutput, long nOutLen, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen,const unsigned char *lpNonce, long nNonceLen, const unsigned char *lpAAD, long nAadLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] buffer of sufficient length to receive the output.

*nOutLen*
:   [in] length of the output buffer in bytes.

*lpInput*
:   [in] byte array containing the input data.

*nInputLen*
:   [in] length of the input data in bytes.

*lpKey*
:   [in] byte array containing the key.

*nKeyLen*
:   [in] length of the key in *bytes* (must be either 16 or 32).

*lpNonce*
:   [in] (required) initialization vector (IV), a.k.a. nonce.

*nNonceLen*
:   [in] length of the nonce in bytes (must be either 12 or 16).

*lpAAD*
:   [in] (optional) additional authenticated data (AAD).

*nAadLen*
:   [in] length of the AAD in bytes.

*nOptions*
:   [in] option flags.
Must be one of the following:  

`API_AEAD_AES_128_GCM` to use the AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_AES_256_GCM` to use the AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_CHACHA20_POLY1305` to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539)  

`API_AEAD_ASCON_128` to use the ASCON-128 authentication scheme (see [ASCON](#ciphersuiteascon)) (provisional, subject to NIST final approval)  

`API_AEAD_ASCON_128A` to use the ASCON-128A authentication scheme (provisional, subject to NIST final approval)  

and optionally add:  

`API_IV_PREFIX` to prepend the IV (nonce) before the ciphertext in the output.

### Returns (VBA/C)

If successful, the return value is the number of bytes in or required in the output; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [aeadEncryptWithTag](#VB_aeadEncryptWithTag)(lpData() As Byte, lpKey() As Byte, lpNonce() As Byte, lpAAD() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Aead.EncryptWithTag Method](#M_Aead_EncryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm)  

[Aead.EncryptWithTag Method](#M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)  

### C++ (STL) Equivalent

`static crsysapi::bvec_t [crsysapi::Aead::EncryptWithTag](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_aead.html#a0f1807e4cd20f3aa3e401738dcc39ba2 "External link") (const bvec_t &data, const bvec_t &key, const bvec_t &iv, const bvec_t &aad, Alg alg, Opts opts=Opts::Default)`

### Python Equivalent

`static [Aead.encrypt_with_tag](https://cryptosys.net/pydocapi/class-stubs/Aead.html#crsysapi.Aead.encrypt_with_tag "External link")(input, key, iv, aeadalg, aad=None, opts=Opts.DEFAULT)`

### Remarks

This is a one-off, stateless function that carries out [Authenticated Encryption with Additional Data (AEAD)](#aeadalgorithms).
In this implementation,  the tag is always exactly 16 bytes (128 bits). 
The tag is automatically appended to the output of the encryption operation in accordance with [[RFC5116](#RFC5116)].
The IV may optionally be prepended to the output using the `API_IV_PREFIX` option flag. 
Note that the term "IV" is used here to mean exactly the same as "nonce".

The length of key *lpKey* must be exactly the required key size in bytes: 
16 for `API_AEAD_AES_128_GCM` and `API_AEAD_ASCON_128`; or 32 for `API_AEAD_AES_256_GCM` and `API_AEAD_CHACHA20_POLY1305`. 
It is an error if the algorithm is not specified in the *nOptions* argument. 
The length of the nonce/IV must be exactly 16 bytes for `API_AEAD_ASCON_128`, otherwise exactly 12 bytes. 
The user is responsible for providing a unique IV each time the same key is used. 
Be aware it is a serious security risk if the same IV and key are used to encrypt different plaintexts. 

*Sizes in bytes*

| Algorithm | keyLen | ivLen | tagLen |
| `API_AEAD_AES_128_GCM` | 16 | 12 | 16 |
| `API_AEAD_AES_256_GCM` | 32 | 12 | 16 |
| `API_AEAD_CHACHA20_POLY1305` | 32 | 12 | 16 |
| `API_AEAD_ASCON_128` | 16 | 16 | 16 |
| `API_AEAD_ASCON_128A` | 16 | 16 | 16 |

If *nOutBytes* is set to zero or *lpOutput* set to 0 (or `NULL` in C or `ByVal 0&` in VBA), 
the required number of bytes will be returned. 
This will be either exactly *tagLen* (16) bytes longer than the length of the input, or exactly *tagLen+ivLen* (28/32) bytes longer if the `API_IV_PREFIX` option is used.

The output buffer *lpOutput* **must not** be the same as or overlap with the input *lpInput*.

### Example (VBA core function)

This is the same example as in 
[`AEAD_Encrypt`](#AEAD_Encrypt) but with the tag appended to the output and the IV (nonce) prefixed.

```

' IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:
Dim abKey() As Byte
Dim abNonce() As Byte
Dim abAAD() As Byte
Dim abPT() As Byte
Dim abCT() As Byte
Dim abDT() As Byte

Dim nKeyLen As Long
Dim nNonceLen As Long
Dim nAadLen As Long
Dim nPtLen As Long
Dim nCtLen As Long
Dim nDtLen As Long
Dim strCTOK As String

Debug.Print "IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:"
Debug.Print "-- using AEAD_EncryptWithTag to output in form IV||CT||TAG"
' Set byte arrays from hex strings
abKey = cnvBytesFromHexStr("071b113b 0ca743fe cccf3d05 1f737382")
abNonce = cnvBytesFromHexStr("f0761e8d cd3d0001 76d457ed")
abAAD = cnvBytesFromHexStr("e20106d7 cd0df076 1e8dcd3d 88e54c2a 76d457ed")
abPT = cnvBytesFromHexStr("08000f10 11121314 15161718 191a1b1c 1d1e1f20 21222324 25262728 292a2b2c 2d2e2f30 31323334 0004")

' Output is ciphertext (same length as plaintext) plus 96-bit IV prefixed and 128-bit tag appended
strCTOK = "f0761e8dcd3d000176d457ed" & _
    "13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3" & _
    "d6a5284f4a6d3fe22a5d6c2b960494c3"

' Get lengths of input byte arrays
nKeyLen = UBound(abKey) + 1
nNonceLen = UBound(abNonce) + 1
nAadLen = UBound(abAAD) + 1
nPtLen = UBound(abPT) + 1

' Display input
Debug.Print "K: " & cnvHexStrFromBytes(abKey)
Debug.Print "N: " & cnvHexStrFromBytes(abNonce)
Debug.Print "A: " & cnvHexStrFromBytes(abAAD)
Debug.Print "P: " & cnvHexStrFromBytes(abPT)
Debug.Print "Len(P)=" & UBound(abPT) + 1

' Find required output length and dimension output array
' -- this will be the length of plaintext in bytes plus 28
nCtLen = AEAD_EncryptWithTag(0, 0, abPT(0), nPtLen, abKey(0), nKeyLen, abNonce(0), nNonceLen, abAAD(0), nAadLen, _
    API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Assert (nCtLen > 0)
ReDim abCT(nCtLen - 1)

' Do authenticated encryption using AEAD_AES_128_GCM
nCtLen = AEAD_EncryptWithTag(abCT(0), nCtLen, abPT(0), nPtLen, abKey(0), nKeyLen, abNonce(0), nNonceLen, _
    abAAD(0), nAadLen, API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Print "AEAD_EncryptWithTag returns " & nCtLen & " (expected >0)"
Debug.Print "C: " & cnvHexStrFromBytes(abCT)
Debug.Print "OK " & strCTOK

' Do authenticated decryption (NB do *not* overwrite input with output)
' Find required output length
' -- this will be the length of ciphertext in bytes minus 28
nDtLen = AEAD_DecryptWithTag(0, 0, abCT(0), nCtLen, abKey(0), nKeyLen, abNonce(0), nNonceLen, _
    abAAD(0), nAadLen, API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Print "AEAD_DecryptWithTag returns " & nDtLen & " (expected >0)"
Debug.Assert (nDtLen > 0)
ReDim abDT(nDtLen - 1)
nDtLen = AEAD_DecryptWithTag(abDT(0), nDtLen, abCT(0), nCtLen, abKey(0), nKeyLen, abNonce(0), nNonceLen, _
    abAAD(0), nAadLen, API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Print "P`:" & cnvHexStrFromBytes(abDT)
Debug.Print "OK " & cnvHexStrFromBytes(abPT)

```

```

IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:
-- using AEAD_EncryptWithTag to output in form IV||CT||TAG
K: 071B113B0CA743FECCCF3D051F737382
N: F0761E8DCD3D000176D457ED
A: E20106D7CD0DF0761E8DCD3D88E54C2A76D457ED
P: 08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004
Len(P)=42
AEAD_EncryptWithTag returns 70 (expected >0)
C: F0761E8DCD3D000176D457ED13B4C72B389DC5018E72A171DD85A5D3752274D3A019FBCAED09A425CD9B2E1C9B72EEE7C9DE7D52B3F3D6A5284F4A6D3FE22A5D6C2B960494C3
OK f0761e8dcd3d000176d457ed13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3d6a5284f4a6d3fe22a5d6c2b960494c3
AEAD_DecryptWithTag returns 42 (expected >0)
P':08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004
OK 08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004

```

### Example (VBA wrapper function)

```

Dim lpKey() As Byte
Dim lpNonce() As Byte
Dim lpAAD() As Byte
Dim lpPT() As Byte
Dim lpCT() As Byte
Dim lpDT() As Byte

' Ref: IEEE P802.1 MACsec 2.4.1 54-byte Packet Encryption Using GCM-AES-128:
' Set byte arrays from hex strings
lpKey = cnvBytesFromHexStr("071b113b 0ca743fe cccf3d05 1f737382")
lpNonce = cnvBytesFromHexStr("f0761e8d cd3d0001 76d457ed")
lpAAD = cnvBytesFromHexStr("e20106d7 cd0df076 1e8dcd3d 88e54c2a 76d457ed")
lpPT = cnvBytesFromHexStr("08000f10 11121314 15161718 191a1b1c 1d1e1f20 21222324 25262728 292a2b2c 2d2e2f30 31323334 0004")

lpCT = aeadEncryptWithTag(lpPT, lpKey, lpNonce, lpAAD, API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Print "C: " & cnvHexStrFromBytes(lpCT)
Debug.Print "OK f0761e8dcd3d000176d457ed13b4c72b389dc5018e72a171dd85a5d3752274d3a019fbcaed09a425cd9b2e1c9b72eee7c9de7d52b3f3d6a5284f4a6d3fe22a5d6c2b960494c3"

lpDT = aeadDecryptWithTag(lpCT, lpKey, lpNonce, lpAAD, API_AEAD_AES_128_GCM Or API_IV_PREFIX)
Debug.Print "P: " & cnvHexStrFromBytes(lpDT)
Debug.Print "OK 08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340004"
```

### See Also

[`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)
[`AEAD_Encrypt`](#AEAD_Encrypt)
[`AEAD_Decrypt`](#AEAD_Decrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_FinishDecrypt"></a>AEAD_FinishDecrypt
-------------------------------------------------

Finishes the authenticated decryption (in incremental mode) .

### VBA/VB6 Syntax

`Public Declare Function AEAD_FinishDecrypt Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = AEAD_FinishDecrypt(hContext)`

### C/C++ Syntax

`long __stdcall  AEAD_FinishDecrypt(long hContext);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.FinishDecrypt Method](#M_Aead_FinishDecrypt)  

### Remarks

Returns the nonzero error code `AUTH_FAILED_ERROR` (-40) if the inputs are not authentic.
Must be preceded by 
[`AEAD_StartDecrypt`](#AEAD_StartEncrypt)
and zero or more calls to [`AEAD_Update`](#AEAD_Update). 
May be followed by  
[`AEAD_SetNonce`](#AEAD_SetNonce) 
to begin processing another packet with the same key and algorithm;
otherwise should be followed by
[`AEAD_Destroy`](#AEAD_Destroy) .
Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_FinishEncrypt"></a>AEAD_FinishEncrypt
-------------------------------------------------

Finishes the authenticated encryption (in incremental mode) .

### VBA/VB6 Syntax

`Public Declare Function AEAD_FinishEncrypt Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpTagOut As Byte, ByVal nTagLen As Long) As Long`

`nRet = AEAD_FinishEncrypt(hContext, abTagOut(0), nTagLen)`

### C/C++ Syntax

`long __stdcall  AEAD_FinishEncrypt(long hContext, unsigned char *lpTagOut, long nTagLen);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

*lpTagOut*
:   [out] byte array of sufficient length to receive the tag (currently 16 bytes for all supported algorithms).

*nTagLen*
:   [in] specifying the length in bytes of the tag array.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.FinishEncrypt Method](#M_Aead_FinishEncrypt)  

### Remarks

Must be preceded by 
[`AEAD_StartEncrypt`](#AEAD_StartEncrypt)
and zero or more calls to [`AEAD_Update`](#AEAD_Update). 
May be followed by  
[`AEAD_SetNonce`](#AEAD_SetNonce) 
to begin processing another packet with the same key and algorithm;
otherwise should be followed by
[`AEAD_Destroy`](#AEAD_Destroy) .
Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_InitKey"></a>AEAD_InitKey
-------------------------------------

Initializes the context with the key and algorithm ready for repeated incremental operations.

### VBA/VB6 Syntax

`Public Declare Function AEAD_InitKey Lib "diCryptoSys.dll" (ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal nOptions As Long) As Long`

`nRet = AEAD_InitKey(abKey(0), nKeyLen, nOptions)`

### C/C++ Syntax

`long __stdcall  AEAD_InitKey(const unsigned char *lpKey, long nKeyLen, long nOptions);`

### Parameters

*lpKey*
:   [in] byte array containing the key of exact length for given algorithm (currently either 16 or 32 bytes).

*nKeyLen*
:   [in] equal to length of the key in *bytes*.

*nOptions*
:   [in] option flags.
Select one of the following:  

`API_AEAD_AES_128_GCM` to use the AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_AES_256_GCM` to use the AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116)  

`API_AEAD_CHACHA20_POLY1305` to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539)

### Returns (VBA/C)

If successful, the return value is the nonzero handle of the AEAD context `hContext`;
otherwise it returns *zero* if an error occurred.

### .NET Equivalent

[Aead.InitKey Method](#M_Aead_InitKey)  

### Remarks

Must be followed by [`AEAD_SetNonce`](#AEAD_SetNonce). 
This function can be called at any time to cancel any previous context settings.
Note that a zero return value indicates an error:
Use [`API_ErrorCode`](#API_ErrorCode) to find more details of the error.
For more details of the correct sequence to call the incremental AEAD functions, see 
[Correct sequence for AEAD incremental functions](#aeadsequence).

### Example

This is a test case of ChaCha20-Poly1305 from RFC 7739.
It encrypts the data in incremental mode (simulating adding chunks) and then decrypts in incremental mode
using the same key.

```

' RFC7739 ChaCha20_Poly1305 Sunscreen test - INCREMENTAL MODE:
Dim abKey() As Byte
Dim abNonce() As Byte
Dim abAAD() As Byte
Dim abPT() As Byte
Dim abCT() As Byte
Dim abTag() As Byte

Dim nRet As Long
Dim nKeyLen As Long
Dim nNonceLen As Long
Dim nAadLen As Long
Dim nDataLen As Long
Dim nTagLen As Long
Dim strCTOK As String
Dim strTagOK As String
Dim hContext As Long
Dim nOffset As Long
Dim nLen As Long
Dim nLeft As Long

Debug.Print "RFC7739 ChaCha20_Poly1305 Sunscreen test:"
' Set byte arrays from hex strings
abKey = cnvBytesFromHexStr("808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F")
abNonce = cnvBytesFromHexStr("070000004041424344454647")
abAAD = cnvBytesFromHexStr("50515253C0C1C2C3C4C5C6C7")
abPT = cnvBytesFromHexStr("4C616469657320616E642047656E746C656D656E206F662074686520636C617373206F66202739393A204966204920636F756C64206F6666657220796F75206F6E6C79206F6E652074697020666F7220746865206675747572652C2073756E73637265656E20776F756C642062652069742E")

strCTOK = "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116"
strTagOK = "1ae10b594f09e26a7e902ecbd0600691"

' Set lengths of byte arrays
nKeyLen = UBound(abKey) + 1
nNonceLen = UBound(abNonce) + 1
nAadLen = UBound(abAAD) + 1
nDataLen = UBound(abPT) + 1
nTagLen = API_AEAD_TAG_MAX_BYTES

' Dimension arrays for output
ReDim abCT(nDataLen - 1)
ReDim abTag(nTagLen - 1)

' Display input
Debug.Print "K: " & cnvHexStrFromBytes(abKey)
Debug.Print "N: " & cnvHexStrFromBytes(abNonce)
Debug.Print "A: " & cnvHexStrFromBytes(abAAD)
Debug.Print "P: " & cnvHexStrFromBytes(abPT)

' Do authenticated encryption using AEAD_CHACHA20_POLY1305
' 1.1 Initialize with the key and AEAD algorithm
hContext = AEAD_InitKey(abKey(0), nKeyLen, API_AEAD_CHACHA20_POLY1305)
Debug.Print "AEAD_InitKey returns 0x" & Hex(hContext) & " (expecting non-zero)"

' 1.2 Set the nonce
nRet = AEAD_SetNonce(hContext, abNonce(0), nNonceLen)

' 1.3 Add the AAD (simulate adding in two parts)
nLen = nAadLen / 2
nOffset = 0
nRet = AEAD_AddAAD(hContext, abAAD(nOffset), nLen)
nOffset = nLen
nLen = nAadLen - nLen
nRet = AEAD_AddAAD(hContext, abAAD(nOffset), nLen)

' 1.4 Start Encrypting
nRet = AEAD_StartEncrypt(hContext)

' 1.5 Update plaintext -> ciphertext (simulate adding in chunks)
Debug.Print "Adding plaintext in chunks"
nLen = 17
nLeft = nDataLen
nOffset = 0
While nLeft > 0
    If nLeft < nLen Then
        nLen = nLeft
    End If
    ' Update another chunk of plaintext
    Debug.Print "P: " & cnvHexFromBytesMid(abPT, nOffset, nLen)
    nRet = AEAD_Update(hContext, abCT(nOffset), nLen, abPT(nOffset), nLen)
    Debug.Print "C: " & cnvHexFromBytesMid(abCT, nOffset, nLen)
    nOffset = nOffset + nLen
    nLeft = nLeft - nLen
Wend

' 1.6 Finish encrypting and output Tag
nRet = AEAD_FinishEncrypt(hContext, abTag(0), nTagLen)

Debug.Print "C: " & cnvHexStrFromBytes(abCT)
Debug.Print "OK " & strCTOK
Debug.Print "T: " & cnvHexStrFromBytes(abTag)
Debug.Print "OK " & strTagOK

' DECRYPTING...
Debug.Print "DECRYPTING..."
' 2.1 Use key we initialized with in step 1.1
' 2.2 Set Nonce
nRet = AEAD_SetNonce(hContext, abNonce(0), nNonceLen)
' 2.3 Add AAD (this time in one go)
nRet = AEAD_AddAAD(hContext, abAAD(0), nAadLen)
' 2.4 Start decrypting using Tag we just made
nRet = AEAD_StartDecrypt(hContext, abTag(0), nTagLen)

' 2.5. Update with ciphertext -> plaintext (simulate adding in chunks)
Debug.Print "Adding ciphertext in chunks"
nLen = 13
nLeft = nDataLen
nOffset = 0
While nLeft > 0
    If nLeft < nLen Then
        nLen = nLeft
    End If
    ' Update chunk of ciphertext in situ
    Debug.Print "C: " & cnvHexFromBytesMid(abCT, nOffset, nLen)
    nRet = AEAD_Update(hContext, abCT(nOffset), nLen, abCT(nOffset), nLen)
    Debug.Print "P: " & cnvHexFromBytesMid(abCT, nOffset, nLen)
    nOffset = nOffset + nLen
    nLeft = nLeft - nLen
Wend
' Note: treat plaintext output as suspect until authenticated by FinishDecrypt
Debug.Print "P':" & cnvHexStrFromBytes(abCT)

' 2.6 Finish decrypting and check OK|FAIL
nRet = AEAD_FinishDecrypt(hContext)
Debug.Print "AEAD_FinishDecrypt returns " & nRet & " (0 => OK)"

' 3. We are done with the key so destroy it
nRet = AEAD_Destroy(hContext)
Debug.Print "AEAD_Destroy returns " & nRet & " (expecting 0)"

```

This should result in output as follows:

```

RFC7739 ChaCha20_Poly1305 Sunscreen test:
K: 808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F
N: 070000004041424344454647
A: 50515253C0C1C2C3C4C5C6C7
P: 4C616469657320616E642047656E746C656D656E206F662074686520636C617373206F66202739393A204966204920636F756C64206F6666657220796F75206F6E6C79206F6E652074697020666F7220746865206675747572652C2073756E73637265656E20776F756C642062652069742E
AEAD_InitKey returns 0x1BE3AC35 (expecting non-zero)
Adding plaintext in chunks
P: 4C616469657320616E642047656E746C65
C: D31A8D34648E60DB7B86AFBC53EF7EC2A4
P: 6D656E206F662074686520636C61737320
C: ADED51296E08FEA9E2B5A736EE62D63DBE
P: 6F66202739393A204966204920636F756C
C: A45E8CA9671282FAFB69DA92728B1A71DE
P: 64206F6666657220796F75206F6E6C7920
C: 0A9E060B2905D6A5B67ECD3B3692DDBD7F
P: 6F6E652074697020666F72207468652066
C: 2D778B8C9803AEE328091B58FAB324E4FA
P: 75747572652C2073756E73637265656E20
C: D675945585808B4831D7BC3FF4DEF08E4B
P: 776F756C642062652069742E
C: 7A9DE576D26586CEC64B6116
C: D31A8D34648E60DB7B86AFBC53EF7EC2A4ADED51296E08FEA9E2B5A736EE62D63DBEA45E8CA9671282FAFB69DA92728B1A71DE0A9E060B2905D6A5B67ECD3B3692DDBD7F2D778B8C9803AEE328091B58FAB324E4FAD675945585808B4831D7BC3FF4DEF08E4B7A9DE576D26586CEC64B6116
OK d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116
T: 1AE10B594F09E26A7E902ECBD0600691
OK 1ae10b594f09e26a7e902ecbd0600691
DECRYPTING...
Adding ciphertext in chunks
C: D31A8D34648E60DB7B86AFBC53
P: 4C616469657320616E64204765
C: EF7EC2A4ADED51296E08FEA9E2
P: 6E746C656D656E206F66207468
C: B5A736EE62D63DBEA45E8CA967
P: 6520636C617373206F66202739
C: 1282FAFB69DA92728B1A71DE0A
P: 393A204966204920636F756C64
C: 9E060B2905D6A5B67ECD3B3692
P: 206F6666657220796F75206F6E
C: DDBD7F2D778B8C9803AEE32809
P: 6C79206F6E652074697020666F
C: 1B58FAB324E4FAD67594558580
P: 7220746865206675747572652C
C: 8B4831D7BC3FF4DEF08E4B7A9D
P: 2073756E73637265656E20776F
C: E576D26586CEC64B6116
P: 756C642062652069742E
P':4C616469657320616E642047656E746C656D656E206F662074686520636C617373206F66202739393A204966204920636F756C64206F6666657220796F75206F6E6C79206F6E652074697020666F7220746865206675747572652C2073756E73637265656E20776F756C642062652069742E
AEAD_FinishDecrypt returns 0 (0 => OK)
AEAD_Destroy returns 0 (expecting 0)

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_SetNonce"></a>AEAD_SetNonce
---------------------------------------

Set the nonce (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_SetNonce Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpNonce As Byte, ByVal nNonceLen As Long) As Long`

`nRet = AEAD_SetNonce(hContext, abNonce(0), nNonceLen)`

### C/C++ Syntax

`long __stdcall  AEAD_SetNonce(long hContext, const unsigned char *lpNonce, long nNonceLen);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

*lpNonce*
:   [in] containing the nonce of exact length for the given algorithm (currently always 12 bytes).

*nNonceLen*
:   [in] equal to length of the nonce in bytes.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.SetNonce Method](#M_Aead_SetNonce)  

### Remarks

Must be followed by zero or more calls to 
[`AEAD_AddAAD`](#AEAD_AddAAD) and then either 
[`AEAD_StartEncrypt`](#AEAD_StartEncrypt) or 
[`AEAD_StartDecrypt`](#AEAD_StartDecrypt). 
Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_StartDecrypt"></a>AEAD_StartDecrypt
-----------------------------------------------

Start authenticated decryption (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_StartDecrypt Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpTagToCheck As Byte, ByVal nTagLen As Long) As Long`

`nRet = AEAD_StartDecrypt(hContext, abTagToCheck(0), nTagLen)`

### C/C++ Syntax

`long __stdcall  AEAD_StartDecrypt(long hContext, const unsigned char *lpTagToCheck, long nTagLen);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

*lpTagToCheck*
:   [in] byte array containing the tag to be checked.

*nTagLen*
:   [in] equal to length of the tag in bytes.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.StartDecrypt Method](#M_Aead_StartDecrypt)  

### Remarks

May be followed by zero or more calls to [`AEAD_Update`](#AEAD_Update) to decrypt data in chunks. 
Must eventually be followed by  
[`AEAD_FinishDecrypt`](#AEAD_FinishDecrypt). 
Returns `MISUSE_ERROR` if called out of sequence.
**Caution:** do not trust decrypted data until final authentication. 

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_StartEncrypt"></a>AEAD_StartEncrypt
-----------------------------------------------

Start authenticated encryption (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_StartEncrypt Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = AEAD_StartEncrypt(hContext)`

### C/C++ Syntax

`long __stdcall  AEAD_StartEncrypt(long hContext);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.StartEncrypt Method](#M_Aead_StartEncrypt)  

### Remarks

May be followed by zero or more calls to [`AEAD_Update`](#AEAD_Update) to encrypt data in chunks. 
Must eventually be followed by  
[`AEAD_FinishEncrypt`](#AEAD_FinishEncrypt). 
Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AEAD_Update"></a>AEAD_Update
-----------------------------------

Encrypts or decrypts a chunk of input (in incremental mode).

### VBA/VB6 Syntax

`Public Declare Function AEAD_Update Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = AEAD_Update(hContext, lpOutput(0), nOutLen, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  AEAD_Update(long hContext, unsigned char *lpOutput, long nOutLen, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the AEAD context set up by an earlier call to 
	[`AEAD_InitKey`](#AEAD_InitKey).

*lpOutput*
:   [out] byte array of sufficient length to receive the output (at least as long as the input).

*nOutLen*
:   [in] specifying the length in bytes of the output array.

*lpData*
:   [in] byte array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[Aead.Update Method](#M_Aead_Update)  

### Remarks

This function may be repeated to add input data in chunks. 

The input data is encrypted or decrypted depending on the start mode set by a preceding call to 
[`AEAD_StartEncrypt`](#AEAD_StartEncrypt) or
[`AEAD_StartDecrypt`](#AEAD_StartDecrypt), respectively.

It must eventually be followed by either
[`AEAD_FinishEncrypt`](#AEAD_FinishEncrypt) or
[`AEAD_FinishDecrypt`](#AEAD_FinishDecrypt),
which must match the start mode. 

Returns `MISUSE_ERROR` if called out of sequence.

### Example

See the example in [`AEAD_InitKey`](#AEAD_InitKey). 

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_B64Mode"></a>AES128_B64Mode
-----------------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function AES128_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = AES128_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  AES128_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (16 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 16 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* must also represent exactly 16 bytes, the required key length.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

This example is the same data as for [`AES128_HexMode`](#AES128_HexMode),
except the data is in base64 format.

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strIV As String
Dim bEncrypt As Boolean
Dim sCorrect As String

' Case #4: Encrypting 64 bytes (4 blocks) using AES-CBC with 128-bit key
' Key       : 0x56e47a38c5598974bc46903dba290349
strKey = "VuR6OMVZiXS8RpA9uikDSQ=="
' IV        : 0x8ce82eefbea0da3c44699ed7db51b7d9
strIV = "jOgu776g2jxEaZ7X21G32Q=="
' Plaintext : 0xa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
'               b0b1b2b3b4b5b6b7b8b9babbbcbdbebf
'               c0c1c2c3c4c5c6c7c8c9cacbcccdcecf
'               d0d1d2d3d4d5d6d7d8d9dadbdcdddedf
strInput = "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/" _
& "AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w=="
' Ciphertext: 0xc30e32ffedc0774e6aff6af0869f71aa
'               0f3af07a9a31a9c684db207eb0ef8e4e
'               35907aa632c3ffdf868bb7b29d3d46ad
'               83ce9f9a102ee99d49a53e87f4c3da55
sCorrect = "ww4y/+3Ad05q/2rwhp9xqg868HqaManGhNsgfrDvjk" _
& "41kHqmMsP/34aLt7KdPUatg86fmhAu6Z1JpT6H9MPaVQ=="

' Set strOutput to be same length as strInput
strOutput = String(Len(strInput), " ")

Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
nRet = AES128_B64Mode(strOutput, strInput, strKey, ENCRYPT, "CBC", strIV)
Debug.Print "CT=" & strOutput & nRet
Debug.Print "OK=" & sCorrect

strInput = strOutput
nRet = AES128_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=VuR6OMVZiXS8RpA9uikDSQ==
IV=jOgu776g2jxEaZ7X21G32Q==
PT=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/
AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w==
CT=ww4y/+3Ad05q/2rwhp9xqg868HqaManGhNsgfrDvjk
41kHqmMsP/34aLt7KdPUatg86fmhAu6Z1JpT6H9MPaVQ== 0 
OK=ww4y/+3Ad05q/2rwhp9xqg868HqaManGhNsgfrDvjk
41kHqmMsP/34aLt7KdPUatg86fmhAu6Z1JpT6H9MPaVQ==
P'=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/
AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w== 0 

```

### See Also

[`AES128_HexMode`](#AES128_HexMode)
[`AES128_BytesMode`](#AES128_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_Bytes"></a>AES128_Bytes
-------------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES128_BytesMode`](#AES128_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES128_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES128_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES128_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Encrypt Method](#M_Aes128_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes128.Decrypt Method](#M_Aes128_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input array *lpData*
must be an exact multiple of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 16 bytes long.
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

This function is equivalent to

```

nRet = AES128_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, "ECB", 0)

```

### Example

```

    Dim nRet As Long
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abPlain() As Byte
    Dim abCipher() As Byte
    Dim nBytes As Long
    
    'FIPS-197
    'C.1 AES-128 (Nk=4, Nr=10)
    'PLAINTEXT: 00112233445566778899aabbccddeeff
    'KEY: 000102030405060708090a0b0c0d0e0f
    
    ' Convert input to bytes
    abKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f")
    abPlain = cnvBytesFromHexStr("00112233445566778899aabbccddeeff")
    abCipher = cnvBytesFromHexStr("69c4e0d86a7b0430d8cdb78070b4c55a")
    
    abBlock = abPlain
    nBytes = UBound(abBlock) - LBound(abBlock) + 1
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    ' Encrypt in one-off process
    nRet = AES128_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), ENCRYPT)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCipher)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abCipher, vbUnicode))
    
    ' Now decrypt back to plain text
    nRet = AES128_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), DECRYPT)
    Debug.Print "P'=" & cnvHexStrFromBytes(abBlock)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abPlain, vbUnicode))

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F
PT=00112233445566778899AABBCCDDEEFF
CT=69C4E0D86A7B0430D8CDB78070B4C55A
OK=69C4E0D86A7B0430D8CDB78070B4C55A
P'=00112233445566778899AABBCCDDEEFF

```

### See Also

[`AES128_BytesMode`](#AES128_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_BytesMode"></a>AES128_BytesMode
---------------------------------------------

Encrypts or decrypts an array of Bytes
using a specified mode.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES128_BytesMode Lib "diCryptoSys.dll" 
	(ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, 
	ByVal bEncrypt As Boolean, 
	ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES128_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES128_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the
initialization vector (IV), or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Encrypt Method](#M_Aes128_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes128.Decrypt Method](#M_Aes128_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Remarks

The input array *lpData*
must be an exact multiple of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 16 bytes long.
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim sCorrect As String
    Dim abKey()  As Byte
    Dim abInitV() As Byte
    Dim abResult() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long

    ' Set up input in byte arrays
    strInput = "Now is the time for all good men"
    sCorrect = "C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E177"
    abKey = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
    abInitV = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
    abData = StrConv(strInput, vbFromUnicode)
    nDataLen = UBound(abData) - LBound(abData) + 1
    
    ' Pre-dimension output array
    ReDim abResult(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = AES128_BytesMode(abResult(0), abData(0), nDataLen, abKey(0), _
        ENCRYPT, "CBC", abInitV(0))
    Debug.Print "CT=" & cnvHexStrFromBytes(abResult)
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back
    nRet = AES128_BytesMode(abData(0), abResult(0), nDataLen, abKey(0), _
        DECRYPT, "CBC", abInitV(0))
    strOutput = StrConv(abData(), vbUnicode)
    Debug.Print "P'=" & strOutput
    
    ' Check
    Debug.Assert (strOutput = strInput)

```

This should result in output as follows:

```

KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E177
OK=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E177
P'=Now is the time for all good men

```

### See Also

[`AES128_Bytes`](#AES128_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_File"></a>AES128_File
-----------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES128_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES128_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES128_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 16 bytes long.
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

This example will encrypt the file "now.txt" in ECB mode
using the 128-bit key
0xfedcba9876543210fedcba9876543210, and then decrypt back to the plain text file
"aesnow.chk" as a check.
Both output files "aesnow.enc" and "aesnow.chk" will be created or
overwritten.

```

Const MY_PATH As String = "C:\Test\"
Dim strFileOut As String, strFileIn As String, strFileChk As String
Dim nRet As Long
Dim abKey() As Byte

' Construct full path names to files
strFileIn = MY_PATH & "now.txt"
strFileOut = MY_PATH & "now.aes128.enc.dat"
strFileChk = MY_PATH & "now.aes128.chk.txt"

' Convert key to byte array
abKey = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
' Encrypt plaintext file to cipher
nRet = AES128_File(strFileOut, strFileIn, abKey(0), ENCRYPT, "ECB", 0)
If nRet <> 0 Then
    Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
End If

' Now decrypt it
nRet = AES128_File(strFileChk, strFileOut, abKey(0), DECRYPT, "ECB", 0)
If nRet <> 0 Then
    Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
End If

```

### See Also

[`AES128_FileExt`](#AES128_FileExt)
[`AES128_FileHex`](#AES128_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_FileExt"></a>AES128_FileExt
-----------------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES128_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = AES128_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  AES128_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`AES128_File`](#AES128_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

For the default behaviour, see [`AES128_File`](#AES128_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

### Example

```

```

### See Also

[`AES128_File`](#AES128_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_FileHex"></a>AES128_FileHex
-----------------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function AES128_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = AES128_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES128_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly 16 bytes/128 bits).
The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly the block size of 16 bytes), except for ECB mode, where it is ignored (use `""`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the 128-bit key
0xfedcba9876543210fedcba9876543210 and initialization vector
0x0123456789abcdef0123456789abcdef. The output file "bigfile.cbc" will be created or
overwritten.

```

    Dim nRet As Long
    nRet = AES128_FileHex("bigfile.cbc", "bigfile.dat", _
        "fedcba9876543210fedcba9876543210", _
        ENCRYPT, "CBC", "0123456789abcdef0123456789abcdef")
    If nRet <> 0 Then
        Debug.Print "AES128_FileHex failed: " & apiErrorLookup(nRet)
    Else
        Debug.Print "AES128_FileHex encrypted file OK"
    End If

```

### See Also

[`AES128_File`](#AES128_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_Final"></a>AES128_Final
-------------------------------------

Closes and clears the AES context.

### VBA/VB6 Syntax

`Public Declare Function AES128_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = AES128_Final(hContext)`

### C/C++ Syntax

`long __stdcall  AES128_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the AES context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Dispose Method](#M_Aes128_Dispose)  

### Remarks

### Example

See the examples in
[`AES128_UpdateHex`](#AES128_UpdateHex)
and [`AES128_Update`](#AES128_Update).

### See Also

[`AES128_Init`](#AES128_Init)
[`AES128_InitHex`](#AES128_InitHex)
[`AES128_UpdateHex`](#AES128_UpdateHex)
[`AES128_Update`](#AES128_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_Hex"></a>AES128_Hex
---------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES128_HexMode`](#AES128_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES128_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES128_Hex(strOutput, strInput, strHexKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  AES128_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput*
should be a multiple of 32 hex characters long (i.e. representing a multiple of 16 bytes).
The key string *szHexKey*
must be exactly 32 hex characters long (i.e. representing exactly 16 bytes).

The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

This function is equivalent to

```

nRet = AES128_HexMode(strOutput, strInput, strHexKey, bEncrypt, "ECB", 0)

```

### Example

This example is taken from FIPS 197 Appendix C.

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    
    'FIPS-197
    'C.1 AES-128 (Nk=4, Nr=10)
    'PLAINTEXT: 00112233445566778899aabbccddeeff
    'KEY: 000102030405060708090a0b0c0d0e0f
    strHexKey = "000102030405060708090a0b0c0d0e0f"
    sPlain = "00112233445566778899aabbccddeeff"
    sCipher = "69c4e0d86a7b0430d8cdb78070b4c55a"
    
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES128_Hex(strOutput, strInput, strHexKey, ENCRYPT)
    Debug.Print "CT=" & strOutput & nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)
    
    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = AES128_Hex(strOutput, strInput, strHexKey, DECRYPT)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Assert (strOutput = sPlain)

```

This should result in output as follows:

```

KY=000102030405060708090a0b0c0d0e0f
PT=00112233445566778899aabbccddeeff
CT=69C4E0D86A7B0430D8CDB78070B4C55A 0 
OK=69c4e0d86a7b0430d8cdb78070b4c55a
P'=00112233445566778899AABBCCDDEEFF 0 

```

### See Also

[`AES128_HexMode`](#AES128_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_HexMode"></a>AES128_HexMode
-----------------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function AES128_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = AES128_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES128_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeString) (String, String, Mode, String)  

### COM/ASP Equivalent

`aes128.HexMode  

Public Function HexMode(ByVal strInput As String, ByVal strHexKey As String, ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As String`

See [`aes128.HexMode`](#x_hexmode).

### Remarks

The length of the input string *szInput*
should be a multiple of 32 hex characters long (i.e. representing a multiple of 16 bytes).
The key string *szHexKey*
must be exactly 32 hex characters long (i.e. representing exactly 16 bytes/128 bits).

The initialization vector *szHexIV*
must be exactly 32 hex characters long (i.e. representing exactly the block size of 16 bytes), 
except for ECB mode, where it is ignored (use `""`).
The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

The examples are from RFC 3602 *The AES-CBC Cipher Algorithm and Its Use with IPsec*

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    Dim strHexIV As String
'Case #1: Encrypting 16 bytes (1 block) using AES-CBC with 128-bit key
'Key       : 0x06a9214036b8a15b512e03d534120006
'IV        : 0x3dafba429d9eb430b422da802c9fac41
'Plaintext : "Single block msg"
'Ciphertext: 0xe353779c1079aeb82708942dbe77181a

    strHexKey = "06a9214036b8a15b512e03d534120006"
    strHexIV = "3dafba429d9eb430b422da802c9fac41"
    sPlain = cnvHexStrFromString("Single block msg")
    sCipher = "e353779c1079aeb82708942dbe77181a"
    
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strHexIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES128_HexMode(strOutput, strInput, strHexKey, ENCRYPT, "CBC", strHexIV)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)
    
    ' Decrypt to check
    strInput = strOutput
    nRet = AES128_HexMode(strOutput, strInput, strHexKey, DECRYPT, "CBC", strHexIV)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Print "OK=" & sPlain
    Debug.Assert (strOutput = sPlain)
    
' Case #4: Encrypting 64 bytes (4 blocks) using AES-CBC with 128-bit key
' Key       : 0x56e47a38c5598974bc46903dba290349
' IV        : 0x8ce82eefbea0da3c44699ed7db51b7d9
' Plaintext : 0xa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
'               b0b1b2b3b4b5b6b7b8b9babbbcbdbebf
'               c0c1c2c3c4c5c6c7c8c9cacbcccdcecf
'               d0d1d2d3d4d5d6d7d8d9dadbdcdddedf
' Ciphertext: 0xc30e32ffedc0774e6aff6af0869f71aa
'               0f3af07a9a31a9c684db207eb0ef8e4e
'               35907aa632c3ffdf868bb7b29d3d46ad
'               83ce9f9a102ee99d49a53e87f4c3da55
    
    strHexKey = "56e47a38c5598974bc46903dba290349"
    strHexIV = "8ce82eefbea0da3c44699ed7db51b7d9"
    sPlain = "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" _
        & "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" _
        & "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" _
        & "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
    sCipher = "c30e32ffedc0774e6aff6af0869f71aa" _
        & "0f3af07a9a31a9c684db207eb0ef8e4e" _
        & "35907aa632c3ffdf868bb7b29d3d46ad" _
        & "83ce9f9a102ee99d49a53e87f4c3da55"
        
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strHexIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES128_HexMode(strOutput, strInput, strHexKey, ENCRYPT, "CBC", strHexIV)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)

    ' Decrypt to check
    strInput = strOutput
    nRet = AES128_HexMode(strOutput, strInput, strHexKey, DECRYPT, "CBC", strHexIV)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Print "OK=" & sPlain
    Debug.Assert (strOutput = sPlain)

```

This should result in output as follows:

```

IV=8ce82eefbea0da3c44699ed7db51b7d9
PT=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf
c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf
CT=C30E32FFEDC0774E6AFF6AF0869F71AA0F3AF07A9A31A9C684DB207EB0EF8E4E
35907AA632C3FFDF868BB7B29D3D46AD83CE9F9A102EE99D49A53E87F4C3DA55 0 
OK=c30e32ffedc0774e6aff6af0869f71aa0f3af07a9a31a9c684db207eb0ef8e4e
35907aa632c3ffdf868bb7b29d3d46ad83ce9f9a102ee99d49a53e87f4c3da55
P'=A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF
C0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF 0 
OK=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf
c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf

```

### See Also

[`AES128_Hex`](#AES128_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_Init"></a>AES128_Init
-----------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES128_Init Lib "diCryptoSys.dll"
    (ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`hContext = AES128_Init(abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES128_Init(const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector,
or zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES128_Update`, `AES128_UpdateHex` or `AES128_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes128.InitEncrypt Method](#M_Aes128_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Aes128.InitDecrypt Method](#M_Aes128_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 16 bytes long.
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
Unlike most other functions in this API, `AES128_Init` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES128_Update`](#AES128_Update).

### See Also

[`AES128_InitHex`](#AES128_InitHex)
[`AES128_UpdateHex`](#AES128_UpdateHex)
[`AES128_Update`](#AES128_Update)
[`AES128_Final`](#AES128_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_InitError"></a>AES128_InitError
---------------------------------------------

Returns the error code after an unsuccessful call to
`AES128_Init` or `AES128_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function AES128_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = AES128_InitError()`

### C/C++ Syntax

`long __stdcall  AES128_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`AES128_Init` or `AES128_InitHex`.

### .NET Equivalent

[Aes128.ErrCode Property](#M_Aes128_ErrCodeProperty)  

### Remarks

### Example

```

    Dim hContext As Long
    Dim nRet As Long
    
    ' Try to initialise with an invalid key
    hContext = AES128_InitHex("THIS IS NOT HEX!", ENCRYPT, _
        "CBC", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES128_InitError()
        Debug.Print "AES128_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If
    
    ' Try with an invalid mode
    hContext = AES128_InitHex("8A05FC5E095AF4848A08D328D3688E3D", _
        ENCRYPT, "XXX", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES128_InitError()
        Debug.Print "AES128_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If

```

This should produce the output

```

AES128_InitHex failed (Invalid key)
AES128_InitHex failed (Invalid mode)

```

### See Also

[`API_ErrorLookup`](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_InitHex"></a>AES128_InitHex
-----------------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are passed in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function AES128_InitHex Lib "diCryptoSys.dll"
    (ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`hContext = AES128_InitHex(strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES128_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector
in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES128_Update`, `AES128_UpdateHex` or `AES128_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes128.InitEncrypt Method](#M_Aes128_InitEncrypt_StringModeString) (String, Mode, String)  

[Aes128.InitDecrypt Method](#M_Aes128_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly 16 bytes/128 bits).

The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly the block size of 16 bytes), except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `AES128_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES128_UpdateHex`](#AES128_UpdateHex).

### See Also

[`AES128_Init`](#AES128_Init)
[`AES128_UpdateHex`](#AES128_UpdateHex)
[`AES128_Update`](#AES128_Update)
[`AES128_Final`](#AES128_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_Update"></a>AES128_Update
---------------------------------------

Carries out the AES transformation function on a byte array
according to the direction
and mode set up by an earlier call to `AES128_Init()` or `AES128_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES128_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = AES128_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  AES128_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES128_Init()` or `AES128_InitHex()`.

*lpData*
:   [in,out] array containing the input
to be processed by the AES function and to receive the output.

*nDataLen*
:   [in] containing length of the data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Update Method](#M_Aes128_Update_Byte) (Byte[])  

### Remarks

The input array *lpData*
must be an exact multiple of 16 bytes long.
If not, an error code will be returned.
Note that the output overwrites the input.

### Example

This example carries out the third (I=2) Monte Carlo MOVS test in ECB decrypt mode.
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

    Dim nRet As Long
    Dim hContext As Long
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abCorrect() As Byte
    Dim j As Integer
    
' File: ecb_d_m.txt
' KEYSIZE=128 I=2
' KEY=A7BC3BD0EABD9EBA981E23E6FFC9C9C2
' CT=E3FD51123B48A2E2AB1DB29894202222
' PT=877B88A77AEF04F05546539E17259F53
     ' Convert to Byte format
    abKey = cnvBytesFromHexStr("A7BC3BD0EABD9EBA981E23E6FFC9C9C2")
    abBlock = cnvBytesFromHexStr("E3FD51123B48A2E2AB1DB29894202222")
    abCorrect = cnvBytesFromHexStr("877B88A77AEF04F05546539E17259F53")
    
    Debug.Print "AES Monte Carlo ECB Mode Decrypt:"
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    
    hContext = AES128_Init(abKey(0), DECRYPT, "ECB", 0)
    If hContext = 0 Then
        MsgBox "Failed to set context", vbCritical
        Exit Function
    End If
    ' Do 10,000 times
    For j = 0 To 9999
        nRet = AES128_Update(hContext, abBlock(0), 16)
    Next
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCorrect)
    nRet = AES128_Final(hContext)
    
    Debug.Assert (StrConv(abCorrect, vbUnicode) = StrConv(abBlock, vbUnicode))

```

This should result in output as follows:

```

AES Monte Carlo ECB Mode Decrypt:
KY=A7BC3BD0EABD9EBA981E23E6FFC9C9C2
CT=E3FD51123B48A2E2AB1DB29894202222
PT=877B88A77AEF04F05546539E17259F53
OK=877B88A77AEF04F05546539E17259F53

```

### See Also

[`AES128_Init`](#AES128_Init)
[`AES128_InitHex`](#AES128_InitHex)
[`AES128_UpdateHex`](#AES128_UpdateHex)
[`AES128_Final`](#AES128_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES128_UpdateHex"></a>AES128_UpdateHex
---------------------------------------------

Carries out the AES transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `AES128_Init()` or `AES128_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES128_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = AES128_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  AES128_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES128_Init()` or `AES128_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the AES function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes128.Update Method](#M_Aes128_Update_String) (String)  

### Remarks

The length of the input string *szHexString* must be a multiple of 32 hex characters long 
(i.e. representing a multiple of the block size of 16 bytes).

If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f].
Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

This example carries out the third (I=2) [[MOVS](#MOVS)] Monte Carlo test in CBC encrypt mode
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

Dim nRet As Long
Dim hContext As Long
Dim sBlock As String
Dim strHexKey As String
Dim strIV As String
Dim sNext As String
Dim sLast As String
Dim sCorrect As String
Dim j As Integer

' cbc_e_m.txt
' KEYSIZE=128 I=2
' KEY=93286764A85146730E641888DB34EB47
' IV=192D9B3AA10BB2F7846CCBA0085C657A
' PT=983BF6F5A6DFBCDAA19370666E83A99A
' CT=40D8DAF6D1FDA0A073B3BD18B7695D2E

strHexKey = "93286764A85146730E641888DB34EB47"
strIV = "192D9B3AA10BB2F7846CCBA0085C657A"
sBlock = "983BF6F5A6DFBCDAA19370666E83A99A"
sCorrect = "40D8DAF6D1FDA0A073B3BD18B7695D2E"

Debug.Print "AES Monte Carlo CBC Mode Encrypt:"
Debug.Print "KY=" & strHexKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & sBlock

hContext = AES128_InitHex(strHexKey, ENCRYPT, "CBC", strIV)
If hContext = 0 Then
    MsgBox "Failed to set context", vbCritical
    Exit Function
End If
' Do 10,000 times
sNext = sBlock
For j = 0 To 9999
    sBlock = sNext
    nRet = AES128_UpdateHex(hContext, sBlock)
    If j = 0 Then
        sNext = strIV
    Else
        sNext = sLast
    End If
    sLast = sBlock
Next
Debug.Print "CT=" & sBlock
Debug.Print "OK=" & sCorrect
nRet = AES128_Final(hContext)

Debug.Assert (sCorrect = sBlock)

```

This should result in output as follows:

```

AES Monte Carlo CBC Mode Encrypt:
KY=93286764A85146730E641888DB34EB47
IV=192D9B3AA10BB2F7846CCBA0085C657A
PT=983BF6F5A6DFBCDAA19370666E83A99A
CT=40D8DAF6D1FDA0A073B3BD18B7695D2E
OK=40D8DAF6D1FDA0A073B3BD18B7695D2E

```

### See Also

[`AES128_Init`](#AES128_Init)
[`AES128_InitHex`](#AES128_InitHex)
[`AES128_Update`](#AES128_Update)
[`AES128_Final`](#AES128_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_B64Mode"></a>AES192_B64Mode
-----------------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function AES192_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = AES192_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  AES192_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Encrypt Method](#M_Aes192_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Aes192.Decrypt Method](#M_Aes192_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (16 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 16 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* must represent exactly 24 bytes, the required key length.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

This example is the same data as for [`AES192_HexMode`](#AES192_HexMode),
except the data is in base64 format.

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strIV As String
Dim bEncrypt As Boolean
Dim sCorrect As String

strInput = "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y" _
& "9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w=="
strKey = "VuR6OMVZiXS8RpA9uikDSQapIUA2uKFb"
strIV = "jOgu776g2jxEaZ7X21G32Q=="
sCorrect = "c4I3A2393p3aM3T6GCYAxTjZGHoCmXJdCn/b6" _
& "ETXdXgVOeQBtVl8u/qDbv0i2ZjSFgXY3zQGIkF7kRRnteUaEg=="

' Set strOutput to be same length as strInput
strOutput = String(Len(strInput), " ")

Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
nRet = AES192_B64Mode(strOutput, strInput, strKey, ENCRYPT, "CBC", strIV)
Debug.Print "CT=" & strOutput; nRet
Debug.Print "OK=" & sCorrect

strInput = strOutput
nRet = AES192_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=VuR6OMVZiXS8RpA9uikDSQapIUA2uKFb
IV=jOgu776g2jxEaZ7X21G32Q==
PT=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/
AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w==
CT=c4I3A2393p3aM3T6GCYAxTjZGHoCmXJdCn/b6ETXdXg
VOeQBtVl8u/qDbv0i2ZjSFgXY3zQGIkF7kRRnteUaEg== 0 
OK=c4I3A2393p3aM3T6GCYAxTjZGHoCmXJdCn/b6ETXdXg
VOeQBtVl8u/qDbv0i2ZjSFgXY3zQGIkF7kRRnteUaEg==
P'=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/
AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w== 0 

```

### See Also

[`AES192_HexMode`](#AES192_HexMode)
[`AES192_BytesMode`](#AES192_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_Bytes"></a>AES192_Bytes
-------------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES192_BytesMode`](#AES192_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES192_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES192_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES192_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Encrypt Method](#M_Aes192_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes192.Decrypt Method](#M_Aes192_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 24 bytes (i.e. 192 bits) long.
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

This function is equivalent to

```

nRet = AES192_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, "ECB", 0)

```

### Example

```

    Dim nRet As Long
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abPlain() As Byte
    Dim abCipher() As Byte
    Dim nBytes As Long
    
    'FIPS-197
    'C.2 AES-192 (Nk=6, Nr=12)
    'PLAINTEXT: 00112233445566778899aabbccddeeff
    'KEY: 000102030405060708090a0b0c0d0e0f1011121314151617
    strHexKey = "000102030405060708090a0b0c0d0e0f1011121314151617"
    sPlain = "00112233445566778899aabbccddeeff"
    sCipher = "dda97ca4864cdfe06eaf70a0ec0d7191"
    
    ' Convert input to bytes
    abKey = cnvBytesFromHexStr(strHexKey)
    abPlain = cnvBytesFromHexStr(sPlain)
    abCipher = cnvBytesFromHexStr(sCipher)
    
    abBlock = abPlain
    nBytes = UBound(abBlock) - LBound(abBlock) + 1
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    ' Encrypt in one-off process
    nRet = AES192_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), ENCRYPT)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCipher)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abCipher, vbUnicode))
    
    ' Now decrypt back to plain text
    nRet = AES192_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), DECRYPT)
    Debug.Print "P'=" & cnvHexStrFromBytes(abBlock)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abPlain, vbUnicode))

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F1011121314151617
PT=00112233445566778899AABBCCDDEEFF
CT=DDA97CA4864CDFE06EAF70A0EC0D7191
OK=DDA97CA4864CDFE06EAF70A0EC0D7191
P'=00112233445566778899AABBCCDDEEFF

```

### See Also

[`AES192_BytesMode`](#AES192_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_BytesMode"></a>AES192_BytesMode
---------------------------------------------

Encrypts or decrypts an array of Bytes
using a specified mode.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES192_BytesMode Lib "diCryptoSys.dll" 
	(ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, 
	ByVal bEncrypt As Boolean, 
	ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES192_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES192_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the
initialization vector (IV), or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Encrypt Method](#M_Aes192_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes192.Decrypt Method](#M_Aes192_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 24 bytes long (i.e. 192 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim sCorrect As String
    Dim abKey()  As Byte
    Dim abInitV() As Byte
    Dim abResult() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long

    ' Set up input in byte arrays
    strInput = "Now is the time for all good men"
    sCorrect = "4BABDC251410549C57390F7FA3F26366F9AC1FABD1354ECA2265F475A2C3D5AF"
    abKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f1011121314151617")
    abInitV = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
    abData = StrConv(strInput, vbFromUnicode)
    nDataLen = UBound(abData) - LBound(abData) + 1
    
    ' Pre-dimension output array
    ReDim abResult(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = AES192_BytesMode(abResult(0), abData(0), nDataLen, abKey(0), _
        ENCRYPT, "CBC", abInitV(0))
    Debug.Print "CT=" & cnvHexStrFromBytes(abResult)
    Debug.Print "OK=" & sCorrect
    Debug.Assert (sCorrect = cnvHexStrFromBytes(abResult))

    ' Now decrypt back
    nRet = AES192_BytesMode(abData(0), abResult(0), nDataLen, abKey(0), _
        DECRYPT, "CBC", abInitV(0))
    strOutput = StrConv(abData(), vbUnicode)
    Debug.Print "P'=" & strOutput
    
    ' Check
    Debug.Assert (strOutput = strInput)

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F1011121314151617
IV=FEDCBA9876543210FEDCBA9876543210
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=4BABDC251410549C57390F7FA3F26366F9AC1FABD1354ECA2265F475A2C3D5AF
OK=4BABDC251410549C57390F7FA3F26366F9AC1FABD1354ECA2265F475A2C3D5AF
P'=Now is the time for all good men

```

### See Also

[`AES192_Bytes`](#AES192_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_File"></a>AES192_File
-----------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES192_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES192_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES192_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 24 bytes long (i.e. 192 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

This example will encrypt the file "now.txt" in ECB mode
using the 128-bit key
000102030405060708090a0b0c0d0e0f1011121314151617, and then decrypt back to the plain text file
"aesnow.chk" as a check.
Both output files "aesnow.enc" and "aesnow.chk" will be created or
overwritten.

```

    Const MY_PATH As String = "C:\Test\"
    Dim strFileOut As String, strFileIn As String, strFileChk As String
    Dim nRet As Long
    Dim abKey() As Byte

    ' Construct full path names to files
    strFileIn = MY_PATH & "now.txt"
    strFileOut = MY_PATH & "now.aes192.enc.data"
    strFileChk = MY_PATH & "now.aes192.chk.txt"

    ' Convert key to byte array
    abKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f1011121314151617")
    ' Encrypt plaintext file to cipher
    nRet = AES192_File(strFileOut, strFileIn, abKey(0), ENCRYPT, "ECB", 0)
    If nRet <> 0 Then
        Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
    End If

    ' Now decrypt it
    nRet = AES192_File(strFileChk, strFileOut, abKey(0), DECRYPT, "ECB", 0)
    If nRet <> 0 Then
        Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
    End If

```

### See Also

[`AES192_FileExt`](#AES192_FileExt)
[`AES192_FileHex`](#AES192_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_FileExt"></a>AES192_FileExt
-----------------------------------------

Encrypts or decrypts a file using a specified mode with extended options. 

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES192_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = AES192_FileExt(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  AES192_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`AES192_File`](#AES192_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

### Example

For the default behaviour, see [`AES192_File`](#AES192_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

```

```

### See Also

[`AES192_File`](#AES192_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_FileHex"></a>AES192_FileHex
-----------------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function AES192_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = AES192_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES192_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 48 hexadecimal characters long
(i.e. representing exactly 24 bytes/192 bits).
The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing the block size of exactly 16 bytes), except for ECB mode, where it is ignored (use `""`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the 192-bit key
000102030405060708090a0b0c0d0e0f1011121314151617 and initialization vector
0x0123456789abcdef0123456789abcdef. The output file "bigfile.cbc" will be created or
overwritten.

```

    Dim nRet As Long
    nRet = AES192_FileHex("bigfile.cbc", "bigfile.dat", _
        "000102030405060708090a0b0c0d0e0f1011121314151617", _
        ENCRYPT, "CBC", "0123456789abcdef0123456789abcdef")
    If nRet <> 0 Then
        Debug.Print "AES192_FileHex failed: " & apiErrorLookup(nRet)
    Else
        Debug.Print "AES192_FileHex encrypted file OK"
    End If

```

### See Also

[`AES192_File`](#AES192_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_Final"></a>AES192_Final
-------------------------------------

Closes and clears the AES context.

### VBA/VB6 Syntax

`Public Declare Function AES192_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = AES192_Final(hContext)`

### C/C++ Syntax

`long __stdcall  AES192_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the AES context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Dispose Method](#M_Aes192_Dispose)  

### Remarks

### Example

See the examples in
[`AES192_UpdateHex`](#AES192_UpdateHex)
and [`AES192_Update`](#AES192_Update).

### See Also

[`AES192_Init`](#AES192_Init)
[`AES192_InitHex`](#AES192_InitHex)
[`AES192_UpdateHex`](#AES192_UpdateHex)
[`AES192_Update`](#AES192_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_Hex"></a>AES192_Hex
---------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES192_HexMode`](#AES192_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES192_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES192_Hex(strOutput, strInput, strHexKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  AES192_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Encrypt Method](#M_Aes192_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes192.Decrypt Method](#M_Aes192_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput*
must be a multiple of 32 hex characters long (i.e. representing a multiple of the block size of 16 bytes).
The key string *szHexKey*
must be exactly 48 hex characters long (i.e. representing exactly 24 bytes/192 bits).

The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

This function is equivalent to

```

nRet = AES192_HexMode(strOutput, strInput, strHexKey, bEncrypt, "ECB", 0)

```

### Example

This example is taken from FIPS 197 Appendix C.

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    
    'FIPS-197
    'C.2 AES-192 (Nk=6, Nr=12)
    'PLAINTEXT: 00112233445566778899aabbccddeeff
    'KEY: 000102030405060708090a0b0c0d0e0f1011121314151617
    strHexKey = "000102030405060708090a0b0c0d0e0f1011121314151617"
    sPlain = "00112233445566778899aabbccddeeff"
    sCipher = "dda97ca4864cdfe06eaf70a0ec0d7191"
    
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES192_Hex(strOutput, strInput, strHexKey, ENCRYPT)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    
    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = AES192_Hex(strOutput, strInput, strHexKey, DECRYPT)
    Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=000102030405060708090a0b0c0d0e0f1011121314151617
PT=00112233445566778899aabbccddeeff
CT=DDA97CA4864CDFE06EAF70A0EC0D7191 0 
OK=dda97ca4864cdfe06eaf70a0ec0d7191
P'=00112233445566778899AABBCCDDEEFF 0 

```

### See Also

[`AES192_HexMode`](#AES192_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_HexMode"></a>AES192_HexMode
-----------------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function AES192_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = AES192_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES192_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Encrypt Method](#M_Aes192_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes192.Decrypt Method](#M_Aes192_Decrypt_StringStringModeString) (String, String, Mode, String)  

### Remarks

The length of the input string *szInput*
must be a multiple of 32 hex characters long (i.e. representing a multiple of the block size of 16 bytes).
The key string *szHexKey*
must be exactly 48 hex characters long (i.e. representing exactly 24 bytes/192 bits).

The initialization vector *szHexIV*
must be exactly 32 hex characters long (i.e. representing the block size of exactly 16 bytes), 
except for ECB mode, where it is ignored (use `""`).
The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    Dim strHexIV As String
    
' Encrypting 64 bytes (4 blocks) using AES-CBC with 192-bit key
    
    strHexKey = "56e47a38c5598974bc46903dba29034906a9214036b8a15b"
    strHexIV = "8ce82eefbea0da3c44699ed7db51b7d9"
    sPlain = "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" _
        & "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" _
        & "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" _
        & "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
    sCipher = "738237036dfdde9dda3374fa182600c5" _
        & "38d9187a0299725d0a7fdbe844d77578" _
        & "1539e401b5597cbbfa836efd22d998d2" _
        & "1605d8df340622417b911467b5e51a12" _
        
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strHexIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES192_HexMode(strOutput, strInput, strHexKey, ENCRYPT, "CBC", strHexIV)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)

    ' Decrypt to check
    strInput = strOutput
    nRet = AES192_HexMode(strOutput, strInput, strHexKey, DECRYPT, "CBC", strHexIV)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Print "OK=" & sPlain
    Debug.Assert (strOutput = sPlain)

```

This should result in output as follows:

```

KY=56e47a38c5598974bc46903dba29034906a9214036b8a15b
IV=8ce82eefbea0da3c44699ed7db51b7d9
PT=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7
b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d
1d2d3d4d5d6d7d8d9dadbdcdddedf
CT=738237036DFDDE9DDA3374FA182600C538D9187A0299725D
0A7FDBE844D775781539E401B5597CBBFA836EFD22D998D2160
5D8DF340622417B911467B5E51A12 0 
OK=738237036dfdde9dda3374fa182600c538d9187a0299725d
0a7fdbe844d775781539e401b5597cbbfa836efd22d998d2160
5d8df340622417b911467b5e51a12
P'=A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7
B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D
1D2D3D4D5D6D7D8D9DADBDCDDDEDF 0 
OK=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7
b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d
1d2d3d4d5d6d7d8d9dadbdcdddedf

```

### See Also

[`AES192_Hex`](#AES192_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_Init"></a>AES192_Init
-----------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES192_Init Lib "diCryptoSys.dll"
    (ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`hContext = AES192_Init(abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES192_Init(const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector,
or zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES192_Update`, `AES192_UpdateHex` or `AES192_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes192.InitEncrypt Method](#M_Aes192_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Aes192.InitDecrypt Method](#M_Aes192_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 24 bytes long (i.e. 192 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
Unlike most other functions in this API, `AES192_Init` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES192_Update`](#AES192_Update).

### See Also

[`AES192_InitHex`](#AES192_InitHex)
[`AES192_UpdateHex`](#AES192_UpdateHex)
[`AES192_Update`](#AES192_Update)
[`AES192_Final`](#AES192_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_InitError"></a>AES192_InitError
---------------------------------------------

Returns the error code after an unsuccessful call to
`AES192_Init` or `AES192_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function AES192_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = AES192_InitError()`

### C/C++ Syntax

`long __stdcall  AES192_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`AES192_Init` or `AES192_InitHex`.

### .NET Equivalent

[Aes192.ErrCode Property](#M_Aes192_ErrCodeProperty)  

### Remarks

### Example

```

    Dim hContext As Long
    Dim nRet As Long
    
    ' Try to initialise with an invalid key
    hContext = AES192_InitHex("THIS IS NOT HEX!", ENCRYPT, _
        "CBC", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES192_InitError()
        Debug.Print "AES192_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If
    
    ' Try with an invalid mode
    hContext = AES192_InitHex("000102030405060708090a0b0c0d0e0f1011121314151617", _
        ENCRYPT, "XXX", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES192_InitError()
        Debug.Print "AES192_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If

```

This should produce the output

```

AES192_InitHex failed (Invalid key)
AES192_InitHex failed (Invalid mode)

```

### See Also

[`API_ErrorLookup`](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_InitHex"></a>AES192_InitHex
-----------------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are passed in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function AES192_InitHex Lib "diCryptoSys.dll"
    (ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`hContext = AES192_InitHex(strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES192_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector
in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES192_Update`, `AES192_UpdateHex` or `AES192_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes192.InitEncrypt Method](#M_Aes192_InitEncrypt_StringModeString) (String, Mode, String)  

[Aes192.InitDecrypt Method](#M_Aes192_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 48 hexadecimal characters long
(i.e. representing exactly 24 bytes/192 bits).

The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly the block size of 16 bytes), except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `AES192_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES192_UpdateHex`](#AES192_UpdateHex).

### See Also

[`AES192_Init`](#AES192_Init)
[`AES192_UpdateHex`](#AES192_UpdateHex)
[`AES192_Update`](#AES192_Update)
[`AES192_Final`](#AES192_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_Update"></a>AES192_Update
---------------------------------------

Carries out the AES transformation function on a byte array
according to the direction
and mode set up by an earlier call to `AES192_Init()` or `AES192_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES192_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = AES192_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  AES192_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES192_Init()` or `AES192_InitHex()`.

*lpData*
:   [in,out] array containing the input
to be processed by the AES function and to receive the output.

*nDataLen*
:   [in] containing length of the data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Update Method](#M_Aes192_Update_Byte) (Byte[])  

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
Note that the output overwrites the input.

### Example

This example carries out the third (I=2) Monte Carlo MOVS test in CBC encrypt mode.
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

    Dim nRet As Long
    Dim hContext As Long
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abCorrect() As Byte
    Dim j As Integer
    
' File: ecb_d_m.txt
' KEYSIZE=192 I=2
' KEY=EF334C87288C43DE84E276D5CCD586228C8EA3A264D2DB0E
' CT=CC01684BE9B29ED01EA7923E7D2380AA
' PT=8726B4E66D6B8FBAA22D42981A5A40CC
     ' Convert to Byte format
    abKey = cnvBytesFromHexStr("EF334C87288C43DE84E276D5CCD586228C8EA3A264D2DB0E")
    abBlock = cnvBytesFromHexStr("CC01684BE9B29ED01EA7923E7D2380AA")
    abCorrect = cnvBytesFromHexStr("8726B4E66D6B8FBAA22D42981A5A40CC")
    
    Debug.Print "AES Monte Carlo ECB Mode Decrypt:"
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    
    hContext = AES192_Init(abKey(0), DECRYPT, "ECB", 0)
    If hContext = 0 Then
        MsgBox "Failed to set context", vbCritical
        Exit Function
    End If
    ' Do 10,000 times
    For j = 0 To 9999
        nRet = AES192_Update(hContext, abBlock(0), 16)
    Next
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCorrect)
    nRet = AES192_Final(hContext)
    
    Debug.Assert (StrConv(abCorrect, vbUnicode) = StrConv(abBlock, vbUnicode))

```

This should result in output as follows:

```

AES Monte Carlo ECB Mode Decrypt:
KY=EF334C87288C43DE84E276D5CCD586228C8EA3A264D2DB0E
CT=CC01684BE9B29ED01EA7923E7D2380AA
PT=8726B4E66D6B8FBAA22D42981A5A40CC
OK=8726B4E66D6B8FBAA22D42981A5A40CC

```

### See Also

[`AES192_Init`](#AES192_Init)
[`AES192_InitHex`](#AES192_InitHex)
[`AES192_UpdateHex`](#AES192_UpdateHex)
[`AES192_Final`](#AES192_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES192_UpdateHex"></a>AES192_UpdateHex
---------------------------------------------

Carries out the AES transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `AES192_Init()` or `AES192_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES192_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = AES192_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  AES192_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES192_Init()` or `AES192_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the AES function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes192.Update Method](#M_Aes192_Update_String) (String)  

### Remarks

*szHexString*
The length of the input string *szHexString* must be a multiple of 32 hex characters long 
(i.e. representing a multiple of the block size of 16 bytes).

If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f].
Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

This example carries out the third (I=2) [[MOVS](#MOVS)] Monte Carlo test in CBC encrypt mode
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

    Dim nRet As Long
    Dim hContext As Long
    Dim sBlock As String
    Dim strHexKey As String
    Dim strIV As String
    Dim sNext As String
    Dim sLast As String
    Dim sCorrect As String
    Dim j As Integer
  
' cbc_e_m.txt
' KEYSIZE=192 I=2
' KEY=74D3414C2374367BFD4560CED3172B0E57571D88A2E13874
' IV=869C061BE9CFEAB5D285B0724A9A8970
' PT=C6FB25A188CF7F3F24B07896C0C76D90
' CT=9E58A52B3840DBE16E8063A18220FEE4

    
    strHexKey = "74D3414C2374367BFD4560CED3172B0E57571D88A2E13874"
    strIV = "869C061BE9CFEAB5D285B0724A9A8970"
    sBlock = "C6FB25A188CF7F3F24B07896C0C76D90"
    sCorrect = "9E58A52B3840DBE16E8063A18220FEE4"
    
    Debug.Print "AES Monte Carlo CBC Mode Encrypt:"
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strIV
    Debug.Print "PT=" & sBlock
    
    hContext = AES192_InitHex(strHexKey, ENCRYPT, "CBC", strIV)
    If hContext = 0 Then
        MsgBox "Failed to set context", vbCritical
        Exit Function
    End If
    ' Do 10,000 times
    sNext = sBlock
    For j = 0 To 9999
        sBlock = sNext
        nRet = AES192_UpdateHex(hContext, sBlock)
        If j = 0 Then
            sNext = strIV
        Else
            sNext = sLast
        End If
        sLast = sBlock
    Next
    Debug.Print "CT=" & sBlock
    Debug.Print "OK=" & sCorrect
    nRet = AES192_Final(hContext)
    
    Debug.Assert (sCorrect = sBlock)

```

This should result in output as follows:

```

AES Monte Carlo CBC Mode Encrypt:
KY=74D3414C2374367BFD4560CED3172B0E57571D88A2E13874
IV=869C061BE9CFEAB5D285B0724A9A8970
PT=C6FB25A188CF7F3F24B07896C0C76D90
CT=9E58A52B3840DBE16E8063A18220FEE4
OK=9E58A52B3840DBE16E8063A18220FEE4

```

### See Also

[`AES192_Init`](#AES192_Init)
[`AES192_InitHex`](#AES192_InitHex)
[`AES192_Update`](#AES192_Update)
[`AES192_Final`](#AES192_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_B64Mode"></a>AES256_B64Mode
-----------------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function AES256_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = AES256_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  AES256_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (16 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 16 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* must represent exactly 32 bytes, the required key length.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

This example is the same data as for [`AES256_HexMode`](#AES256_HexMode),
except the data is in base64 format.

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strIV As String
Dim bEncrypt As Boolean
Dim sCorrect As String

strInput = "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/" _
& "AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w=="
strKey = "VuR6OMVZiXS8RpA9uikDSQapIUA2uKFbUS4D1TQSAAY="
strIV = "jOgu776g2jxEaZ7X21G32Q=="
sCorrect = "KECaKYK9LPfONDp9Q/aSf9uexTK7pWnuyS5XognE/" _
& "bpZrboFpchUaU3cn3mRwBY05yvrT+AjbLOxGaRjiR40bw=="

' Set strOutput to be same length as strInput
strOutput = String(Len(strInput), " ")

Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
nRet = AES256_B64Mode(strOutput, strInput, strKey, ENCRYPT, "CBC", strIV)
Debug.Print "CT=" & strOutput; nRet
Debug.Print "OK=" & sCorrect

strInput = strOutput
nRet = AES256_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=VuR6OMVZiXS8RpA9uikDSQapIUA2uKFbUS4D1TQSAAY=
IV=jOgu776g2jxEaZ7X21G32Q==
PT=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/A
wcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w==
CT=KECaKYK9LPfONDp9Q/aSf9uexTK7pWnuyS5XognE/bpZ
rboFpchUaU3cn3mRwBY05yvrT+AjbLOxGaRjiR40bw== 0 
OK=KECaKYK9LPfONDp9Q/aSf9uexTK7pWnuyS5XognE/bpZ
rboFpchUaU3cn3mRwBY05yvrT+AjbLOxGaRjiR40bw==
P'=oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/A
wcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3w== 0 

```

### See Also

[`AES256_HexMode`](#AES256_HexMode)
[`AES256_BytesMode`](#AES256_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_Bytes"></a>AES256_Bytes
-------------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES256_BytesMode`](#AES256_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES256_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES256_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES256_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Encrypt Method](#M_Aes256_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes256.Decrypt Method](#M_Aes256_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 32 bytes long (i.e. 256 bits).
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

This function is equivalent to

```

nRet = AES256_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, "ECB", 0)

```

### Example

```

    Dim nRet As Long
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abPlain() As Byte
    Dim abCipher() As Byte
    Dim nBytes As Long
    
'FIPS-197
'C.3 AES-256 (Nk=8, Nr=14)
'PLAINTEXT: 00112233445566778899aabbccddeeff
'KEY: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
' round[14].output 8ea2b7ca516745bfeafc49904b496089

    strHexKey = _
    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
    sPlain = "00112233445566778899aabbccddeeff"
    sCipher = "8ea2b7ca516745bfeafc49904b496089"
    
    ' Convert input to bytes
    abKey = cnvBytesFromHexStr(strHexKey)
    abPlain = cnvBytesFromHexStr(sPlain)
    abCipher = cnvBytesFromHexStr(sCipher)
    
    abBlock = abPlain
    nBytes = UBound(abBlock) - LBound(abBlock) + 1
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    ' Encrypt in one-off process
    nRet = AES256_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), ENCRYPT)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCipher)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abCipher, vbUnicode))
    
    ' Now decrypt back to plain text
    nRet = AES256_Bytes(abBlock(0), abBlock(0), nBytes, abKey(0), DECRYPT)
    Debug.Print "P'=" & cnvHexStrFromBytes(abBlock)
    Debug.Assert (StrConv(abBlock, vbUnicode) = StrConv(abPlain, vbUnicode))

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
PT=00112233445566778899AABBCCDDEEFF
CT=8EA2B7CA516745BFEAFC49904B496089
OK=8EA2B7CA516745BFEAFC49904B496089
P'=00112233445566778899AABBCCDDEEFF

```

### See Also

[`AES256_BytesMode`](#AES256_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_BytesMode"></a>AES256_BytesMode
---------------------------------------------

Encrypts or decrypts an array of Bytes
using a specified mode.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES256_BytesMode Lib "diCryptoSys.dll" 
	(ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, 
	ByVal bEncrypt As Boolean, 
	ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES256_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  AES256_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the
initialization vector (IV), or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Encrypt Method](#M_Aes256_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Aes256.Decrypt Method](#M_Aes256_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
The key array *abKey()*
must be exactly 32 bytes long (i.e. 256 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
The output array *lpOutput* must be at least as long as the input array.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim sCorrect As String
    Dim abKey()  As Byte
    Dim abInitV() As Byte
    Dim abResult() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long

    ' Set up input in byte arrays
    strInput = "Now is the time for all good men"
    sCorrect = "36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6"
    abKey = _
    cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
    abInitV = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
    abData = StrConv(strInput, vbFromUnicode)
    nDataLen = UBound(abData) - LBound(abData) + 1
    
    ' Pre-dimension output array
    ReDim abResult(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = AES256_BytesMode(abResult(0), abData(0), nDataLen, abKey(0), _
        ENCRYPT, "CBC", abInitV(0))
    Debug.Print "CT=" & cnvHexStrFromBytes(abResult)
    Debug.Print "OK=" & sCorrect
    Debug.Assert (sCorrect = cnvHexStrFromBytes(abResult))

    ' Now decrypt back
    nRet = AES256_BytesMode(abData(0), abResult(0), nDataLen, abKey(0), _
        DECRYPT, "CBC", abInitV(0))
    strOutput = StrConv(abData(), vbUnicode)
    Debug.Print "P'=" & strOutput
    
    ' Check
    Debug.Assert (strOutput = strInput)

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
IV=FEDCBA9876543210FEDCBA9876543210
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6
OK=36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6
P'=Now is the time for all good men

```

### See Also

[`AES256_Bytes`](#AES256_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_File"></a>AES256_File
-----------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES256_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = AES256_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES256_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 32 bytes long (i.e. 256 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

This example will encrypt the file "now.txt" in ECB mode
using the 256-bit key
0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f, 
and then decrypt back to the plain text file
"aesnow.chk" as a check.
Both output files "aesnow.enc" and "aesnow.chk" will be created or
overwritten.

```

    Const MY_PATH As String = "C:\Test\"
    Dim strFileOut As String, strFileIn As String, strFileChk As String
    Dim nRet As Long
    Dim abKey() As Byte

    ' Construct full path names to files
    strFileIn = MY_PATH & "now.txt"
    strFileOut = MY_PATH & "now.aes256.enc.dat"
    strFileChk = MY_PATH & "now.aes256.chk.txt"

    ' Convert key to byte array
    abKey = _
cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
    ' Encrypt plaintext file to cipher
    nRet = AES256_File(strFileOut, strFileIn, abKey(0), ENCRYPT, "ECB", 0)
    If nRet <> 0 Then
        Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
    End If

    ' Now decrypt it
    nRet = AES256_File(strFileChk, strFileOut, abKey(0), DECRYPT, "ECB", 0)
    If nRet <> 0 Then
        Debug.Print "Error " & nRet & ": " & apiErrorLookup(nRet)
    End If

```

### See Also

[`AES256_FileExt`](#AES256_FileExt)
[`AES256_FileHex`](#AES256_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_FileExt"></a>AES256_FileExt
-----------------------------------------

Encrypts or decrypts a file using a specified mode with extended options. 

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function AES256_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = AES256_FileExt(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  AES256_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`AES256_File`](#AES256_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

For the default behaviour, see [`AES256_File`](#AES256_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

### Example

```

```

### See Also

[`AES256_File`](#AES256_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_FileHex"></a>AES256_FileHex
-----------------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function AES256_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = AES256_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES256_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 64 hexadecimal characters long
(i.e. representing exactly 32 bytes/256 bits).
The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly the block size of 16 bytes), except for ECB mode, where it is ignored (use `""`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the 256-bit key
`0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f` and initialization vector
`0x0123456789abcdef0123456789abcdef`. The output file "bigfile.cbc" will be created or
overwritten.

```

Dim nRet As Long
nRet = AES256_FileHex("bigfile.cbc", "bigfile.dat", _
    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", _
    ENCRYPT, "CBC", "0123456789abcdef0123456789abcdef")
If nRet <> 0 Then
    Debug.Print "AES256_FileHex failed: " & apiErrorLookup(nRet)
Else
    Debug.Print "AES256_FileHex encrypted file OK"
End If

```

### See Also

[`AES256_File`](#AES256_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_Final"></a>AES256_Final
-------------------------------------

Closes and clears the AES context.

### VBA/VB6 Syntax

`Public Declare Function AES256_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = AES256_Final(hContext)`

### C/C++ Syntax

`long __stdcall  AES256_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the AES context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Dispose Method](#M_Aes256_Dispose)  

### Remarks

### Example

See the examples in
[`AES256_UpdateHex`](#AES256_UpdateHex)
and [`AES256_Update`](#AES256_Update).

### See Also

[`AES256_Init`](#AES256_Init)
[`AES256_InitHex`](#AES256_InitHex)
[`AES256_UpdateHex`](#AES256_UpdateHex)
[`AES256_Update`](#AES256_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_Hex"></a>AES256_Hex
---------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`AES256_HexMode`](#AES256_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function AES256_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = AES256_Hex(strOutput, strInput, strHexKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  AES256_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput*
must be a multiple of 32 hex characters long (i.e. representing a multiple of the block size of 16 bytes).
The key string *szHexKey*
must be exactly 64 hex characters long (i.e. representing exactly 32 bytes/256 bits).

The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

This function is equivalent to

```

nRet = AES256_HexMode(strOutput, strInput, strHexKey, bEncrypt, "ECB", 0)

```

### Example

This example is taken from FIPS 197 Appendix C.

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    
'FIPS-197
'C.3 AES-256 (Nk=8, Nr=14)
'PLAINTEXT: 00112233445566778899aabbccddeeff
'KEY: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
    strHexKey = _
    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
    sPlain = "00112233445566778899aabbccddeeff"
    sCipher = "8EA2B7CA516745BFEAFC49904B496089"
    
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES256_Hex(strOutput, strInput, strHexKey, ENCRYPT)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)
    
    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = AES256_Hex(strOutput, strInput, strHexKey, DECRYPT)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Assert (strOutput = sPlain)

```

This should result in output as follows:

```

KY=000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
PT=00112233445566778899aabbccddeeff
CT=8EA2B7CA516745BFEAFC49904B496089 0 
OK=8EA2B7CA516745BFEAFC49904B496089
P'=00112233445566778899AABBCCDDEEFF 0 

```

### See Also

[`AES256_HexMode`](#AES256_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_HexMode"></a>AES256_HexMode
-----------------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function AES256_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strHexKey As String,
    ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`AES256_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES256_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeString) (String, String, Mode, String)  

### Remarks

The length of the input string *szInput*
must be a multiple of 32 hex characters long (i.e. representing a multiple of the block size of 16 bytes).
The key string *szHexKey*
must be exactly 64 hex characters long (i.e. representing exactly 32 bytes/256 bits).

The initialization vector *szHexIV*
must be exactly 32 hex characters long (i.e. representing exactly the block size of 16 bytes), 
except for ECB mode, where it is ignored (use `""`).
The output string *szOutput* must be set up with at least the
same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

The examples are from RFC 3602 *The AES-CBC Cipher Algorithm and Its Use with IPsec*

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim sPlain As String
    Dim sCipher As String
    Dim strHexIV As String
    
' Encrypting 64 bytes (4 blocks) using AES-CBC with 256-bit key
    
    strHexKey = "56e47a38c5598974bc46903dba29034906a9214036b8a15b512e03d534120006"
    strHexIV = "8ce82eefbea0da3c44699ed7db51b7d9"
    sPlain = "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" _
        & "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" _
        & "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" _
        & "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
    sCipher = "28409A2982BD2CF7CE343A7D43F6927F" _
        & "DB9EC532BBA569EEC92E57A209C4FDBA" _
        & "59ADBA05A5C854694DDC9F7991C01634" _
        & "E72BEB4FE0236CB3B119A463891E346F"
        
    strInput = sPlain
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")
    
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strHexIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = AES256_HexMode(strOutput, strInput, strHexKey, ENCRYPT, "CBC", strHexIV)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCipher
    Debug.Assert (strOutput = sCipher)

    ' Decrypt to check
    strInput = strOutput
    nRet = AES256_HexMode(strOutput, strInput, strHexKey, DECRYPT, "CBC", strHexIV)
    Debug.Print "P'=" & strOutput; nRet
    Debug.Print "OK=" & sPlain
    Debug.Assert (strOutput = sPlain)

```

This should result in output as follows:

```

KY=56e47a38c5598974bc46903dba29034906a9214036b8a15b512e03d534120006
IV=8ce82eefbea0da3c44699ed7db51b7d9
PT=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf
c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf
CT=28409A2982BD2CF7CE343A7D43F6927FDB9EC532BBA569EEC92E57A209C4FDBA
59ADBA05A5C854694DDC9F7991C01634E72BEB4FE0236CB3B119A463891E346F 0 
OK=28409A2982BD2CF7CE343A7D43F6927FDB9EC532BBA569EEC92E57A209C4FDBA
59ADBA05A5C854694DDC9F7991C01634E72BEB4FE0236CB3B119A463891E346F
P'=A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF
C0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF 0 
OK=a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf
c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf

```

### See Also

[`AES256_Hex`](#AES256_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_Init"></a>AES256_Init
-----------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function AES256_Init Lib "diCryptoSys.dll"
    (ByRef lpKey As Byte, 
    ByVal bEncrypt As Boolean, ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`hContext = AES256_Init(abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  AES256_Init(const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector,
or zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES256_Update`, `AES256_UpdateHex` or `AES256_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes256.InitEncrypt Method](#M_Aes256_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Aes256.InitDecrypt Method](#M_Aes256_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The key array *abKey()*
must be exactly 32 bytes long (i.e. 256 bits).
The initialization vector *abInitV()*
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use `0`).
Unlike most other functions in this API, `AES256_Init` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES256_Update`](#AES256_Update).

### See Also

[`AES256_InitHex`](#AES256_InitHex)
[`AES256_UpdateHex`](#AES256_UpdateHex)
[`AES256_Update`](#AES256_Update)
[`AES256_Final`](#AES256_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_InitError"></a>AES256_InitError
---------------------------------------------

Returns the error code after an unsuccessful call to
`AES256_Init` or `AES256_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function AES256_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = AES256_InitError()`

### C/C++ Syntax

`long __stdcall  AES256_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`AES256_Init` or `AES256_InitHex`.

### .NET Equivalent

[Aes256.ErrCode Property](#M_Aes256_ErrCodeProperty)  

### Remarks

### Example

```

    Dim hContext As Long
    Dim nRet As Long
    
    ' Try to initialise with an invalid key
    hContext = AES256_InitHex("THIS IS NOT HEX!", ENCRYPT, _
        "CBC", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES192_InitError()
        Debug.Print "AES192_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If
    
    ' Try with an invalid mode
    hContext = AES256_InitHex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", _
        ENCRYPT, "XXX", "0123456789abcdef0123456789abcdef")
    If hContext = 0 Then
        nRet = AES192_InitError()
        Debug.Print "AES192_InitHex failed (" & apiErrorLookup(nRet) & ")"
    End If

```

This should produce the output

```

AES256_InitHex failed (Invalid key)
AES256_InitHex failed (Invalid mode)

```

### See Also

[`API_ErrorLookup`](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_InitHex"></a>AES256_InitHex
-----------------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the AES function.
The key and IV data are passed in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function AES256_InitHex Lib "diCryptoSys.dll"
    (ByVal strHexKey As String, 
    ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`hContext = AES256_InitHex(strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  AES256_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 128-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector
in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`AES256_Update`, `AES256_UpdateHex` or `AES256_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Aes256.InitEncrypt Method](#M_Aes256_InitEncrypt_StringModeString) (String, Mode, String)  

[Aes256.InitDecrypt Method](#M_Aes256_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 64 hexadecimal characters long
(i.e. representing exactly 32 bytes/256 bits).

The initialization vector *szHexIV*
must be exactly 32 hexadecimal characters long
(i.e. representing exactly the block size of 16 bytes), except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `AES256_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling the AES Update function.

### Example

See [`AES256_UpdateHex`](#AES256_UpdateHex).

### See Also

[`AES256_Init`](#AES256_Init)
[`AES256_UpdateHex`](#AES256_UpdateHex)
[`AES256_Update`](#AES256_Update)
[`AES256_Final`](#AES256_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_Update"></a>AES256_Update
---------------------------------------

Carries out the AES transformation function on a byte array
according to the direction
and mode set up by an earlier call to `AES256_Init()` or `AES256_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES256_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = AES256_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  AES256_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES256_Init()` or `AES256_InitHex()`.

*lpData*
:   [in,out] array containing the input
to be processed by the AES function and to receive the output.

*nDataLen*
:   [in] containing length of the data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Update Method](#M_Aes256_Update_Byte) (Byte[])  

### Remarks

The input array *lpData*
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
Note that the output overwrites the input.

### Example

This example carries out the second Monte Carlo MOVS test in CBC encrypt mode.
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

    Dim nRet As Long
    Dim hContext As Long
    Dim abBlock() As Byte
    Dim abKey() As Byte
    Dim abCorrect() As Byte
    Dim j As Integer
    
' File: ecb_d_m.txt
' KEYSIZE=256 I=2
' KEY=2447EC44111548FBB670B98F182D5DEE109BF5F30D9464ED411F18A63C53A998
' CT=15173A0EB65F5CC05E704EFE61D9E346
' PT=85F083ACC676D91EDD1ABFB43935237A
    ' Convert to Byte format
    abKey = _
    cnvBytesFromHexStr("2447EC44111548FBB670B98F182D5DEE109BF5F30D9464ED411F18A63C53A998")
    abBlock = cnvBytesFromHexStr("15173A0EB65F5CC05E704EFE61D9E346")
    abCorrect = cnvBytesFromHexStr("85F083ACC676D91EDD1ABFB43935237A")
    
    Debug.Print "AES Monte Carlo ECB Mode Decrypt:"
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "CT=" & cnvHexStrFromBytes(abBlock)
    
    hContext = AES256_Init(abKey(0), DECRYPT, "ECB", 0)
    If hContext = 0 Then
        MsgBox "Failed to set context", vbCritical
        Exit Function
    End If
    ' Do 10,000 times
    For j = 0 To 9999
        nRet = AES256_Update(hContext, abBlock(0), 16)
    Next
    Debug.Print "PT=" & cnvHexStrFromBytes(abBlock)
    Debug.Print "OK=" & cnvHexStrFromBytes(abCorrect)
    nRet = AES256_Final(hContext)
    
    Debug.Assert (StrConv(abCorrect, vbUnicode) = StrConv(abBlock, vbUnicode))

```

This should result in output as follows:

```

AES Monte Carlo ECB Mode Decrypt:
KY=2447EC44111548FBB670B98F182D5DEE109BF5F30D9464ED411F18A63C53A998
CT=15173A0EB65F5CC05E704EFE61D9E346
PT=85F083ACC676D91EDD1ABFB43935237A
OK=85F083ACC676D91EDD1ABFB43935237A

```

### See Also

[`AES256_Init`](#AES256_Init)
[`AES256_InitHex`](#AES256_InitHex)
[`AES256_UpdateHex`](#AES256_UpdateHex)
[`AES256_Final`](#AES256_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="AES256_UpdateHex"></a>AES256_UpdateHex
---------------------------------------------

Carries out the AES transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `AES256_Init()` or `AES256_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function AES256_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = AES256_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  AES256_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the AES context set up by an earlier call to
	`AES256_Init()` or `AES256_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the AES function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Aes256.Update Method](#M_Aes256_Update_String) (String)  

### Remarks

The length of the input string *szHexString* must be a multiple of 32 hex characters long 
(i.e. representing a multiple of the block size of 16 bytes).

If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f].
Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

This example carries out the second [[MOVS](#MOVS)] Monte Carlo test in CBC encrypt mode
(Ref: *AES Candidate Algorithm Submissions*, update 17 Feb 1998, file cbc_e_m.txt 
[[RIJNVALS](#RIJNVALS)]).

```

    Dim nRet As Long
    Dim hContext As Long
    Dim sBlock As String
    Dim strHexKey As String
    Dim strIV As String
    Dim sNext As String
    Dim sLast As String
    Dim sCorrect As String
    Dim j As Integer
  
' cbc_e_m.txt
' KEYSIZE=256 I=2
' KEY=33A36646FE56F70DC0C51A3117E639F182DEF8CAB5C06671EEA0407C48A9C757
' IV=7CE2ABAF8BEF23C4816DC8CE842048A7
' PT=81EA5BA46945C1705F6F89778868CC67
' CT=50CD14A12C6852D39654C816BFAF9AC2
    
    strHexKey = _
    "33A36646FE56F70DC0C51A3117E639F182DEF8CAB5C06671EEA0407C48A9C757"
    strIV = "7CE2ABAF8BEF23C4816DC8CE842048A7"
    sBlock = "81EA5BA46945C1705F6F89778868CC67"
    sCorrect = "50CD14A12C6852D39654C816BFAF9AC2"
    
    Debug.Print "AES Monte Carlo CBC Mode Encrypt:"
    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strIV
    Debug.Print "PT=" & sBlock
    
    hContext = AES256_InitHex(strHexKey, ENCRYPT, "CBC", strIV)
    If hContext = 0 Then
        MsgBox "Failed to set context", vbCritical
        Exit Function
    End If
    ' Do 10,000 times
    sNext = sBlock
    For j = 0 To 9999
        sBlock = sNext
        nRet = AES256_UpdateHex(hContext, sBlock)
        If j = 0 Then
            sNext = strIV
        Else
            sNext = sLast
        End If
        sLast = sBlock
    Next
    Debug.Print "CT=" & sBlock
    Debug.Print "OK=" & sCorrect
    nRet = AES256_Final(hContext)
    
    Debug.Assert (sCorrect = sBlock)

```

This should result in output as follows:

```

AES Monte Carlo CBC Mode Encrypt:
KY=33A36646FE56F70DC0C51A3117E639F182DEF8CAB5C06671EEA0407C48A9C757
IV=7CE2ABAF8BEF23C4816DC8CE842048A7
PT=81EA5BA46945C1705F6F89778868CC67
CT=50CD14A12C6852D39654C816BFAF9AC2
OK=50CD14A12C6852D39654C816BFAF9AC2

```

### See Also

[`AES256_Init`](#AES256_Init)
[`AES256_InitHex`](#AES256_InitHex)
[`AES256_Update`](#AES256_Update)
[`AES256_Final`](#AES256_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_CompileTime"></a>API_CompileTime
-------------------------------------------

Retrieves the date and time the core library executable was last compiled.

### VBA/VB6 Syntax

`Public Declare Function API_CompileTime Lib "diCryptoSys.dll" 
    (ByVal strCompiledOn As String, ByVal nStrLen As Long) As Long`

`nRet = API_CompileTime(strCompiledOn, nStrLen)`

### C/C++ Syntax

`long __stdcall  API_CompileTime(char *szOutput, long nMaxChars);`

### Parameters

*szOutput*
:   [out] to receive the date and time string.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [apiCompileTime](#VB_apiCompileTime)() As String`

### .NET Equivalent

[General.CompileTime Method](#M_General_CompileTime)  

### C++ (STL) Equivalent

`static std::string [crsysapi::Gen::CompileTime](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a9d77fbd3a604f7231dc83909670ac735 "External link") ()`

### Python Equivalent

`static [Gen.compile_time](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.compile_time "External link")()`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 
Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example (VBA core function)

```

Dim nLen As Long
Dim strCompiledOn As String

strCompiledOn = String(255, " ")
nLen = API_CompileTime(strCompiledOn, Len(strCompiledOn))
strCompiledOn = Left(strCompiledOn, nLen)
Debug.Print "API_CompileTime returns " & nLen & " [" & strCompiledOn & "]"

```

### Example (VBA wrapper function)

```

Debug.Print "CompileTime=" & apiCompileTime()
```

### See Also

[`API_Version`](#API_Version)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_ErrorCode"></a>API_ErrorCode
---------------------------------------

Returns the [error code](#errorcodes) of the error that occurred when calling the last function.

### VBA/VB6 Syntax

`Public Declare Function API_ErrorCode Lib "diCryptoSys.dll" () As Long`

`nRet = API_ErrorCode()`

### C/C++ Syntax

`long __stdcall  API_ErrorCode(void);`

### Parameters

None.

### Returns (VBA/C)

Returns the [error code](#errorcodes) of the error that occurred
when calling the last function, or zero if no error occurred.

### .NET Equivalent

[General.ErrorCode Method](#M_General_ErrorCode)  

[General.FormatErrorMessage Method](#M_General_FormatErrorMessage)  

### C++ (STL) Equivalent

`static int [crsysapi::Err::ErrorCode](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#af3164ad23c9c1002133fdcb7bbf05225 "External link") ()`

### Python Equivalent

`static [Gen.error_code](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.error_code "External link")()`

### Remarks

The value returned is always a non-negative integer greater than or equal to zero.
Not all functions set this value.

### Example

```

Dim nErrCode as Long
nErrCode = API_ErrorCode()

```

```

Debug.Print "API_ErrorCode=" & API_ErrorCode() & ": " & apiErrorLookup(API_ErrorCode())

```

```

API_ErrorCode=19: Item is not supported (NOT_SUPPORTED_ERROR)

```

A sample function in C to display error details.

```

/** Display error codes and corresponding message.
@param nRet Error code returned by last function.
*/
static void disp_error(long nRet)
{
    long errcode;
    char errmsg[128] = { 0 };
    // Get error that occurred when calling last function (if any)
    errcode = API_ErrorCode();
    // Lookup message for error code
    if (errcode != 0)
        API_ErrorLookup(errmsg, sizeof(errmsg), errcode);
    else 
        API_ErrorLookup(errmsg, sizeof(errmsg), nRet);
    printf("ERROR Returned=%ld/Code=%ld: %s\n", nRet, errcode, errmsg);
}

```

```

HASH_DigestLength returns -64
ERROR Returned=-64/Code=64: Invalid context handle (INVALID_HANDLE_ERROR)

```

### See Also

[API_ErrorLookup](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_ErrorLookup"></a>API_ErrorLookup
-------------------------------------------

Retrieves the error message associated with a given error code.

### VBA/VB6 Syntax

`Public Declare Function API_ErrorLookup Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal nErrorCode As Long) As Long`

`nRet = API_ErrorLookup(strOutput, nMaxChars, nErrorCode)`

### C/C++ Syntax

`long __stdcall  API_ErrorLookup(char *szOutput, long nMaxChars, long nErrCode);`

### Parameters

*szOutput*
:   [out] to receive error message.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*nErrCode*
:   [in] specifying the error code for which the message is required.

### Returns (VBA/C)

the number of characters in the output string or zero if there
is no corresponding error message.

### VBA Wrapper Syntax

`Public Function [apiErrorLookup](#VB_apiErrorLookup)(nCode As Long) As String`

### .NET Equivalent

[General.ErrorLookup Method](#M_General_ErrorLookup)  

[General.FormatErrorMessage Method](#M_General_FormatErrorMessage)  

### C++ (STL) Equivalent

`static std::string [crsysapi::Err::ErrorLookup](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#a15d3fd8bc5938342cff4201e82fe032e "External link") (int errCode)  

static std::string [crsysapi::Err::FormatErrorMessage](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#af58077604f154b4bf861b458018332d5 "External link") (int errCode=0)`

### Python Equivalent

`static [Gen.error_lookup](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.error_lookup "External link")(n)`

### Remarks

The error message will never be longer than 127 characters. 

### Example

```

Dim nErrCode As Long
nErrCode = 33
Debug.Print "ErrorLookup(" & nErrCode & ")=" & apiErrorLookup(nErrCode)

```

```

ErrorLookup(33)=Invalid key length (BAD_KEY_LEN_ERROR)

```

To display all possible error messages:

```

    Dim nRet As Long
    Dim strErrMsg As String * 128
    Dim i As Integer
    
    For i = 0 To 10000
        nRet = API_ErrorLookup(strErrMsg, Len(strErrMsg), i)
        If (nRet > 0) Then
            Debug.Print i & " = " & Left(strErrMsg, nRet)
        End If
    Next

```

### See Also

[Error codes](#errorcodes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_LicenceType"></a>API_LicenceType
-------------------------------------------

Returns the ASCII value of the licence type.

### VBA/VB6 Syntax

`Public Declare Function API_LicenceType Lib "diCryptoSys.dll" 
    (ByVal nOptions As Long) As Long`

`nRet = API_LicenceType(nOptions)`

### C/C++ Syntax

`long __stdcall  API_LicenceType(long nOptions);`

### Parameters

*nOptions*
:   [in] not used in this release. Specify zero.

### Returns (VBA/C)

Returns the ASCII value of the licence type, either "D" (ASCII 68, 0x44) for the Developer Edition
 or "T" (ASCII 84, 0x54) for the Trial Edition.

### .NET Equivalent

[General.LicenceType Method](#M_General_LicenceType)  

### COM/ASP Equivalent

`gen.LicenceType  

Public Function LicenceType() As String`

See [`gen.LicenceType`](#x_gen_licencetype).

### C++ (STL) Equivalent

`static std::string [crsysapi::Gen::LicenceType](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a7c09a642f3241754076151a2296b6635 "External link") ()`

### Python Equivalent

`static [Gen.licence_type](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.licence_type "External link")()`

### Remarks

Note the Australian/British spelling of `Licence'.

### Example

```

Dim nRet As Long
nRet = API_LicenceType(0)
Debug.Print "API_LicenceType is " & Chr(nRet)

```

### See Also

[`API_Version`](#API_Version)
[`API_CompileTime`](#API_CompileTime)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_ModuleInfo"></a>API_ModuleInfo
-----------------------------------------

Get additional information about the core DLL module.

### VBA/VB6 Syntax

`Public Declare Function API_ModuleInfo Lib "diCryptoSys.dll" 
    (ByVal strName As String, ByVal nStrLen As Long, ByVal nOptions As Long) As Long`

`nRet = API_ModuleInfo(strName, nStrLen, 0)`

### C/C++ Syntax

`long __stdcall API_ModuleInfo(char *szOutput, long nOutChars, long nOptions);`

### Parameters

*szOutput*
:   [out] Buffer to receive output string.

*nOutChars*
:   [in] Maximum length of output string in bytes.

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is the number of characters in or required for the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [apiModuleInfo](#VB_apiModuleInfo) (Optional nOptions As Long = 0) As String`

### .NET Equivalent

[General.ModuleInfo Method](#M_General_ModuleInfo)  

### Example (VBA core function)

```

Dim nLen As Long
Dim strModuleInfo As String

nLen = API_ModuleInfo("", 0, 0)
If nLen > 0 Then
    strModuleInfo = String(nLen, " ")
    nLen = API_ModuleInfo(strModuleInfo, nLen, 0)
    strModuleInfo = Left(strModuleInfo, nLen)
    Debug.Print "API_ModuleInfo returns " & nLen & " [" & strModuleInfo & "]"
Else
    Debug.Print "Error " & nLen & " with API_ModuleInfo"
End If

```

```

API_ModuleInfo returns 26 [Licensed Developer Edition]

```

### Example (VBA wrapper function)

```

Debug.Print apiCompileTime()
Debug.Print apiModuleInfo()
Debug.Print apiModuleName()
Debug.Print apiPlatform()

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_ModuleName"></a>API_ModuleName
-----------------------------------------

Retrieves the name of the current process's module.

### VBA/VB6 Syntax

`Public Declare Function API_ModuleName Lib "diCryptoSys.dll" 
    (ByVal strModuleName As String, ByVal nMaxChars As Long, ByVal nOptions As Long) As Long`

`nRet = API_ModuleName(strName, nStrLen, 0)`

### C/C++ Syntax

`long __stdcall  API_ModuleName(char *szOutput, long nMaxChars, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive the name of the module.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*nOptions*
:   [in] option flags: `API_GEN_PLATFORM` to get the platform name, either "Win32" or "X64".

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [apiModuleName](#VB_apiModuleName)(Optional nOptions As Long = 0) As String`

### .NET Equivalent

[General.ModuleName Method](#M_General_ModuleName)  

### COM/ASP Equivalent

`gen.ModuleName  

Public Function ModuleName() As String`

See [`gen.ModuleName`](#x_gen_modulename).

### C++ (STL) Equivalent

`static std::string [crsysapi::Gen::ModuleName](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#acbeb4e6e67a6f2cda8f193b3c435dd22 "External link") ()  

static std::string [crsysapi::Gen::Platform](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#aa4fa152ba3f20d2705a567469e559bad "External link") ()`

### Python Equivalent

`static [Gen.module_name](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.module_name "External link")()`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 
Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example (VBA core function)

```

Dim nChars As Long
Dim strModuleName As String

nChars = API_ModuleName("", 0, 0)
Debug.Assert nChars > 0
strModuleName = String(nChars, " ")
nChars = API_ModuleName(strModuleName, nChars, 0)
Debug.Print strModuleName   ' C:\WINDOWS\SYSTEM32\diCryptoSys.dll

```

### Example (VBA wrapper function)

```

Debug.Print "ModuleName= " & apiModuleName()
```

### See Also

[[Back to Top](#topofpage)]

<a id="API_Platform"></a>API_Platform
-------------------------------------

Gets the platform the core DLL was compiled for.

### VBA/VB6 Syntax

`Public Declare Function API_Platform Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nOutChars As Long) As Long`

`nRet = API_Platform(strOutput, nOutChars)`

### C/C++ Syntax

`long __stdcall API_Platform(char *szOutput, long nOutChars);`

### Parameters

*szOutput*
:   [out] to receive output, either "Win32" or "X64".

*nOutChars*
:   [in] specifying the maximum length of the string to be copied.

### Returns (VBA/C)

If successful, the return value is the number of characters in or required for the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [apiPlatform](#VB_apiPlatform)() As String`

### .NET Equivalent

[General.Platform Method](#M_General_Platform)  

### Python Equivalent

`static [Gen.core_platform](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.core_platform "External link")()`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length. ANSI C users [must add one to this value](#cusersaddone) when allocating memory.

### Example (VBA wrapper function)

```

Debug.Print apiCompileTime()
Debug.Print apiModuleInfo()
Debug.Print apiModuleName()
Debug.Print apiPlatform()

```

### See Also

[API_ModuleName](#API_ModuleName)

[[Contents](#topofpage)] [[Index](#index)]

<a id="API_PowerUpTests"></a>API_PowerUpTests
---------------------------------------------

Carries out on demand the full set of power-up tests automatically performed by the toolkit
when first powered up (i.e. when the DLL is first attached to the process).

### VBA/VB6 Syntax

`Public Declare Function API_PowerUpTests Lib "diCryptoSys.dll" 
    (ByVal nOptions As Long) As Long`

`nRet = API_PowerUpTests(nOptions)`

### C/C++ Syntax

`long __stdcall  API_PowerUpTests(long nOptions);`

### Parameters

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[General.PowerUpTests Method](#M_General_PowerUpTests) ()  

### Remarks

This is an optional function. Unlike the tests carried out on actual power-up, this function does
not cause the DLL to quit. If errors do occur, an error event will be recorded in the Application event log
for NT+ operating systems or in an error log file on W9x systems. 
For more information on error logging after a self-test error, see [Self Tests](#selftests).
Users are warned not to use the toolkit if an error has
occurred after using this optional test. In such an event, please contact us. 

### Example

```

Dim nRet As Long  
nRet = API_PowerUpTests(0)
Debug.Print "API_PowerUpTests returns " & nRet

```

### See Also

[[Back to Top](#topofpage)]

<a id="API_Version"></a>API_Version
-----------------------------------

Retrieves the release version number.

### VBA/VB6 Syntax

`Public Declare Function API_Version Lib "diCryptoSys.dll" 
    () As Long`

`nRet = API_Version()`

### C/C++ Syntax

`long __stdcall  API_Version(void);`

### Parameters

None.

### Returns (VBA/C)

The value of `Major*100*100 + Minor*100 + Revision`. 
For example, version 6.2.3 (major version 6, minor version 2, revision 3) will return 60203.

### .NET Equivalent

[General.Version Method](#M_General_Version)  

### COM/ASP Equivalent

`gen.Version  

Public Function Version() As Long`

See [`gen.Version`](#x_gen_version).

### C++ (STL) Equivalent

`static int [crsysapi::Gen::Version](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a8cd280838013e607c24d4b754b9338f6 "External link") ()`

### Python Equivalent

`static [Gen.version](https://cryptosys.net/pydocapi/class-stubs/Gen.html#crsysapi.Gen.version "External link")()`

### Remarks

### Example

```

Dim nRet As Long
nRet = API_Version()
Debug.Print "API_Version returns " & nRet

```

### See Also

[`API_LicenceType`](#API_LicenceType)
[`API_CompileTime`](#API_CompileTime)

<a id="BLF_B64Mode"></a>BLF_B64Mode
-----------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function BLF_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = BLF_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  BLF_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (8 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 8 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* can represent up to 56 bytes.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim strIV As String
    Dim sCorrect As String

    ' "7654321 Now is the time for " padded to 32 bytes with 4 nulls
    strInput = "NzY1NDMyMSBOb3cgaXMgdGhlIHRpbWUgZm9yIAAAAAA="
    sCorrect = "a3e01jAG3uYFsVbidAOXk1jeuecVRhbZWfFlK9X/ksw="
    ' Key is 0x0123456789ABCDEFF0E1D2C3B4A59687
    strKey = "ASNFZ4mrze/w4dLDtKWWhw=="
    ' IV is 0xFEDCBA9876543210
    strIV = "/ty6mHZUMhA="
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "IV=" & strIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = BLF_B64Mode(strOutput, strInput, strKey, ENCRYPT, "CBC", strIV)
    Debug.Print "CT=" & strOutput, nRet
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = BLF_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
    Debug.Print "P'=" & strOutput, nRet

```

This should result in output as follows:

```

KY=ASNFZ4mrze/w4dLDtKWWhw==
IV=/ty6mHZUMhA=
PT=NzY1NDMyMSBOb3cgaXMgdGhlIHRpbWUgZm9yIAAAAAA=
CT=a3e01jAG3uYFsVbidAOXk1jeuecVRhbZWfFlK9X/ksw=          0 
OK=a3e01jAG3uYFsVbidAOXk1jeuecVRhbZWfFlK9X/ksw=
P'=NzY1NDMyMSBOb3cgaXMgdGhlIHRpbWUgZm9yIAAAAAA=          0 

```

### See Also

[`BLF_HexMode`](#BLF_HexMode)
[`BLF_BytesMode`](#BLF_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_Bytes"></a>BLF_Bytes
-------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`BLF_BytesMode`](#BLF_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function BLF_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal bEncrypt As Boolean) As Long`

`nRet = BLF_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), nKeyLen, bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  BLF_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, long keyBytes, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*keyBytes*
:   [in] equal to length of the key in bytes.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Encrypt Method](#M_Blowfish_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Blowfish.Decrypt Method](#M_Blowfish_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* can be any length between 1 and 56 bytes (448 bits).
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

```

Dim nRet As Long
Dim strInput As String
Dim strKey As String
Dim sCorrect As String
Dim nKeyLen As Long
Dim abKey() As Byte
Dim lpOutput() As Byte
Dim abData() As Byte
Dim nDataLen As Long

' Define test vectors in hex
strKey = "FEDCBA9876543210"
strInput = "0123456789ABCDEF0123456789ABCDEF"
sCorrect = "0ACEAB0FC6A0A28D0ACEAB0FC6A0A28D"

' Convert to byte arrays and compute lengths
nKeyLen = Len(strKey) \ 2
abKey = cnvBytesFromHexStr(strKey)
nDataLen = Len(strInput) \ 2
abData = cnvBytesFromHexStr(strInput)

' Dimension array for output
ReDim lpOutput(nDataLen - 1)

Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
Debug.Print "PT=" & cnvHexStrFromBytes(abData)
' Encrypt in one-off process
nRet = BLF_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), nKeyLen, ENCRYPT)
Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput), nRet
Debug.Print "OK=" & sCorrect

' Now decrypt back
nRet = BLF_Bytes(abData(0), lpOutput(0), nDataLen, abKey(0), nKeyLen, DECRYPT)
Debug.Print "P'=" & cnvHexStrFromBytes(abData), nRet

```

This should result in output as follows:

```

KY=FEDCBA9876543210
PT=0123456789ABCDEF0123456789ABCDEF
CT=0ACEAB0FC6A0A28D0ACEAB0FC6A0A28D        0 
OK=0ACEAB0FC6A0A28D0ACEAB0FC6A0A28D
P'=0123456789ABCDEF0123456789ABCDEF        0 

```

### See Also

[`BLF_BytesMode`](#BLF_BytesMode)
[`BLF_B64Mode`](#BLF_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_BytesMode"></a>BLF_BytesMode
---------------------------------------

Encrypts or decrypts an array of Bytes
using a specified mode.

### VBA/VB6 Syntax

`Public Declare Function BLF_BytesMode Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = BLF_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), nKeyLen, bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  BLF_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, long keyBytes, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*keyBytes*
:   [in] equal to length of the key in bytes.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the
initialization vector (IV), or zero (0) for `ECB` mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Encrypt Method](#M_Blowfish_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Blowfish.Decrypt Method](#M_Blowfish_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Python Equivalent

`static [Blowfish.encrypt_block](https://cryptosys.net/pydocapi/class-stubs/Blowfish.html#crsysapi.Blowfish.encrypt_block "External link")(data, key, modestr="ECB", iv=None)`

`static [Blowfish.decrypt_block](https://cryptosys.net/pydocapi/class-stubs/Blowfish.html#crsysapi.Blowfish.decrypt_block "External link")(data, key, modestr="ECB", iv=None)`

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* can be any length between 1 and 56 bytes (448 bits).
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim strHexIV As String
    Dim sCorrect As String
    Dim nKeyLen As Long
    Dim abKey() As Byte
    Dim lpOutput() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long
    Dim abInitV() As Byte
    Dim nIVLen As Long
    
    strKey = "0123456789ABCDEFF0E1D2C3B4A59687"
    strHexIV = "FEDCBA9876543210"
    strInput = _
"37363534333231204E6F77206973207468652074696D6520666F722000000000"
    sCorrect = _
"6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC"
    
    ' Convert to byte arrays and compute lengths
    nKeyLen = Len(strKey) \ 2
    nDataLen = Len(strInput) \ 2
    nIVLen = Len(strHexIV) \ 2
    abKey = cnvBytesFromHexStr(strKey)
    abData = cnvBytesFromHexStr(strInput)
    abInitV = cnvBytesFromHexStr(strHexIV)
    
    ' Dimension array for output
    ReDim lpOutput(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = BLF_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), _
        nKeyLen, ENCRYPT, "CBC", abInitV(0))
    Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput), nRet
    Debug.Print "OK=" & sCorrect
    
    ' Now decrypt back
    nRet = BLF_BytesMode(abData(0), lpOutput(0), nDataLen, abKey(0), _
        nKeyLen, DECRYPT, "cbc", abInitV(0))
    Debug.Print "P'=" & cnvHexStrFromBytes(abData), nRet

```

This should result in output as follows:

```

KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210
PT=37363534333231204E6F77206973207468652074696D6520666F722000000000
CT=6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC    0 
OK=6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC
P'=37363534333231204E6F77206973207468652074696D6520666F722000000000    0 

```

### See Also

[`BLF_Bytes`](#BLF_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_File"></a>BLF_File
-----------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

### VBA/VB6 Syntax

`Public Declare Function BLF_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = BLF_File(strFileOut, strFileIn, abKey(0), nKeyLen, bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  BLF_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long keyBytes, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*keyBytes*
:   [in] containing the length of the key in bytes.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The initialization vector
byte array *lpInitV* must be exactly the block size of 8 bytes long, 
except for ECB mode, where it is ignored (use `0`).
The key array *lpKey* can be any length between 1 and 56 bytes (448 bits).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

```

    Const MY_PATH As String = "C:\Test\"
    Dim abKey() As Byte
    Dim strFileOut As String
    Dim strFileIn As String
    Dim strFileChk As String
    Dim nRet As Long
    Dim nBytes As Long

    ' Construct full path names to files
    strFileIn = MY_PATH & "hello.txt"
    strFileOut = MY_PATH & "hello.blf.enc.dat"
    strFileChk = MY_PATH & "hello.blf.chk.txt"

    ' Create the key as an array of bytes
    ' This creates an array of 8 bytes {&HFE, &HDC, ... &H10}
    abKey = cnvBytesFromHexStr("fedcba9876543210")
    nBytes = 8

    ' Encrypt plaintext file to cipher
    ' WARNING: output file is just clobbered
    nRet = BLF_File(strFileOut, strFileIn, abKey(0), nBytes, ENCRYPT, "ECB", 0)
    Debug.Print nRet
    ' Output file should be a 16-byte file hello.enc
    ' containing the following values in hexadecimal:
    ' 1A A1 51 B7 7A 5A 33 5C 4E 7E DC 84 A3 86 DC 96

    ' Now decrypt it
    nRet = BLF_File(strFileChk, strFileOut, abKey(0), nBytes, DECRYPT, "ECB", 0)
    Debug.Print nRet

```

### See Also

[`BLF_FileExt`](#BLF_FileExt)
[`BLF_FileHex`](#BLF_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_FileExt"></a>BLF_FileExt
-----------------------------------

Encrypts or decrypts a file using a specified mode with extended options. 

### VBA/VB6 Syntax

`Public Declare Function BLF_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = BLF_FileExt(strFileOut, strFileIn, abKey(0), nKeyLen, bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  BLF_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long keyBytes, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*keyBytes*
:   [in] containing the length of the key in bytes.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`BLF_File`](#BLF_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

For the default behaviour, see [`BLF_File`](#BLF_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

### Example

```

```

### See Also

[`BLF_File`](#BLF_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_FileHex"></a>BLF_FileHex
-----------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function BLF_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = BLF_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  BLF_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *sHexIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*sHexIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

The initialization vector
string *szHexIV* must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes) unless *szMode* is `ECB`, 
in which case *szHexIV* is ignored (use `""`).
The key *szKey* can be any even length between 2 and 112 hexadecimal characters.
Valid hexadecimal characters are [0-9A-Fa-f].

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the key
`0xfedcba9876543210fedcba9876543210` and initialization vector
`0x0123456789abcdef`. The output file "bigfile.cbc" will be created or
overwritten.

```

    Dim nRet As Long

    ' Encrypt plaintext file to cipher
    nRet = BLF_FileHex("bigfile.cbc", "bigfile.dat", _
        "fedcba9876543210fedcba9876543210", ENCRYPT, "CBC", "0123456789abcdef")
    Debug.Print nRet

```

### See Also

[`BLF_File`](#BLF_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_Final"></a>BLF_Final
-------------------------------

Closes and clears the BLF context.

### VBA/VB6 Syntax

`Public Declare Function BLF_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = BLF_Final(hContext)`

### C/C++ Syntax

`long __stdcall  BLF_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the BLF context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Dispose Method](#M_Blowfish_Dispose)  

### Remarks

The handle *hContext* must have been set up by an earlier call 
to `BLF_Init()` or `BLF_InitHex()`.

### Example

See [`BLF_UpdateHex`](#BLF_UpdateHex).

### See Also

[`BLF_Init`](#BLF_Init)
[`BLF_InitHex`](#BLF_InitHex)
[`BLF_UpdateHex`](#BLF_UpdateHex)
[`BLF_Update`](#BLF_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_Hex"></a>BLF_Hex
---------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`BLF_HexMode`](#BLF_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function BLF_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = BLF_Hex(strOutput, strInput, strKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  BLF_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned..
The key *szKey* can be any even length between 2 and 112 hexadecimal characters.
The output string *szOutput* must be set up with at least the same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim sCorrect As String

    strInput = "0123456789ABCDEF"
    strKey = "FEDCBA9876543210"
    sCorrect = "0ACEAB0FC6A0A28D"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = BLF_Hex(strOutput, strInput, strKey, ENCRYPT)
    Debug.Print "CT=" & strOutput
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = BLF_Hex(strOutput, strInput, strKey, DECRYPT)
    Debug.Print "P'=" & strOutput

```

This should result in output as follows:

```

KY=FEDCBA9876543210
PT=0123456789ABCDEF
CT=0ACEAB0FC6A0A28D
OK=0ACEAB0FC6A0A28D
P'=0123456789ABCDEF

```

### See Also

[`BLF_HexMode`](#BLF_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_HexMode"></a>BLF_HexMode
-----------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function BLF_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = BLF_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  BLF_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeString) (String, String, Mode, String)  

### COM/ASP Equivalent

`blf.HexMode  

Public Function HexMode(ByVal strInput As String, ByVal strHexKey As String, ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As String`

See [`blf.HexMode`](#x_hexmode).

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned..
The initialization vector
string *szIV* must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes) unless *szMode* is `ECB`, 
in which case *szIV* is ignored (use `""`).
The key *szKey* can be any even length between 2 and 112 hexadecimal characters.
Valid hexadecimal characters are [0-9A-Fa-f].
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strHexKey As String
    Dim strHexIV As String
    Dim sCorrect As String

    ' "7654321 Now is the time for " padded to 32 bytes with 4 nulls
    strInput = "37363534333231204E6F77206973207468652074696D6520666F722000000000"
    sCorrect = "6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC"
    strHexKey = "0123456789ABCDEFF0E1D2C3B4A59687"
    strHexIV = "FEDCBA9876543210"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strHexKey
    Debug.Print "IV=" & strHexIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = BLF_HexMode(strOutput, strInput, strHexKey, ENCRYPT, "CBC", strHexIV)
    Debug.Print "CT=" & strOutput, nRet
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = BLF_HexMode(strOutput, strInput, strHexKey, DECRYPT, "CBC", strHexIV)
    Debug.Print "P'=" & strOutput, nRet

```

This should result in output as follows:

```

KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210
PT=37363534333231204E6F77206973207468652074696D6520666F722000000000
CT=6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC    0
OK=6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC
P'=37363534333231204E6F77206973207468652074696D6520666F722000000000    0

```

### See Also

[`BLF_Hex`](#BLF_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_Init"></a>BLF_Init
-----------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the `BLF_Update` or `BLF_UpdateHex` functions.
The key and IV data are provided in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function BLF_Init Lib "diCryptoSys.dll"
    (ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`hContext = BLF_Init(abKey(0), nKeyLen, bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  BLF_Init(const unsigned char *lpKey, long keyBytes, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] array containing the key.

*keyBytes*
:   [in] containing the length of the key in bytes.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`BLF_Update`, `BLF_UpdateHex` or `BLF_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Blowfish.InitEncrypt Method](#M_Blowfish_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Blowfish.InitDecrypt Method](#M_Blowfish_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The initialization vector
byte array *lpInitV* must be exactly the block size of 8 bytes long,
except for ECB mode, where it is ignored (use `0`).
The key array *lpKey* can be any length between 1 and 56 bytes (448 bits).

Unlike most other functions in this API, `BLF_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling `BLF_Update` or `BLF_UpdateHex`.

### Example

See [`BLF_Update`](#BLF_Update).

### See Also

[`BLF_InitHex`](#BLF_InitHex)
[`BLF_UpdateHex`](#BLF_UpdateHex)
[`BLF_Update`](#BLF_Update)
[`BLF_Final`](#BLF_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_InitError"></a>BLF_InitError
---------------------------------------

Returns the error code after an unsuccessful call to
`BLF_Init` or `BLF_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function BLF_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = BLF_InitError()`

### C/C++ Syntax

`long __stdcall  BLF_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`BLF_Init` or `BLF_InitHex`.

### .NET Equivalent

[Blowfish.ErrCode Property](#M_Blowfish_ErrCodeProperty)  

### Remarks

### Example

### See Also

<a id="BLF_InitHex"></a>BLF_InitHex
-----------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the `BLF_Update` or `BLF_UpdateHex` functions.
The key and IV data are in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function BLF_InitHex Lib "diCryptoSys.dll"
    (ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`hContext = BLF_InitHex(strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  BLF_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *sHexIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*sHexIV*
:   [in] containing the initialization vector
 in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`BLF_Update`, `BLF_UpdateHex` or `BLF_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Blowfish.InitEncrypt Method](#M_Blowfish_InitEncrypt_StringModeString) (String, Mode, String)  

[Blowfish.InitDecrypt Method](#M_Blowfish_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The initialization vector
string *szIV* must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes) unless *szMode* is `ECB`, 
in which case *szIV* is ignored (use `""`).
The key *szKey* can be any even length between 2 and 112 hexadecimal characters.
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `BLF_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling `BLF_Update` or `BLF_UpdateHex`.

### Example

See [`BLF_UpdateHex`](#BLF_UpdateHex).

### See Also

[`BLF_Init`](#BLF_Init)
[`BLF_UpdateHex`](#BLF_UpdateHex)
[`BLF_Update`](#BLF_Update)
[`BLF_Final`](#BLF_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_Update"></a>BLF_Update
---------------------------------

Carries out the Blowfish transformation function on a byte array
according to the direction
and mode set up by an earlier call to `BLF_Init()` or `BLF_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function BLF_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = BLF_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  BLF_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the BLF context set up by an earlier call to
	`BLF_Init()` or `BLF_InitHex()`.

*lpData*
:   [in,out] array containing the input
to be processed by the BLF function and to receive the output.

*nDataLen*
:   [in] containing length of the data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Update Method](#M_Blowfish_Update_Byte) (Byte[])  

### Remarks

*lpData* must be an exact multiple of 8 bytes long. If not, an error code will be returned.
 Note that the output overwrites the input.

### Example

```

    ' Contrived example to encrypt sample blocks in CBC mode
    Dim abBlock(7) As Byte
    Dim abKey() As Byte
    Dim nKeyLen As Long
    Dim abInitV() As Byte
    Dim hContext As Long
    Dim nRet As Long
    Dim i As Integer
    Dim j As Integer
   
    ' Specify a key and its length
    abKey = cnvBytesFromHexStr("FEDCBA9876543210")
    nKeyLen = UBound(abKey) - LBound(abKey) + 1
    
    ' And an IV (length is assumed to be 8 bytes)
    abInitV = cnvBytesFromHexStr("0123456789abcdef")
    
    ' Initialise the context
    hContext = BLF_Init(abKey(0), nKeyLen, ENCRYPT, "CBC", abInitV(0))
    If hContext = 0 Then
        nRet = BLF_InitError()
        Debug.Print "BFL_Init Failed: " & apiErrorLookup(nRet)
        Exit Function
    End If
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    
    ' Create some test blocks and encrypt them
    For i = 1 To 4
        For j = 0 To 7
            abBlock(j) = CByte(i)
        Next
        Debug.Print "PT(" & i & ")=" & cnvHexStrFromBytes(abBlock)
        nRet = BLF_Update(hContext, abBlock(0), 8)
        Debug.Print "CT(" & i & ")=" & cnvHexStrFromBytes(abBlock)
    Next
    
    ' Clear the context
    BLF_Final (hContext)

```

This should result in output as follows:

```

KY=FEDCBA9876543210
IV=0123456789ABCDEF
PT(1)=0101010101010101
CT(1)=46733BCD9C72C5E3
PT(2)=0202020202020202
CT(2)=F434DA62B6869A06
PT(3)=0303030303030303
CT(3)=2AE6DFE458559138
PT(4)=0404040404040404
CT(4)=DEEBF97D6F83A5F3

```

### See Also

[`BLF_Init`](#BLF_Init)
[`BLF_InitHex`](#BLF_InitHex)
[`BLF_UpdateHex`](#BLF_UpdateHex)
[`BLF_Final`](#BLF_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="BLF_UpdateHex"></a>BLF_UpdateHex
---------------------------------------

Carries out the Blowfish transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `BLF_Init()` or `BLF_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function BLF_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = BLF_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  BLF_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the BLF context set up by an earlier call to
	`BLF_Init()` or `BLF_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the BLF function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Blowfish.Update Method](#M_Blowfish_Update_String) (String)  

### Remarks

*szHexString* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f]. Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

```

    Dim nRet As Long
    Dim hContext As Long
    Dim strKey As String
    Dim strHexString As String
    Dim sCorrect As String

    strKey = "0123456789abcdef"
    Debug.Print "KY=" & strKey

    ' Initialise the context
    hContext = BLF_InitHex(strKey, True, "ECB", "")
    If hContext = 0 Then
        ' Always check for error
        MsgBox "Unable to initialise BLF context", vbCritical
        Exit Function
    End If

    '              "Now is t"
    strHexString = "4e6f772069732074"
    Debug.Print "PT=" & strHexString
    nRet = BLF_UpdateHex(hContext, strHexString)
    Debug.Print "CT=" & strHexString
    Debug.Print "OK=" & "cb08e682c67e32e2"

    '              "he time for all"
    strHexString = "68652074696d6520666f7220616c6c20"
    Debug.Print "PT=" & strHexString
    nRet = BLF_UpdateHex(hContext, strHexString)
    Debug.Print "CT=" & strHexString
    Debug.Print "OK=" & "8fcb010ac2ce9b1d9c4538762e33b52f"

    nRet = BLF_Final(hContext)

```

This should result in output as follows:

```

KY=0123456789abcdef
PT=4e6f772069732074
CT=CB08E682C67E32E2
OK=cb08e682c67e32e2
PT=68652074696d6520666f7220616c6c20
CT=8FCB010AC2CE9B1D9C4538762E33B52F
OK=8fcb010ac2ce9b1d9c4538762e33b52f

```

### See Also

[`BLF_Init`](#BLF_Init)
[`BLF_InitHex`](#BLF_InitHex)
[`BLF_Update`](#BLF_Update)
[`BLF_Final`](#BLF_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_DecryptBytes"></a>CIPHER_DecryptBytes
---------------------------------------------------

Decrypts data in a byte array using the specified block cipher algorithm, mode and padding.
The key and initialization vector are passed as byte arrays.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_DecryptBytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_DecryptBytes(lpOutput(0), nOutBytes, abInput(0), nInputLen, abKey(0), nKeyLen, abIV(0), nIvLen, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_DecryptBytes(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output (*must be at least as long as the input*, see ** in remarks)).

*nOutBytes*
:   [in] specifying the length of the output buffer in bytes.

*lpInput*
:   [in] array containing the input data.

*nInputLen*
:   [in] specifying the length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] the length of the key in bytes.

*lpIV*
:   [in] containing the initialization vector (IV), or zero (0) or `NULL` for ECB mode.

*nIvLen*
:   [in] the length of the IV in bytes.

*szAlgModePad*
:   [in] containing the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to expect the IV to be prepended at the start of the file (ignored for ECB mode).

### Returns (VBA/C)

If successful, the return value is the number of bytes required in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherDecryptBytes](#VB_cipherDecryptBytes)(lpInput() As Byte, lpKey() As Byte, lpIV() As Byte, szAlgModePad As String, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Cipher.Decrypt Method](#M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)  

### Python Equivalent

`static [Cipher.decrypt](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.decrypt "External link")(data, key, iv=None, algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

`static [Cipher.decrypt_block](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.decrypt_block "External link")(data, key, iv=None, alg=Alg.TDEA, mode=Mode.ECB)`

### Remarks

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

The length of key *lpKey* must be *exactly* the required key size, 
and the length of the IV, if required, *exactly* the block size.
See [Valid key and block sizes](#blockciphersizes).

[*New in v5.4*] You can find the required output length in bytes by setting
*nOutBytes* to zero or *lpOutput* to 0 (or `NULL` in C or `ByVal 0&` in VBA).
For ECB and CBC cipher modes, the return value will be the exact length of plaintext *after* padding has been removed (or a negative error code).

** For ECB and CBC cipher modes, any padding must be removed. To specify the length of *lpOutput* you can either
1. [ORIGINAL METHOD] specify the output length of *lpOutput* equal to the length of the input then truncate the result to the correct length.
2. [NEW in v5.4] do a first pass setting *nOutBytes* to zero or *lpOutput* to 0 or `NULL` to find the exact decrypted length.

See the examples below. In both cases you may need to cope with the special case where the encrypted output is the empty string, a zero-length byte array.

It is an error (`DECRYPT_ERROR`) if the padding bytes after decryption are not as expected according to the padding method specified.
If the cipher mode is ECB or CBC, it is an error (`BAD_LENGTH_ERROR`) 
if the length of the input is not an exact multiple of the block size.
The input buffer *lpInput* may point to the same location as the output buffer. 
If so, the input ciphertext data will be overwritten by the output (and the user must truncate to remove any padding bytes).

**Defaults:** If padding is not specified then the default padding method depends on the cipher mode: 
`pkcs5padding` will be used for ECB and CBC mode and `nopadding` for all other modes.
The default cipher mode is `ECB`. 
Thus `"aes128"` is the same as `"aes128/ecb/pkcs5padding"`.

### Example (VBA core function)

```

Dim key() As Byte
Dim iv() As Byte
Dim ct() As Byte
Dim ok() As Byte
Dim dt() As Byte
Dim ctlen As Long
Dim dtlen As Long
Dim keylen As Long
Dim ivlen As Long
Dim algstr As String

' INPUT for known test vector
algstr = "Aes128/CBC/OneAndZeroes"
Debug.Print algstr
key = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
iv = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
keylen = UBound(key) + 1
ivlen = UBound(iv) + 1
Debug.Print ("KY=" & cnvHexStrFromBytes(key))
Debug.Print ("IV=" & cnvHexStrFromBytes(iv))
ct = cnvBytesFromHexStr("C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B")
ctlen = UBound(ct) + 1
Debug.Print ("CT=" & cnvHexStrFromBytes(ct))
' OK = "Now is the time for all good men to"
ok = cnvBytesFromHexStr("4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F")

' DECRYPT - OLD METHOD WITH TRUNCATION
Debug.Print "Decrypt - old method with truncation"
' 1. Set output buffer to same length as input (final output will always be shorter for CBC mode)
dtlen = ctlen
ReDim dt(dtlen - 1)
' 2. Perform decryption including padding into output buffer
dtlen = CIPHER_DecryptBytes(dt(0), dtlen, ct(0), ctlen, key(0), keylen, iv(0), ivlen, algstr, 0)
Debug.Print "CIPHER_DecryptBytes returns " & dtlen
Debug.Assert dtlen > 0
' 3. Re-dimension the output to the correct length
ReDim Preserve dt(dtlen - 1)

Debug.Print ("DT=" & cnvHexStrFromBytes(dt))
Debug.Print ("DT='" & StrConv(dt, vbUnicode) + "'")

' DECRYPT - NEW METHOD WITH EXACT LENGTH
Debug.Print "Decrypt - new method with exact length"
' 1. Find exact output length using null/zero-length output
dtlen = CIPHER_DecryptBytes(ByVal 0&, 0, ct(0), ctlen, key(0), keylen, iv(0), ivlen, algstr, 0)
Debug.Print "CIPHER_DecryptBytes(NULL) returns " & dtlen
Debug.Assert dtlen > 0
' 2. Dimension output buffer to exact length
ReDim dt(dtlen - 1)
' 3. Perform decryption - no need to truncate
dtlen = CIPHER_DecryptBytes(dt(0), dtlen, ct(0), ctlen, key(0), keylen, iv(0), ivlen, algstr, 0)
Debug.Print "CIPHER_DecryptBytes returns " & dtlen
Debug.Assert dtlen > 0

Debug.Print ("DT=" & cnvHexStrFromBytes(dt))
Debug.Print ("DT='" & StrConv(dt, vbUnicode) + "'")

Debug.Print "Check actual padding by decrypting with NoPadding..."
algstr = "Aes128/CBC/NoPadding"
Debug.Print algstr
dtlen = ctlen
ReDim dt(dtlen - 1)
dtlen = CIPHER_DecryptBytes(dt(0), dtlen, ct(0), ctlen, key(0), keylen, iv(0), ivlen, algstr, 0)
Debug.Print "CIPHER_DecryptBytes(NoPadding) returns " & dtlen
Debug.Print ("DT=" & cnvHexStrFromBytes(dt))

```

This should result in output as follows:

```

Aes128/CBC/OneAndZeroes
KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
Decrypt - old method with truncation
CIPHER_DecryptBytes returns 35
DT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
DT='Now is the time for all good men to'
Decrypt - new method with exact length
CIPHER_DecryptBytes(NULL) returns 35
CIPHER_DecryptBytes returns 35
DT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
DT='Now is the time for all good men to'
Check actual padding by decrypting with NoPadding...
Aes128/CBC/NoPadding
CIPHER_DecryptBytes(NoPadding) returns 48
DT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F80000000000000000000000000

```

**Example 2:** showing use of `API_IV_PREFIX` to prepend the IV before the ciphertext in the output.

```

Dim strCipherValue As String
Dim strPlain As String
Dim pt() As Byte
Dim ptlen As Long
Dim ct() As Byte
Dim ctlen As Long
Dim key() As Byte
Dim keylen As Long
Dim iv() As Byte
Dim ivlen As Long
Dim nRet As Long
Dim strDT As String
Dim dt() As Byte
Dim dtlen As Long

' The plaintext to encrypt...
strPlain = "<encryptme>hello world</encryptme>"
Debug.Print "PT='" & strPlain & "'"

' We need this as a byte array...
pt = StrConv(strPlain, vbFromUnicode)
Debug.Print "HEX(PT)=" & cnvHexStrFromBytes(pt)
ptlen = UBound(pt) + 1
Debug.Print "Len(PT)=" & ptlen

' 128-bit AES key
' (Secret key agreed between parties)
key = cnvBytesFromHexStr("6162636465666768696A6B6C6D6E6F70")
keylen = UBound(key) + 1
Debug.Print "HEX(KEY)=" & cnvHexStrFromBytes(key)

' Generate a random 128-bit IV for AES encryption
ivlen = API_BLK_AES_BYTES
ReDim iv(ivlen - 1)
nRet = RNG_NonceData(iv(0), ivlen)
Debug.Print "HEX(IV)=" & cnvHexStrFromBytes(iv)

' Encrypt using AES-128 with IV prefixed to ciphertext

' How many bytes in the encrypted output?
ctlen = CIPHER_EncryptBytes(ByVal 0&, 0, pt(0), ptlen, key(0), keylen, iv(0), ivlen, "aes128/cbc/pkcs5", API_IV_PREFIX)
Debug.Print "Len(IV|CT)=" & ctlen
Debug.Assert (ctlen > 0)
' Allocate the buffer
ReDim ct(ctlen - 1)
' Encrypt to output buffer
ctlen = CIPHER_EncryptBytes(ct(0), ctlen, pt(0), ptlen, key(0), keylen, iv(0), ivlen, "aes128/cbc/pkcs5", API_IV_PREFIX)
Debug.Assert (ctlen > 0)
Debug.Print "IV|CT=" & cnvHexStrFromBytes(ct)

' Encode CT using base64
strCipherValue = cnvB64StrFromBytes(ct)

' Output the CipherValue element
' (Note this will be different each time)
Debug.Print "<CipherValue>" & strCipherValue & "</CipherValue>"

' ------------------------------------------
' PART 2 - decrypt the given ciphertext

Debug.Print
Debug.Print "DECRYPTING..."
' INPUT: strCipherValue, key
' Decode base64 to byte array
ct = cnvBytesFromB64Str(strCipherValue)
ctlen = UBound(ct) + 1
Debug.Print "IV|CT=" & cnvHexStrFromBytes(ct)
' Find decrypted output length - new behaviour in [v5.4] (previously needed to truncate)
dtlen = CIPHER_DecryptBytes(ByVal 0&, 0, ct(0), ctlen, key(0), keylen, ByVal 0&, 0, "aes128/cbc/pkcs5", API_IV_PREFIX)
Debug.Assert (dtlen > 0)
ReDim dt(dtlen - 1)
' Note we don't need to specify the IV: it is included in the prefix
dtlen = CIPHER_DecryptBytes(dt(0), dtlen, ct(0), ctlen, key(0), keylen, ByVal 0&, 0, "aes128/cbc/pkcs5", API_IV_PREFIX)
Debug.Print "Len(DT)=" & dtlen
Debug.Assert (dtlen >= 0)

Debug.Print "DT=" & cnvHexStrFromBytes(dt)
' Convert from bytes to string
strDT = StrConv(dt, vbUnicode)
Debug.Print "DT='" & strDT & "'"

```

```

PT='<encryptme>hello world</encryptme>'
HEX(PT)=3C656E63727970746D653E68656C6C6F20776F726C643C2F656E63727970746D653E
Len(PT)=34
HEX(KEY)=6162636465666768696A6B6C6D6E6F70
HEX(IV)=556DA05DF58DE51874B032768BA99A26
Len(IV|CT)=64
IV|CT=556DA05DF58DE51874B032768BA99A26884B6CD2045916D7F1D8D88E6BB8F5520C69479D352701BBBA2E67DE03DF0319B3C83EA90093AC6C77E4709A26B46E80
<CipherValue>VW2gXfWN5Rh0sDJ2i6maJohLbNIEWRbX8djYjmu49VIMaUedNScBu7ouZ94D3wMZs8g+qQCTrGx35HCaJrRugA==</CipherValue>

DECRYPTING...
IV|CT=556DA05DF58DE51874B032768BA99A26884B6CD2045916D7F1D8D88E6BB8F5520C69479D352701BBBA2E67DE03DF0319B3C83EA90093AC6C77E4709A26B46E80
Len(DT)=34
DT=3C656E63727970746D653E68656C6C6F20776F726C643C2F656E63727970746D653E
DT='<encryptme>hello world</encryptme>'

```

### Example (VBA wrapper function)

See example for VBA wrapper `cipherEncryptBytes` in [CIPHER_EncryptBytes](#CIPHER_EncryptBytes).

### See Also

[CIPHER_EncryptBytes](#CIPHER_EncryptBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_DecryptBytes2"></a>CIPHER_DecryptBytes2
-----------------------------------------------------

@deprecated use `[CIPHER_DecryptBytes](#CIPHER_DecryptBytes)`.

<a id="CIPHER_DecryptHex"></a>CIPHER_DecryptHex
-----------------------------------------------

Decrypt data using the specified block cipher algorithm, mode and padding. 
The input data, key and initialization vector are all represented as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_DecryptHex Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nOutChars As Long, ByVal strInputHex As String, ByVal strKeyHex As String, ByVal strIvHex As String, ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_DecryptHex(strOutput, nOutChars, strInputHex, strKeyHex, strIvHex, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_DecryptHex(char *szOutput, long nOutChars, const char *szInputHex, const char *szKeyHex, const char *szIvHex, const char *szAlgModePad, long nOptions);`

### Parameters

*szOutput*
:   [out] string buffer of sufficient length to receive the output.

*nOutChars*
:   [in] maximum number of characters to be received.

*szInputHex*
:   [in] the input data in hex format.

*szKeyHex*
:   [in] the key in hex format.

*szIvHex*
:   [in] the initialization vector (IV) in hex format, ignored for ECB mode or if `API_IV_PREFIX` is used (use `""`).

*szAlgModePad*
:   [in] string specifying the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to expect the IV to be prepended before the ciphertext in the input (not applicable for ECB mode).

### Returns (VBA/C)

If successful, the return value is the number of characters in or required in the output;
otherwise it returns a nonzero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherDecryptHex](#VB_cipherDecryptHex)(szInputHex As String, szKeyHex As String, szIvHex As String, szAlgModePad As String, Optional nOptions As Long = 0) As String`

### .NET Equivalent

[Cipher.Decrypt Method](#M_Cipher_Decrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)  

### Python Equivalent

`static [Cipher.decrypt_hex](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.decrypt_hex "External link")(datahex, keyhex, ivhex='', algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length. C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

This is the equivalent of [`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes) with all parameters passed as hex-encoded strings instead of byte arrays.

Any padding will be removed after decryption.

If the `API_IV_PREFIX` option is used, the IV will be expected prepended to the ciphertext in the input.

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

It is an error (`BAD_PARAM_ERROR`) to pass the empty string `""` as input in *szInputHex*.
The output buffer *strOutput* should *not* be the same as the input *strInputHex*.

CAUTION: be aware of the special case where the output is the empty string `""` of length zero.

### Example (VBA core function)

```

Dim strKey As String
Dim strIV As String
Dim strPlain As String
Dim strCipher As String
Dim strOK As String
Dim strAlg As String
Dim nChars As Long

strAlg = "Aes128/CBC/OneAndZeroes"
Debug.Print strAlg
strKey = "0123456789ABCDEFF0E1D2C3B4A59687"
strIV = "FEDCBA9876543210FEDCBA9876543210"
Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
strCipher = "C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"
Debug.Print "CT=" & strCipher
' Correct result
strOK = "4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F"

' 1. Find out how long an output buffer we need
nChars = CIPHER_DecryptHex(vbNullString, 0, strCipher, strKey, strIV, strAlg, 0)
Debug.Print "CIPHER_DecryptHex returns " & nChars
Debug.Assert nChars > 0
' 2. Allocate the buffer
strPlain = String(nChars, " ")
' 3. Decrypt to output buffer
nChars = CIPHER_DecryptHex(strPlain, nChars, strCipher, strKey, strIV, strAlg, 0)

Debug.Print "PT=" & strPlain
Debug.Print "OK=" & strOK

' PART 2 - CT includes IV prefix
strCipher = "FEDCBA9876543210FEDCBA9876543210C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"
Debug.Print "IV||CT=" & strCipher
nChars = CIPHER_DecryptHex(vbNullString, 0, strCipher, strKey, strIV, strAlg, API_IV_PREFIX)
Debug.Print "CIPHER_DecryptHex(API_IV_PREFIX) returns " & nChars
Debug.Assert nChars > 0
strPlain = String(nChars, " ")
nChars = CIPHER_DecryptHex(strPlain, nChars, strCipher, strKey, strIV, strAlg, API_IV_PREFIX)

Debug.Print "PT=" & strPlain
Debug.Print "PT='" & cnvStringFromHexStr(strPlain) & "'"

```

This should result in output as follows:

```

Aes128/CBC/OneAndZeroes
KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
CIPHER_DecryptHex returns 70
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
OK=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
IV||CT=FEDCBA9876543210FEDCBA9876543210C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
CIPHER_DecryptHex(API_IV_PREFIX) returns 70
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
PT='Now is the time for all good men to'

```

### Example (VBA wrapper function)

```

Dim strKeyHex As String
Dim strIvHex As String
Dim strPlainHex As String
Dim strCipherHex As String
strKeyHex = "0123456789ABCDEFF0E1D2C3B4A59687"
strIvHex = "FEDCBA9876543210FEDCBA9876543210"
strCipherHex = "C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"
strPlainHex = cipherDecryptHex(strCipherHex, strKeyHex, strIvHex, "Aes128/CBC/OneAndZeroes")
Debug.Print "PT=" & strPlainHex
Debug.Print "PT='" & cnvStringFromHexStr(strPlainHex) & "'"
' PART 2 - CT includes IV prefix
strCipherHex = "FEDCBA9876543210FEDCBA9876543210C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"
Debug.Print "IV||CT=" & strCipherHex
strPlainHex = cipherDecryptHex(strCipherHex, strKeyHex, strIvHex, "Aes128/CBC/OneAndZeroes", API_IV_PREFIX)
Debug.Print "PT=" & strPlainHex
Debug.Print "PT='" & cnvStringFromHexStr(strPlainHex) & "'"

```

### See Also

[CIPHER_EncryptHex](#CIPHER_EncryptHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_EncryptBytes"></a>CIPHER_EncryptBytes
---------------------------------------------------

Encrypts data in a byte array using the specified block cipher algorithm, mode and padding.
The key and initialization vector are passed as byte arrays.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_EncryptBytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_EncryptBytes(lpOutput(0), nOutBytes, abInput(0), nInputLen, abKey(0), nKeylen
abIV(0), nIvLen, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_EncryptBytes(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*nOutBytes*
:   [in] specifying the length of the output buffer in bytes.

*lpInput*
:   [in] array containing the input data.

*nInputLen*
:   [in] specifying the length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] the length of the key in bytes.

*lpIV*
:   [in] containing the initialization vector (IV), or zero (0) or `NULL` for ECB mode.

*nIvLen*
:   [in] the length of the IV in bytes.

*szAlgModePad*
:   [in] containing the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output (ignored for ECB mode).

### Returns (VBA/C)

If successful, the return value is the number of bytes required in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherEncryptBytes](#VB_cipherEncryptBytes)(lpInput() As Byte, lpKey() As Byte, lpIV() As Byte, szAlgModePad As String, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Cipher.Encrypt Method](#M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)  

### Python Equivalent

`static [Cipher.encrypt](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.encrypt "External link")(data, key, iv=None, algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

`static [Cipher.encrypt_block](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.encrypt_block "External link")(data, key, iv=None, alg=Alg.TDEA, mode=Mode.ECB)`

### Remarks

Padding is added as specified to the input before encryption.
The user must allocate an output buffer of the required length, which will always be at least as long as the input,
or longer if padding is to be added.

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

The length of key *lpKey* must be *exactly* the required key size, 
and the length of the IV, if required, *exactly* the block size.
See [Valid key and block sizes](#blockciphersizes).

If *nOutBytes* is set to zero or *lpOutput* set to 0 (or `NULL` in C or `ByVal 0&` in VBA), 
the required number of bytes will be returned.
If the `NoPadding` option is specified, the required output length will be the same as the input.

**Defaults:** If padding is not specified then the default padding method depends on the cipher mode: 
`pkcs5padding` will be used for ECB and CBC mode and `nopadding` for all other modes.
The default cipher mode is `ECB`. 
Thus `"aes128"` is the same as `"aes128/ecb/pkcs5padding"`.

Note that padding is only needed for ECB or CBC mode where the input length is not a multiple of the block size.
It is an error (`BAD_LENGTH_ERROR`) to specify `NoPadding` with ECB or CBC mode if the length of the input 
is not an exact multiple of the block size.

The padding option is ignored for CTR, OFB and CFB modes, which do not need padding.
The default `nopadding` is *always* used for these modes regardless of what is specified 
(so just use the default, e.g. `"aes128/ctr"`).

*[New in v5.4]*
Use the `API_IV_PREFIX` to prepend the IV before the ciphertext in the output.
This will add the IV before the ciphertext in the form `IV||CT`.
This is the scheme used with block ciphers in XML encryption (see section 5.2 of [[XMLENC](#XMLENC)])
where they use the phrase "The resulting cipher text is prefixed by the IV."
It is the responsibility of the receiver to parse this data to recover the IV.

### Example (VBA core function)

```

Dim key() As Byte
Dim iv() As Byte
Dim pt() As Byte
Dim ct() As Byte
Dim ok() As Byte
Dim ptlen As Long
Dim ctlen As Long
Dim keylen As Long
Dim ivlen As Long
Dim algstr As String

algstr = "Aes128/CBC/OneAndZeroes"
Debug.Print algstr
key = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
iv = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
keylen = UBound(key) + 1
ivlen = UBound(iv) + 1
Debug.Print "KY=" & cnvHexStrFromBytes(key)
Debug.Print "IV=" & cnvHexStrFromBytes(iv)
' "Now is the time for all good men to"
pt = cnvBytesFromHexStr("4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F")
ptlen = UBound(pt) + 1
' Correct result
ok = cnvBytesFromHexStr("C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B")
Debug.Print ("PT=" & cnvHexStrFromBytes(pt))
Debug.Print ("PT='" & StrConv(pt, vbUnicode) + "'")
' 1. Find out how long an output buffer we need
ctlen = CIPHER_EncryptBytes(0, 0, pt(0), ptlen, key(0), keylen, iv(0), ivlen, algstr, 0)
Debug.Print "CIPHER_EncryptBytes returns " & ctlen
' 2. Allocate the buffer
ReDim ct(ctlen - 1)
' 3. Encrypt to output buffer
ctlen = CIPHER_EncryptBytes(ct(0), ctlen, pt(0), ptlen, key(0), keylen, iv(0), ivlen, algstr, 0)

Debug.Print "CT=" & cnvHexStrFromBytes(ct)
Debug.Print "OK=" & cnvHexStrFromBytes(ok)

' PART 2 - prefix the IV in the output
ctlen = CIPHER_EncryptBytes(0, 0, pt(0), ptlen, key(0), keylen, iv(0), ivlen, algstr, API_IV_PREFIX)
Debug.Print "CIPHER_EncryptBytes(API_IV_PREFIX) returns " & ctlen
ReDim ct(ctlen - 1)
ctlen = CIPHER_EncryptBytes(ct(0), ctlen, pt(0), ptlen, key(0), keylen, iv(0), ivlen, algstr, API_IV_PREFIX)

Debug.Print "IV||CT=" & cnvHexStrFromBytes(ct)

```

This should result in output as follows:

```

Aes128/CBC/OneAndZeroes
KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
PT='Now is the time for all good men to'
CIPHER_EncryptBytes returns 48
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
OK=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B

```

*[New in v12.3]*
Use the `API_IV_PREFIX` option to prepend the IV to the ciphertext in the output.

```

CIPHER_EncryptBytes(API_IV_PREFIX) returns 64
IV||CT=FEDCBA9876543210FEDCBA9876543210C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
       <------IV (16 bytes)-----------><--------CT (48 bytes)------------------------------------------------------------------------->

```

For another example of using `API_IV_PREFIX` see the second example in 
[CIPHER_DecryptBytes](#CIPHER_DecryptBytes).

### Example (VBA wrapper function)

```

Dim key() As Byte
Dim iv() As Byte
Dim pt() As Byte
Dim ct() As Byte
Dim dt() As Byte
Dim algstr As String

' PART 1
algstr = "Aes128/CBC/OneAndZeroes"
Debug.Print algstr
key = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
iv = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
' "Now is the time for all good men to"
pt = cnvBytesFromHexStr("4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F")

ct = cipherEncryptBytes(pt, key, iv, algstr)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)
Debug.Print "OK=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"

dt = cipherDecryptBytes(ct, key, iv, algstr)
Debug.Print "dt='" & StrConv(dt, vbUnicode) & "'"

' PART 2 - Use CTR mode and prefix the IV in the output
algstr = "Aes128/CTR"
Debug.Print algstr & " + PREFIX"
ct = cipherEncryptBytes(pt, key, iv, algstr, API_IV_PREFIX)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)
dt = cipherDecryptBytes(ct, key, iv, algstr, API_IV_PREFIX)
Debug.Print "dt='" & StrConv(dt, vbUnicode) & "'"

' PART 3 - Use ECB mode and pass an empty byte array for the IV
algstr = "Aes128/ECB"
Debug.Print algstr
iv = vbNullString     ' Set IV as empty array
ct = cipherEncryptBytes(pt, key, iv, algstr)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)
dt = cipherDecryptBytes(ct, key, iv, algstr)
Debug.Print "dt='" & StrConv(dt, vbUnicode) & "'"

```

### See Also

[CIPHER_DecryptBytes](#CIPHER_DecryptBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_EncryptBytes2"></a>CIPHER_EncryptBytes2
-----------------------------------------------------

@deprecated use `[CIPHER_EncryptBytes](#CIPHER_EncryptBytes)`.

<a id="CIPHER_EncryptHex"></a>CIPHER_EncryptHex
-----------------------------------------------

Encrypt data using the specified block cipher algorithm, mode and padding. 
The input data, key and initialization vector are all represented as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_EncryptHex Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nOutChars As Long, ByVal strInputHex As String, ByVal strKeyHex As String, ByVal strIvHex As String, ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_EncryptHex(strOutput, nOutChars, strInputHex, strKeyHex, strIvHex, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_EncryptHex(char *szOutput, long nOutChars, const char *szInputHex, const char *szKeyHex, const char *szIvHex, const char *szAlgModePad, long nOptions);`

### Parameters

*szOutput*
:   [out] string buffer of sufficient length to receive the output.

*nOutChars*
:   [in] maximum number of characters to be received.

*szInputHex*
:   [in] the input data in hex format.

*szKeyHex*
:   [in] the key in hex format.

*szIvHex*
:   [in] the initialization vector (IV) in hex format, ignored for ECB mode (use `""`).

*szAlgModePad*
:   [in] string specifying the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output (ignored for ECB mode).

### Returns (VBA/C)

If successful, the return value is the number of characters in or required in the output;
otherwise it returns a nonzero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherEncryptHex](#VB_cipherEncryptHex)(szInputHex As String, szKeyHex As String, szIvHex As String, szAlgModePad As String, Optional nOptions As Long = 0) As String`

### .NET Equivalent

[Cipher.Encrypt Method](#M_Cipher_Encrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)  

### Python Equivalent

`static [Cipher.encrypt_hex](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.encrypt_hex "External link")(datahex, keyhex, ivhex='', algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length. C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

This is the equivalent of [`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes) with all parameters passed as hex-encoded strings instead of byte arrays.

Padding is added as specified to the input before encryption. The output will always be at least as long as the input,
or longer if padding or a prefixed IV is to be added.

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

It is an error (`BAD_PARAM_ERROR`) to pass the empty string `""` as input in *szInputHex*.
The output buffer *strOutput* should *not* be the same as the input *strInputHex*.

Use the `API_IV_PREFIX` option to prepend the IV before the ciphertext in the output.
This will add the IV before the ciphertext in the form `IV||CT`.
This is the scheme used with block ciphers in XML encryption (see section 5.2 of [[XMLENC](#XMLENC)])
where they use the phrase "The resulting cipher text is prefixed by the IV."

### Example (VBA core function)

```

Dim strKey As String
Dim strIV As String
Dim strPlain As String
Dim strCipher As String
Dim strOK As String
Dim strAlg As String
Dim nChars As Long

strAlg = "Aes128/CBC/OneAndZeroes"
Debug.Print strAlg
strKey = "0123456789ABCDEFF0E1D2C3B4A59687"
strIV = "FEDCBA9876543210FEDCBA9876543210"
Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
' "Now is the time for all good men to"
strPlain = "4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F"
Debug.Print "PT=" & strPlain
Debug.Print "PT='" & cnvStringFromHexStr(strPlain) & "'"
' Correct result
strOK = "C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B"

' 1. Find out how long an output buffer we need
nChars = CIPHER_EncryptHex(vbNullString, 0, strPlain, strKey, strIV, strAlg, 0)
Debug.Print "CIPHER_EncryptHex returns " & nChars
Debug.Assert nChars > 0
' 2. Allocate the buffer
strCipher = String(nChars, " ")
' 3. Encrypt to output buffer
nChars = CIPHER_EncryptHex(strCipher, nChars, strPlain, strKey, strIV, strAlg, 0)

Debug.Print "CT=" & strCipher
Debug.Print "OK=" & strOK

' PART 2 - prefix the IV in the output
nChars = CIPHER_EncryptHex(vbNullString, 0, strPlain, strKey, strIV, strAlg, API_IV_PREFIX)
Debug.Print "CIPHER_EncryptHex(API_IV_PREFIX) returns " & nChars
Debug.Assert nChars > 0
strCipher = String(nChars, " ")
nChars = CIPHER_EncryptHex(strCipher, nChars, strPlain, strKey, strIV, strAlg, API_IV_PREFIX)

Debug.Print "IV||CT=" & strCipher

```

This should result in output as follows:

```

Aes128/CBC/OneAndZeroes
KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F
PT='Now is the time for all good men to'
CIPHER_EncryptHex returns 96
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
OK=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B
CIPHER_EncryptHex(API_IV_PREFIX) returns 128
IV||CT=FEDCBA9876543210FEDCBA9876543210C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E1771D4CDA34FBFB7E74B321F9A2CF4EA61B

```

### Example (VBA wrapper function)

```

Dim strKeyHex As String
Dim strIvHex As String
Dim strPlainHex As String
Dim strCipherHex As String
strKeyHex = "0123456789ABCDEFF0E1D2C3B4A59687"
strIvHex = "FEDCBA9876543210FEDCBA9876543210"
strPlainHex = "4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E20746F"

' Get encrypted output directly in hex
strCipherHex = cipherEncryptHex(strPlainHex, strKeyHex, strIvHex, "Aes128/CBC/OneAndZeroes", 0)
Debug.Print strCipherHex

' Same again with hex using ECB mode with default PKCS#5 padding
' To pass a "null" IV in hex, just use the empty string
strCipherHex = cipherEncryptHex(strPlainHex, strKeyHex, "", "Aes128/ECB", 0)
Debug.Print strCipherHex

' Or vbNullString
strCipherHex = cipherEncryptHex(strPlainHex, strKeyHex, vbNullString, "Aes128/ECB", 0)
Debug.Print strCipherHex

```

### See Also

[CIPHER_DecryptHex](#CIPHER_DecryptHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_FileDecrypt"></a>CIPHER_FileDecrypt
-------------------------------------------------

Decrypts a file using specified block cipher algorithm, mode and padding.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_FileDecrypt Lib "diCryptoSys.dll" 
(ByVal strFileOut As String, ByVal strFileIn As String, 
ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nKeyLen As Long, 
ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_FileDecrypt(strFileOut, strFileIn, abKey(0), nKeyLen, abIV(0), nIvLen, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_FileDecrypt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output file to be created.

*szFileIn*
:   [in] with the full path name of the input file to be processed.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] specifying the length of the key in bytes.

*lpIV*
:   [in] containing the initialization vector (IV), if required.

*nIvLen*
:   [in] specifying the length of the IV in bytes.

*szAlgModePad*
:   [in] containing the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to expect the IV to be prepended at the start of the file (ignored for ECB mode).

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonzero [error code](#errorcodes).

### .NET Equivalent

[Cipher.FileDecrypt Method](#M_Cipher_FileDecrypt)  

### Python Equivalent

`static [Cipher.file_decrypt](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.file_decrypt "External link")(fileout, filein, key, iv, algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

### Remarks

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

The length of key must be *exactly* the required key size, 
and the length of the IV, if required, *exactly* the block size.
See [Valid key and block sizes](#blockciphersizes).

The output file *szFileOut* will be overwritten without warning.
If there is an error, the output file will **not exist**.
The input and output files must **not** be the same.

**Prepended IV:** If the ciphertext file was created with the IV prepended at the start of the file, then you 
	*must* specify the `API_IV_PREFIX` option. In this case, leave the *lpIV* parameter empty.
	The input file is expected to be of the form `IV||ciphertext`.

**Defaults:** If padding is not specified then the default padding method depends on the cipher mode: 
`pkcs5padding` will be used for ECB and CBC mode and `nopadding` for all other modes.
The default cipher mode is `ECB`. 
Thus `"aes128"` is the same as `"aes128/ecb/pkcs5padding"`.

**Padding:** When decrypting you can specify `NoPadding` to leave any padding intact in the deciphered file.
	This is useful if you wish to examine an unknown padding scheme.
Otherwise, when decrypting in ECB or CBC mode, you *must* specify the same padding scheme used when encrypting.
It is an error (`DECRYPT_ERROR`) if the expected padding string is not found after decrypting.
The padding parameter is ignored when decrypting in CTR, OFB or CFB mode.

### Example

See example in [CIPHER_FileEncrypt](#CIPHER_FileEncrypt).

### See Also

[CIPHER_FileEncrypt](#CIPHER_FileEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_FileEncrypt"></a>CIPHER_FileEncrypt
-------------------------------------------------

Encrypts a file using specified block cipher algorithm, mode and padding. 
The IV may be prepended to the file, if required.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_FileEncrypt Lib "diCryptoSys.dll" 
(ByVal strFileOut As String, ByVal strFileIn As String, 
ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, 
ByVal strAlgModePad As String, ByVal nOptions As Long) As Long`

`nRet = CIPHER_FileEncrypt(strFileOut, strFileIn, abKey(0), nKeyLen,
abIV(0), nIvLen, strAlgModePad, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_FileEncrypt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output file to be created.

*szFileIn*
:   [in] with the full path name of the input file to be processed.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] specifying the length of the key in bytes.

*lpIV*
:   [in] containing the initialization vector (IV), if required.

*nIvLen*
:   [in] specifying the length of the IV in bytes.

*szAlgModePad*
:   [in] containing the block cipher algorithm, mode and padding
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

*nOptions*
:   [in] option flags:  

	Zero (0) for default options. Optionally add:  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode).

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonzero [error code](#errorcodes).

### .NET Equivalent

[Cipher.FileEncrypt Method](#M_Cipher_FileEncrypt)  

### Python Equivalent

`static [Cipher.file_encrypt](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.file_encrypt "External link")(fileout, filein, key, iv, algmodepad='', alg=None, mode=Mode.ECB, pad=Pad.DEFAULT, opts=Opts.DEFAULT)`

### Remarks

The algorithm/mode/padding must be specified using either the *szAlgModePad* string or *nOptions* parameter,
but not both
(see [Specifying the algorithm, mode and padding for generic block cipher functions](#cipheralgmode)).

The length of key must be *exactly* the required key size, 
and the length of the IV, if required, *exactly* the block size.
See [Valid key and block sizes](#blockciphersizes).

The output file *szFileOut* will be overwritten without warning.
If there is an error, the output file will **not exist**.
The input and output files must **not** be the same.

**Prepended IV:** If the `API_IV_PREFIX` option flag is set in *nOptions* then the IV will be
prepended (i.e. added) at the start of the output file.
That is, the output file will be of the form `IV||ciphertext`.
The `API_IV_PREFIX` flag is ignored in ECB mode where an IV is not needed.

**Defaults:** If padding is not specified then the default padding method depends on the cipher mode: 
`pkcs5padding` will be used for ECB and CBC mode and `nopadding` for all other modes.
The default cipher mode is `ECB`. 
Thus `"aes128"` is the same as `"aes128/ecb/pkcs5padding"`.

**Padding:** In normal circumstances you should leave the padding unspecified and use the default padding when encrypting.
The only time it should be required is if you want to use an exotic padding like `OneAndZeroesPadding` 
instead of `pkcs5padding` with ECB or CBC mode.
Note that, unlike the behaviour with `[CIPHER_EncryptBytes](#CIPHER_EncryptBytes)`,
it is an error (`BAD_PARAM_ERROR`) to specify `NoPadding` when encrypting a file with ECB or CBC mode 
*under any circumstances*.
The padding option is ignored for CTR, OFB and CFB modes; that is,
the default `NoPadding` is *always* used for these modes regardless of what is specified (so just use the default, 
e.g. `"aes128/ctr"`).

### Example

```

Dim abKey() As Byte
Dim abIV() As Byte
Dim nKeyLen As Long
Dim nIvLen As Long
Dim strFileEnc As String
Dim strFileIn As String
Dim strFileChk As String
Dim strAlgModePad As String
Dim nRet As Long

' Construct full path names to files
strFileIn = "hello.txt"
strFileEnc = "hello.aes192.enc.dat"
strFileChk = "hello.aes192.chk.txt"

' Check input file
Debug.Print "FileLen('" & strFileIn & "')=" & FileLen(strFileIn)

' Create the AES-192 key as an array of 24 bytes
abKey = cnvBytesFromHexStr("fedcba9876543210fedcba98765432101122334455667788")
nKeyLen = UBound(abKey) + 1
Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
Debug.Print "LEN(KY)=" & nKeyLen
' Create the IV at random
ReDim abIV(API_BLK_AES_BYTES - 1)
Call RNG_NonceData(abIV(0), API_BLK_AES_BYTES)
' Display the IV (this will be prepended to the ciphertext in the output file)
Debug.Print "IV=" & cnvHexStrFromBytes(abIV)
nIvLen = UBound(abIV) + 1
Debug.Print "LEN(IV)=" & nIvLen

' Specify cipher alg/mode/padding
strAlgModePad = "aes192/CBC/ANSIX923"
Debug.Print strAlgModePad

' Encrypt the plaintext file, prefixing the IV
nRet = CIPHER_FileEncrypt(strFileEnc, strFileIn, abKey(0), nKeyLen, abIV(0), nIvLen, strAlgModePad, API_IV_PREFIX)
Debug.Print "CIPHER_FileEncrypt() returns " & nRet & " (expected 0)"
Debug.Assert (0 = nRet)

' Check output file
Debug.Print "FileLen('" & strFileEnc & "')=" & FileLen(strFileEnc)

' Now decipher using the IV already prefixed to the ciphertext
nRet = CIPHER_FileDecrypt(strFileChk, strFileEnc, abKey(0), nKeyLen, 0, 0, strAlgModePad, API_IV_PREFIX)
Debug.Print "CIPHER_FileDecrypt() returns " & nRet & " (expected 0)"
Debug.Assert (0 = nRet)

' Check decrypted file - it should match the original plaintext
Debug.Print "FileLen('" & strFileChk & "')=" & FileLen(strFileChk)
Debug.Assert (FileLen(strFileChk) = FileLen(strFileIn))

```

The input file is 13 bytes long (`"hello world\r\n"`). This is padded to 16 bytes when encrypted in CBC mode.
The output file contains 16 bytes of ciphertext plus the prepended IV of 16 bytes,
so it is 32 bytes long.

```

FileLen('hello.txt')=13
KY=FEDCBA9876543210FEDCBA98765432101122334455667788
LEN(KY)=24
IV=ECD982FF61DDC6506828690D20B55BBE
LEN(IV)=16
aes192/CBC/ANSIX923
CIPHER_FileEncrypt() returns 0 (expected 0)
FileLen('hello.aes192.enc.dat')=32
CIPHER_FileDecrypt() returns 0 (expected 0)
FileLen('hello.aes192.chk.txt')=13

```

### See Also

[CIPHER_FileDecrypt](#CIPHER_FileDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_Final"></a>CIPHER_Final
-------------------------------------

Closes and clears the CIPHER context. 

### VBA/VB6 Syntax

`Public Declare Function CIPHER_Final Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = CIPHER_Final(hContext)` 

### C/C++ Syntax

`long __stdcall CIPHER_Final(long hContext);`

### Parameters

*hContext*
:   [in] handle to the current CIPHER context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Cipher.Dispose Method](#M_Cipher_Dispose)  

### C++ (STL) Equivalent

`bool [crsysapi::Cipher::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#a9fb8ddb966e48754d13f72a27fed803f "External link") ()`

### Remarks

### Example

See [`CIPHER_Update`](#CIPHER_Update).

### See Also

[`CIPHER_Init`](#CIPHER_Init)
[`CIPHER_Update`](#CIPHER_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_Init"></a>CIPHER_Init
-----------------------------------

Initialize the CIPHER context with the key, iv, algorithm and mode ready for repeated update operations. 

### VBA/VB6 Syntax

`Public Declare Function CIPHER_Init Lib "diCryptoSys.dll" (ByVal fEncrypt As Integer, ByVal strAlgAndMode As String, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal nOptions As Long) As Long`

`hContext = CIPHER_Init(fEncrypt, strAlgAndMode, lpKey(0), nKeyLen, lpIV(0), nIvLen, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_Init(int fEncrypt, const char *szAlgAndMode, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, long nOptions);`

### Parameters

*fEncrypt*
:   [in] Direction flag: set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szAlgAndMode*
:   [in] String specifying the block cipher algorithm and mode, e.g. `"aes128/cbc"`
(see [Specifying the algorithm and mode for generic block cipher functions](#cipheralgmode)).

*lpKey*
:   [in] Key of exact length for block cipher algorithm.

*nKeyLen*
:   [in] Length of key in bytes.

*lpIV*
:   [in] Initialization Vector (IV) of exactly the block size, or zero (0) for ECB mode.

*nIvLen*
:   [in] Length of IV in bytes.

*nOptions*
:   [in] Option flags: zero (0) for default options.

### Returns (VBA/C)

Non-zero handle of the CIPHER context, or *zero* if an error occurs.

### VBA Wrapper Syntax

`Public Function [cipherInit](#VB_cipherInit)(fEncrypt As Integer, szAlgAndMode As String, lpKey() As Byte, lpIV() As Byte, Optional nOptions As Long = 0) As Long`

### .NET Equivalent

[Cipher.InitEncrypt Method](#M_Cipher_InitEncrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode)  

[Cipher.InitDecrypt Method](#M_Cipher_InitDecrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode)  

### C++ (STL) Equivalent

`bool [crsysapi::Cipher::InitDecrypt](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#ab4e4c6e06158886884ec7d27e651de54 "External link") (const bvec_t &key, const bvec_t &iv, Alg alg, Mode mode)  

bool [crsysapi::Cipher::InitEncrypt](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#a09a0220dc782f125dcd710ded8d8ab4e "External link") (const bvec_t &key, const bvec_t &iv, Alg alg, Mode mode)`

### Remarks

The key must be of the exact key length required for the cipher algorithm. The IV, if provided, must be exactly the length of the cipher block (16 bytes for AES, 8 bytes for Triple DES).

### Example

See [`CIPHER_Update`](#CIPHER_Update).

Example showing an error

```

Dim hContext As Long
hContext = cipherInit(ENCRYPT, "BADALG", cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687"), cnvBytesFromHexStr(""))
Debug.Print "cipherInit returns 0x" & Hex(hContext) & " (0 => error)"
Debug.Print "ErrorCode=" & API_ErrorCode() & ": " & apiErrorLookup(API_ErrorCode())

```

```

cipherInit returns 0x0 (0 => error)
ErrorCode=6: Parameter is wrong or missing (BAD_PARAM_ERROR)

```

### See Also

[`CIPHER_InitHex`](#CIPHER_InitHex)
[`CIPHER_Update`](#CIPHER_Update)
[`CIPHER_UpdateHex`](#CIPHER_UpdateHex)
[`CIPHER_Final`](#CIPHER_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_InitHex"></a>CIPHER_InitHex
-----------------------------------------

Initialize the CIPHER context with hex-encoded key, iv, algorithm and mode ready for repeated update operations. The key and IV data are passed as hexadecimal-encoded strings. 

### VBA/VB6 Syntax

`Public Declare Function CIPHER_InitHex Lib "diCryptoSys.dll" (ByVal fEncrypt As Integer, ByVal strAlgAndMode As String, ByVal strKeyHex As String, ByVal strIvHex As String, ByVal nOptions As Long) As Long`

`hContext = CIPHER_InitHex(fEncrypt, strAlgAndMode, strKeyHex, strIvHex, nOptions)`

### C/C++ Syntax

`long __stdcall CIPHER_InitHex(int fEncrypt, const char *szAlgAndMode, const char *szKeyHex, const char *szIvHex, long nOptions);`

### Parameters

*fEncrypt*
:   [in] Direction flag: set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szAlgAndMode*
:   [in] String specifying the block cipher algorithm and mode, e.g. `"aes128/cbc"`
(see [Specifying the algorithm and mode for generic block cipher functions](#cipheralgmode)).

*szKeyHex*
:   [in] Hex-encoded key of exact length for block cipher algorithm.

*szIvHex*
:   [in] Hex-encoded Initialization Vector (IV) of exactly the block size, or `""` for ECB mode.

*nOptions*
:   [in] Option flags: zero (0) for default options.

### Returns (VBA/C)

Non-zero handle of the CIPHER context, or *zero* if an error occurs.

### .NET Equivalent

[Cipher.InitEncrypt Method](#M_Cipher_InitEncrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode)  

[Cipher.InitDecrypt Method](#M_Cipher_InitDecrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode)  

### Remarks

This function is the equivalent of [`CIPHER_Init`](#CIPHER_Init) except it passes the key and IV parameters as hexadecimal-encoded strings.

### Example

See [`CIPHER_UpdateHex`](#CIPHER_UpdateHex).

### See Also

[`CIPHER_Init`](#CIPHER_Init)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_KeyUnwrap"></a>CIPHER_KeyUnwrap
---------------------------------------------

Unwraps (decrypts) a content-encryption key with a key-encryption key.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_KeyUnwrap Lib "diCryptoSys.dll" 
(ByRef lpOutput As Byte, ByVal nOutBytes As Long, 
ByRef lpData As Byte, ByVal nDataLen As Long, 
ByRef lpKek As Byte, ByVal nKekLen As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_KeyUnwrap(lpOutput(0), nOutBytes, abInput(0), nDataLen, 
abKek(0), nKekLen, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_KeyUnwrap(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpData, long nDataLen, const unsigned char *lpKEK, long nKekLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*nOutBytes*
:   [in] specifying the maximum length of the output array.

*lpData*
:   [in] array containing the input data (wrapped key).

*nDataLen*
:   [in] specifying the length of the input data in bytes.

*lpKEK*
:   [in] array containing the key encryption key.

*nKekLen*
:   [in] specifying the length of the key encryption key.

*nOptions*
:   [in] option flags:  

Select the key wrap algorithm from one of the following:  

`API_BC_AES128` to use `AES128-Wrap`  

`API_BC_AES192` to use `AES192-Wrap`  

`API_BC_AES256` to use `AES256-Wrap`  

`API_BC_3DES` to use `cms3DESWrap`

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherKeyUnwrap](#VB_cipherKeyUnwrap)(lpData() As Byte, lpKek() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Cipher.KeyUnwrap Method](#M_Cipher_KeyUnwrap)  

### Python Equivalent

`static [Cipher.key_unwrap](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.key_unwrap "External link")(data, kek, alg)`

### Remarks

This unwraps (decrypts) key material using a key encryption key (KEK) and uses either the AES Key Wrap Algorithm
from RFC 3394 [[AES-WRAP](#AES-WRAP)] or the 
Triple-DES Key Wrap algorithm from RFC 3217 [[WRAP-3DES](#WRAP-3DES)].
There is no default algorithm. The algorithm must be specified in the *nOptions* parameter.
To find the required length for the output key material, pass zero as the *nOutBytes* parameter.
This will be 8 bytes less than the input length for AES and 16 bytes less for triple DES.
No parity bit checks or changes are made for a Triple-DES key.

### Example (VBA core function)

```

Dim abWK() As Byte
Dim abKeyData() As Byte
Dim abKek() As Byte
Dim nWkLen As Long
Dim nKdLen As Long
Dim nKekLen As Long

abWK = cnvBytesFromHexStr("503D75C73630A7B02ECF51B9B29B907749310B77B0B2E054")
abKek = cnvBytesFromHexStr("c17a44e8 e28d7d64 81d1ddd5 0a3b8914")
nWkLen = UBound(abWK) + 1
nKekLen = UBound(abKek) + 1
Debug.Print "INPUT:"
Debug.Print "KEK=" & cnvHexStrFromBytes(abKek)
Debug.Print "WK =" & cnvHexStrFromBytes(abWK)
Debug.Print "ALG=AES-128"
   
nKdLen = CIPHER_KeyUnwrap(0, 0, abWK(0), nWkLen, abKek(0), nKekLen, API_BC_AES128)
If nKdLen <= 0 Then
    Debug.Print "CIPHER_KeyUnwrap returns " & nKdLen & ": " & apiErrorLookup(nKdLen)
    Exit Sub
End If
ReDim abKeyData(nKdLen - 1)
nKdLen = CIPHER_KeyUnwrap(abKeyData(0), nKdLen, abWK(0), nWkLen, abKek(0), nKekLen, API_BC_AES128)
Debug.Print "OUTPUT:"
Debug.Print "KD =" & cnvHexStrFromBytes(abKeyData)
Debug.Print "OK =00112233445566778899AABBCCDDEEFF"

```

This should result in output as follows:

```

INPUT:
KEK=C17A44E8E28D7D6481D1DDD50A3B8914
WK =503D75C73630A7B02ECF51B9B29B907749310B77B0B2E054
ALG=AES-128
OUTPUT:
KD =00112233445566778899AABBCCDDEEFF
OK =00112233445566778899AABBCCDDEEFF

```

### Example (VBA wrapper function)

See example for VBA wrapper `cipherKeyWrap` in [`CIPHER_KeyWrap`](#CIPHER_KeyWrap).

### See Also

[`CIPHER_KeyWrap`](#CIPHER_KeyWrap)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_KeyWrap"></a>CIPHER_KeyWrap
-----------------------------------------

Wraps a content-encryption key with a key-encryption key.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_KeyWrap Lib "diCryptoSys.dll" 
(ByRef lpOutput As Byte, ByVal nOutBytes As Long, 
ByRef lpData As Byte, ByVal nDataLen As Long, 
ByRef lpKek As Byte, ByVal nKekLen As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_KeyWrap(lpOutput(0), nOutBytes, abInput(0), nDataLen, 
abKek(0), nKekLen, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_KeyWrap(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpData, long nDataLen, const unsigned char *lpKEK, long nKekLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*nOutBytes*
:   [in] specifying the maximum length of the output array.

*lpData*
:   [in] array containing the input data (key material).

*nDataLen*
:   [in] specifying the length of the input data in bytes.

*lpKEK*
:   [in] array containing the key encryption key.

*nKekLen*
:   [in] specifying the length of the key encryption key.

*nOptions*
:   [in] option flags:  

Select the key wrap algorithm from one of the following:  

`API_BC_AES128` to use `AES128-Wrap`  

`API_BC_AES192` to use `AES192-Wrap`  

`API_BC_AES256` to use `AES256-Wrap`  

`API_BC_3DES` to use `cms3DESWrap`

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherKeyWrap](#VB_cipherKeyWrap)(lpData() As Byte, lpKek() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Cipher.KeyWrap Method](#M_Cipher_KeyWrap)  

### Python Equivalent

`static [Cipher.key_wrap](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.key_wrap "External link")(data, kek, alg)`

### Remarks

This wraps (encrypts) key material using a key encryption key (KEK) and uses either the AES Key Wrap Algorithm
from RFC 3394 [[AES-WRAP](#AES-WRAP)] or the 
Triple-DES Key Wrap algorithm from RFC 3217 [[WRAP-3DES](#WRAP-3DES)].
There is no default algorithm. The algorithm must be specified in the *nOptions* parameter.
The input data to be wrapped must be a valid length for the underlying data encapsulation mechanism; 
specifically, at least 16 bytes and a multiple of 8 bytes for AES, or exactly 24 bytes for Triple DES.
To find the required length for the output wrapped key, pass zero as the *nOutBytes* parameter
(*Hint:* an AES-wrapped key is exactly 8 bytes longer than the input; a triple-DES-wrapped key is 16 bytes longer).
No parity bit checks or changes are made for a Triple-DES key.

### Example (VBA core function)

```

Dim abWK() As Byte
Dim abKeyData() As Byte
Dim abKek() As Byte
Dim nWkLen As Long
Dim nKdLen As Long
Dim nKekLen As Long

abKeyData = cnvBytesFromHexStr("00112233 44556677 8899aabb ccddeeff")
abKek = cnvBytesFromHexStr("c17a44e8 e28d7d64 81d1ddd5 0a3b8914")
nKdLen = UBound(abKeyData) + 1
nKekLen = UBound(abKek) + 1

Debug.Print "INPUT:"
Debug.Print "KEK=" & cnvHexStrFromBytes(abKek)
Debug.Print "KD =" & cnvHexStrFromBytes(abKeyData)
Debug.Print "OUTPUT:"

nWkLen = CIPHER_KeyWrap(0, 0, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_AES128)
If nWkLen <= 0 Then
    Debug.Print "CIPHER_KeyWrap returns " & nWkLen & ": " & apiErrorLookup(nWkLen)
    Exit Sub
End If
ReDim abWK(nWkLen - 1)
nWkLen = CIPHER_KeyWrap(abWK(0), nWkLen, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_AES128)
Debug.Print "WK{AES-128}=" & cnvHexStrFromBytes(abWK)

abKeyData = cnvBytesFromHexStr("8cbedec4 8d063e1b a46be8e3 69a9c398 d8e30ee5 42bc347c 4f30e928 ddd7db49")
abKek = cnvBytesFromHexStr("9e84ee99 e6a84b50 c76cd414 a2d2ec05 8af41bfe 4bf3715b f894c8da 1cd445f6")
nKdLen = UBound(abKeyData) + 1
nKekLen = UBound(abKek) + 1

nWkLen = CIPHER_KeyWrap(0, 0, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_AES256)
If nWkLen <= 0 Then
    Debug.Print "CIPHER_KeyWrap returns " & nWkLen & ": " & apiErrorLookup(nWkLen)
    Exit Sub
End If
ReDim abWK(nWkLen - 1)
nWkLen = CIPHER_KeyWrap(abWK(0), nWkLen, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_AES256)
Debug.Print "WK{AES-256}=" & cnvHexStrFromBytes(abWK)

abKeyData = cnvBytesFromHexStr("84e7f2d8 78f89fcc cd2d5eba fc56daf7 3300f27e f771cd68")
abKek = cnvBytesFromHexStr("8ad8274e 56f46773 8edd83d4 394e5e29 af7c4089 e4f8d9f4")
nKdLen = UBound(abKeyData) + 1
nKekLen = UBound(abKek) + 1

Debug.Print "INPUT:"
Debug.Print "KEK=" & cnvHexStrFromBytes(abKek)
Debug.Print "KD =" & cnvHexStrFromBytes(abKeyData)
Debug.Print "OUTPUT:"

nWkLen = CIPHER_KeyWrap(0, 0, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_3DES)
If nWkLen <= 0 Then
    Debug.Print "CIPHER_KeyWrap returns " & nWkLen & ": " & apiErrorLookup(nWkLen)
    Exit Sub
End If
ReDim abWK(nWkLen - 1)
nWkLen = CIPHER_KeyWrap(abWK(0), nWkLen, abKeyData(0), nKdLen, abKek(0), nKekLen, API_BC_3DES)
Debug.Print "WK(3DES}=" & cnvHexStrFromBytes(abWK)

' Now unwrap (decrypt)...
Debug.Print "Unwrap..."
Debug.Print "INPUT:"
Debug.Print "ALG=3DES"
Debug.Print "KEK=" & cnvHexStrFromBytes(abKek)
Debug.Print "WK =" & cnvHexStrFromBytes(abWK)
' In this case, we know that the Triple DES key will be exactly 24 bytes long, so
nKdLen = API_KEYSIZE_TDEA_BYTES
ReDim abKeyData(nKdLen - 1)
nKdLen = CIPHER_KeyUnwrap(abKeyData(0), nKdLen, abWK(0), nWkLen, abKek(0), nKekLen, API_BC_3DES)
If nKdLen <= 0 Then
    Debug.Print "CIPHER_KeyUnwrap returns " & nKdLen & ": " & apiErrorLookup(nKdLen)
    Exit Sub
End If
Debug.Print "OUTPUT:"
Debug.Print "KD =" & cnvHexStrFromBytes(abKeyData)
Debug.Print "OK =84E7F2D878F89FCCCD2D5EBAFC56DAF73300F27EF771CD68"

```

This should result in output as follows:

```

INPUT:
KEK=C17A44E8E28D7D6481D1DDD50A3B8914
KD =00112233445566778899AABBCCDDEEFF
OUTPUT:
WK{AES-128}=503D75C73630A7B02ECF51B9B29B907749310B77B0B2E054
WK{AES-256}=EAFB901F82B98D37F17497063DE3E5EC7246AB57200AE73EDDDDF24AA403DAFA0C5AE151D1746FA4
INPUT:
KEK=8AD8274E56F467738EDD83D4394E5E29AF7C4089E4F8D9F4
KD =84E7F2D878F89FCCCD2D5EBAFC56DAF73300F27EF771CD68
OUTPUT:
WK{3DES}=97BC2665A5E90185F8772B1EC4EDAB94879521CDFF896823E08ACBC26F620917D7071140C9D5C024
Unwrap...
INPUT:
ALG=3DES
KEK=8AD8274E56F467738EDD83D4394E5E29AF7C4089E4F8D9F4
WK =97BC2665A5E90185F8772B1EC4EDAB94879521CDFF896823E08ACBC26F620917D7071140C9D5C024
OUTPUT:
KD =84E7F2D878F89FCCCD2D5EBAFC56DAF73300F27EF771CD68
OK =84E7F2D878F89FCCCD2D5EBAFC56DAF73300F27EF771CD68

```

Note that the AES key wrap will always give the same result for the same input data, 
but the Triple DES result will be different each time.

### Example (VBA wrapper function)

```

Dim lpKeyData() As Byte
Dim lpKek() As Byte
Dim lpWK() As Byte
Dim lpKD() As Byte

' Input for AES128-Wrap
lpKeyData = cnvBytesFromHexStr("8cbedec4 8d063e1b a46be8e3 69a9c398 d8e30ee5 42bc347c 4f30e928 ddd7db49")
lpKek = cnvBytesFromHexStr("9e84ee99 e6a84b50 c76cd414 a2d2ec05 8af41bfe 4bf3715b f894c8da 1cd445f6")
' Wrap the content encyption key
lpWK = cipherKeyWrap(lpKeyData, lpKek, API_BC_AES256)
Debug.Print "WK=" & cnvHexStrFromBytes(lpWK)
Debug.Print "OK=EAFB901F82B98D37F17497063DE3E5EC7246AB57200AE73EDDDDF24AA403DAFA0C5AE151D1746FA4"
' Unwrap
lpKD = cipherKeyUnwrap(lpWK, lpKek, API_BC_AES256)
Debug.Print "KD=" & cnvHexStrFromBytes(lpKD)
Debug.Print "OK=" & cnvHexStrFromBytes(lpKeyData)
```

### See Also

[`CIPHER_KeyUnwrap`](#CIPHER_KeyUnwrap)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamBytes"></a>CIPHER_StreamBytes
-------------------------------------------------

Enciphers data in array of bytes using specified stream cipher.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamBytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal nCounter As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_StreamBytes(lpOutput(0), abData(0), nDataLen, abKey(0), nKeyLen, abIV(0), nIvLen, nCounter, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamBytes(unsigned char *lpOutput, unsigned char *lpData, long nDataLen, unsigned char *lpKey, long nKeyLen, unsigned char *lpIV, long nIvLen, long nCounter, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output (at least as long as the input).

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] specifying the length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] specifying the length of the key in bytes.

*lpIV*
:   [in] array containing the initialization vector (IV, nonce), if required.

*nIvLen*
:   [in] specifying the length of the IV in bytes.

*nCounter*
:   [in] the value of the counter (ChaCha20 only).

*nOptions*
:   [in] option flags:  

Select one of the following:  

`API_SC_ARCFOUR` to use ARCFOUR (RC4)  

`API_SC_SALSA20` to use Salsa20  

`API_SC_CHACHA20` to use ChaCha20

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherStreamBytes](#VB_cipherStreamBytes)(lpInput() As Byte, lpKey() As Byte, lpIV() As Byte, nOptions As Long, Optional nCounter As Long = 0) As Byte()`

### .NET Equivalent

[CipherStream.Bytes Method](#M_CipherStream_Bytes)  

### C++ (STL) Equivalent

`static crsysapi::bvec_t [crsysapi::CipherStream::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher_stream.html#a540163cc4bebfb5e73994d54f37931a2 "External link") (const bvec_t &data, const bvec_t &key, const bvec_t &iv, Alg alg, int counter=0)`

### Python Equivalent

`static [CipherStream.bytes](https://cryptosys.net/pydocapi/class-stubs/CipherStream.html#crsysapi.CipherStream.bytes "External link")(data, key, iv, alg, counter=0)`

### Remarks

This performs a one-off encryption over a byte array using the specified stream cipher.
The key and IV are passed as byte arrays. 
The output will be exactly the same length as the input. 
The output buffer *lpOutput* may be the same as the input *lpInput*.

* **Arcfour:** any length key; specify `null` for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long.
Counter is ignored if IV is 16 bytes.
* See [Stream Ciphers](#streamcipher) for more details

### Example (VBA core function)

```

Dim abKey() As Byte
Dim abInput() As Byte
Dim lpOutput() As Byte
Dim nRet As Long
Dim nDataLen As Long
Dim nKeyLen As Long
Dim strCorrect As String

' Arcfour test vector
abKey = cnvBytesFromHexStr("0123456789abcdef")
abInput = cnvBytesFromHexStr("0123456789abcdef")
strCorrect = "75b7878099e0c596"

ReDim lpOutput(UBound(abInput))
nDataLen = UBound(abInput) + 1
nKeyLen = UBound(abKey) + 1

Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
Debug.Print "PT=" & cnvHexStrFromBytes(abInput)
' Encipher using Arcfour
nRet = CIPHER_StreamBytes(lpOutput(0), abInput(0), nDataLen, abKey(0), nKeyLen, ByVal 0&, 0, 0, API_SC_ARCFOUR)
Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput)
Debug.Print "OK=" & strCorrect

' Now decipher just by calling again. Use same output as input.
nRet = CIPHER_StreamBytes(lpOutput(0), lpOutput(0), nDataLen, abKey(0), nKeyLen, ByVal 0&, 0, 0, API_SC_ARCFOUR)
Debug.Print "P'=" & cnvHexStrFromBytes(lpOutput)

```

This should result in output as follows:

```

KY=0123456789ABCDEF
PT=0123456789ABCDEF
CT=75B7878099E0C596
OK=75b7878099e0c596
P'=0123456789ABCDEF

```

```

' ChaCha20 test vector from "ChaCha20 and Poly1305 for IETF protocols"
Dim abKey() As Byte
Dim abInput() As Byte
Dim lpOutput() As Byte
Dim abIV() As Byte
Dim nRet As Long
Dim nDataLen As Long
Dim nKeyLen As Long
Dim nIvLen As Long
Dim strCorrect As String
Dim strData As String

' Obtain parameters in byte array format
abKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
abIV = cnvBytesFromHexStr("000000000000004a00000000")
strData = _
"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."
abInput = StrConv(strData, vbFromUnicode)
strCorrect = _
"6E2E359A2568F98041BA0728DD0D6981E97E7AEC1D4360C20A27AFCCFD9FAE0BF91B65C5524733AB8F593DABCD62B3571639D624E65152AB8F530C359F0861D807CA0DBF500D6A6156A38E088A22B65E52BC514D16CCF806818CE91AB77937365AF90BBF74A35BE6B40B8EEDF2785E42874D"

ReDim lpOutput(UBound(abInput))
nDataLen = UBound(abInput) + 1
nKeyLen = UBound(abKey) + 1
nIvLen = UBound(abIV) + 1

Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
Debug.Print "IV=" & cnvHexStrFromBytes(abIV)
Debug.Print "PT=" & cnvHexStrFromBytes(abInput)
' Encipher using ChaCha20 with counter=1
nRet = CIPHER_StreamBytes(lpOutput(0), abInput(0), nDataLen, abKey(0), nKeyLen, abIV(0), nIvLen, 1, API_SC_CHACHA20)
Debug.Print "CIPHER_StreamBytes returns " & nRet & " (expecting 0)"
Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput)
Debug.Print "OK=" & strCorrect

' Now decipher just by calling again. Use same output as input.
nRet = CIPHER_StreamBytes(lpOutput(0), lpOutput(0), nDataLen, abKey(0), nKeyLen, abIV(0), nIvLen, 1, API_SC_CHACHA20)
Debug.Print "P'=" & cnvHexStrFromBytes(lpOutput)
Debug.Print "P'=" & StrConv(lpOutput, vbUnicode)

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
IV=000000000000004A00000000
PT=4C616469657320616E642047656E746C656D656E206F662074686520636C617373206F66202739393A204966204920636F756C64206F6666657220796F75206F6E6C79206F6E652074697020666F7220746865206675747572652C2073756E73637265656E20776F756C642062652069742E
CIPHER_StreamBytes returns 0 (expecting 0)
CT=6E2E359A2568F98041BA0728DD0D6981E97E7AEC1D4360C20A27AFCCFD9FAE0BF91B65C5524733AB8F593DABCD62B3571639D624E65152AB8F530C359F0861D807CA0DBF500D6A6156A38E088A22B65E52BC514D16CCF806818CE91AB77937365AF90BBF74A35BE6B40B8EEDF2785E42874D
OK=6E2E359A2568F98041BA0728DD0D6981E97E7AEC1D4360C20A27AFCCFD9FAE0BF91B65C5524733AB8F593DABCD62B3571639D624E65152AB8F530C359F0861D807CA0DBF500D6A6156A38E088A22B65E52BC514D16CCF806818CE91AB77937365AF90BBF74A35BE6B40B8EEDF2785E42874D
P'=4C616469657320616E642047656E746C656D656E206F662074686520636C617373206F66202739393A204966204920636F756C64206F6666657220796F75206F6E6C79206F6E652074697020666F7220746865206675747572652C2073756E73637265656E20776F756C642062652069742E
P'=Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.

```

### Example (VBA wrapper function)

```

Dim lpCipher() As Byte
Dim lpPlain() As Byte
Dim lpKey() As Byte
Dim lpIV() As Byte
Dim strData As String
lpKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
lpIV = cnvBytesFromHexStr("000000000000004a00000000")
strData = _
"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."
lpPlain = StrConv(strData, vbFromUnicode)   ' Encode as bytes

' Encipher using ChaCha20 with counter=1
lpCipher = cipherStreamBytes(lpPlain, lpKey, lpIV, API_SC_CHACHA20, 1)
Debug.Print "CT=" & cnvHexStrFromBytes(lpCipher)
Debug.Print "OK=6E2E359A2568F98041BA0728DD0D6981E97E7AEC1D4360C20A27AFCCFD9FAE0BF91B65C5524733AB8F593DABCD62B3571639D624E65152AB8F" _
	& "530C359F0861D807CA0DBF500D6A6156A38E088A22B65E52BC514D16CCF806818CE91AB77937365AF90BBF74A35BE6B40B8EEDF2785E42874D"
' Now decipher just by calling again. ...
lpPlain = cipherStreamBytes(lpCipher, lpKey, lpIV, API_SC_CHACHA20, 1)
Debug.Print "PT=" & StrConv(lpPlain, vbUnicode) ' Decode bytes to string

' Arcfour test vector
lpKey = cnvBytesFromHexStr("0123456789abcdef")
lpPlain = cnvBytesFromHexStr("0123456789abcdef")
lpIV = vbNullString     ' Empty (null) array
' Encipher using Arcfour
lpCipher = cipherStreamBytes(lpPlain, lpKey, lpIV, API_SC_ARCFOUR)
Debug.Print "CT=" & cnvHexStrFromBytes(lpCipher)
Debug.Print "OK=75b7878099e0c596"

```

### See Also

[`CIPHER_StreamHex`](#CIPHER_StreamHex)
[`CIPHER_StreamInit`](#CIPHER_StreamInit)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamFile"></a>CIPHER_StreamFile
-----------------------------------------------

Enciphers data in a file using specified stream cipher.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamFile Lib "diCryptoSys.dll" (ByVal strFileOut As String, ByVal strFileIn As String, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal nCounter As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_StreamFile(strFileOut, strFileIn, abKey(0), nKeyLen, abIV(0), nIvLen, nCounter, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamFile(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long nKeyLen, unsigned char *lpIV, long nIvLen, long nCounter, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output file to be created.

*szFileIn*
:   [in] with the full path name of the input file to be processed.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] specifying the length of the key in bytes.

*lpIV*
:   [in] array containing the initialization vector (IV, nonce), if required.

*nIvLen*
:   [in] specifying the length of the IV in bytes.

*nCounter*
:   [in] the value of the counter (ChaCha20 only).

*nOptions*
:   [in] option flags:  

Select one of the following:  

`API_SC_ARCFOUR` to use ARCFOUR (RC4)  

`API_SC_SALSA20` to use Salsa20  

`API_SC_CHACHA20` to use ChaCha20

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[CipherStream.File Method](#M_CipherStream_File)  

### C++ (STL) Equivalent

`static int [crsysapi::CipherStream::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher_stream.html#abf1c89b187d94adf62478fc23787acd4 "External link") (const std::string &fileOut, const std::string &fileIn, const bvec_t &key, const bvec_t &iv, Alg alg, int counter=0)`

### Python Equivalent

`static [CipherStream.file](https://cryptosys.net/pydocapi/class-stubs/CipherStream.html#crsysapi.CipherStream.file "External link")(fileout, filein, key, iv, alg, counter=0)`

### Remarks

This performs a one-off encryption of a file using the specified stream cipher.
The key and IV are passed as byte arrays.
The output file will be exactly the same length as the input. 
The output file **must not** be the same as the input file.

* **Arcfour:** any length key; specify `null` for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long.
Counter is ignored if IV is 16 bytes.
* See [Stream Ciphers](#streamcipher) for more details

### Example

```

Dim nRet As Long
Dim strFileIn As String
Dim strFileOut As String
Dim abKey() As Byte
Dim abInput() As Byte
Dim abIV() As Byte
Dim nKeyLen As Long
Dim nIvLen As Long
Dim nCounter As Long

' Obtain parameters in byte array format
abKey = cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
abIV = cnvBytesFromHexStr("000000000000004a00000000")
nCounter = 1
nKeyLen = UBound(abKey) + 1
nIvLen = UBound(abIV) + 1
Debug.Print "Key: " & cnvHexStrFromBytes(abKey)
Debug.Print "IV:  " & cnvHexStrFromBytes(abIV)
Debug.Print "Counter: " & nCounter

' Encipher plaintext file
strFileIn = "sunscreen.txt"
strFileOut = "sunscreen-chacha.dat"
nRet = CIPHER_StreamFile(strFileOut, strFileIn, abKey(0), nKeyLen, abIV(0), nIvLen, nCounter, API_SC_CHACHA20)
Debug.Print "CIPHER_StreamFile returns " & nRet & " (expecting 0)"

```

### See Also

[`CIPHER_StreamBytes`](#CIPHER_StreamBytes)
[`CIPHER_StreamInit`](#CIPHER_StreamInit)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamFinal"></a>CIPHER_StreamFinal
-------------------------------------------------

Closes the CIPHERSTREAM context and destroys the key.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamFinal Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = CIPHER_StreamFinal(hContext)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamFinal(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the CIPHERSTREAM context.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[CipherStream.Dispose Method](#M_CipherStream_Dispose)  

### Remarks

### Example

See the example in [`CIPHER_StreamInit`](#CIPHER_StreamInit).

### See Also

[`CIPHER_StreamInit`](#CIPHER_StreamInit)
[`CIPHER_StreamUpdate`](#CIPHER_StreamUpdate)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamHex"></a>CIPHER_StreamHex
---------------------------------------------

Enciphers data in a hex-encoded string using specified stream cipher.

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamHex Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nOutChars As Long, ByVal strInputHex As String, ByVal strKeyHex As String, ByVal strIvHex As String, ByVal nCounter As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_StreamHex(strOutput, nOutChars, strInputHex, strKeyHex, strIvHex, nCounter, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamHex(char *szOutput, long nOutChars, const char *szInputHex, const char *szKeyHex, const char *szIvHex, long nCounter, long nOptions);`

### Parameters

*szOutput*
:   [out] string of sufficient length to receive the output (at least as long as the input).

*nOutChars*
:   [in] specifying the length of the output buffer in bytes.

*szInputHex*
:   [in] string containing the hex-encoded input data.

*szKeyHex*
:   [in] string containing the hex-encoded key.

*szIvHex*
:   [in] string containing the hex-encoded initialization vector (IV, nonce). Specify `""` for Arcfour.

*nCounter*
:   [in] the value of the counter (ChaCha20 only).

*nOptions*
:   [in] option flags:  

Select one of the following:  

`API_SC_ARCFOUR` to use ARCFOUR (RC4)  

`API_SC_SALSA20` to use Salsa20  

`API_SC_CHACHA20` to use ChaCha20

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherStreamHex](#VB_cipherStreamHex)(lpInput() As Byte, lpKey() As Byte, lpIV() As Byte, nOptions As Long, Optional nCounter As Long = 0) As String`

### .NET Equivalent

[CipherStream.Hex Method](#M_CipherStream_Hex)  

### Remarks

This performs a one-off encryption of data in a hex-encoded string using the specified stream cipher. 
The key and IV are passed as hex-encoded strings.
The output will be exactly the same length as the input. 
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

* **Arcfour:** any length key; specify `""` for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long.
Counter is ignored if IV is 16 bytes.
* See [Stream Ciphers](#streamcipher) for more details

### Example (VBA core function)

```

' Ref: eSTREAM `verified.test-vectors.txt` Set 3, vector#  0:
Dim nRet As Long
Dim strKey As String
Dim strIV As String
Dim strInput As String
Dim strOutput As String
Dim strCorrect As String
Dim strCheck As String

' Parameters are hex-encoded strings
strKey = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"
strIV = "0000000000000000"
' Key stream is generated by encrypting 32 zero bytes (=64 hex chars)
strInput = "0000000000000000000000000000000000000000000000000000000000000000"
strCorrect = "B580F7671C76E5F7441AF87C146D6B513910DC8B4146EF1B3211CF12AF4A4B49"
Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
' Encipher using Salsa20 in hex mode
strOutput = String(Len(strInput), " ")
nRet = CIPHER_StreamHex(strOutput, Len(strOutput), strInput, strKey, strIV, 0, API_SC_SALSA20)
Debug.Print "CT=" & strOutput
Debug.Print "OK=" & strCorrect

```

This should result in output as follows:

```

KY=000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
IV=0000000000000000
PT=0000000000000000000000000000000000000000000000000000000000000000
CT=B580F7671C76E5F7441AF87C146D6B513910DC8B4146EF1B3211CF12AF4A4B49
OK=B580F7671C76E5F7441AF87C146D6B513910DC8B4146EF1B3211CF12AF4A4B49

```

### Example (VBA wrapper function)

```

Dim strCipher As String
Dim strPlain As String
strCipher = cipherStreamHex("0000000000000000000000000000000000000000000000000000000000000000", _
    "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", _
    "0000000000000000", API_SC_SALSA20)
Debug.Print "CT=" & strCipher
Debug.Print "OK=B580F7671C76E5F7441AF87C146D6B513910DC8B4146EF1B3211CF12AF4A4B49"
' Decrypt by calling again...
strPlain = cipherStreamHex(strCipher, _
    "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", _
    "0000000000000000", API_SC_SALSA20)
Debug.Print "PT=" & strPlain

strCipher = cipherStreamHex("00000000000000000000", _
    "ef012345", "", API_SC_ARCFOUR)
Debug.Print "CT=" & strCipher
Debug.Print "OK=d6a141a7ec3c38dfbd61"
' Decrypt by calling again...
strPlain = cipherStreamHex(strCipher, _
    "ef012345", "", API_SC_ARCFOUR)
Debug.Print "PT=" & strPlain
```

### See Also

[`CIPHER_StreamBytes`](#CIPHER_StreamBytes)
[`CIPHER_StreamInit`](#CIPHER_StreamInit)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamInit"></a>CIPHER_StreamInit
-----------------------------------------------

Initializes the CIPHERSTREAM context ready for repeated operations of CIPHER_StreamUpdate()

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamInit Lib "diCryptoSys.dll" (ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByVal nCounter As Long, ByVal nOptions As Long) As Long`

`nRet = CIPHER_StreamInit(abKey(0), nKeyLen, abIV(0), nIvLen, nCounter, nOptions)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamInit(const unsigned char *lpKey, long nKeyLen, unsigned char *lpIV, long nIvLen, long nCounter, long nOptions);`

### Parameters

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] specifying the length of the key in bytes.

*lpIV*
:   [in] array containing the initialization vector (IV, nonce), if required.

*nIvLen*
:   [in] specifying the length of the IV in bytes.

*nCounter*
:   [in] the value of the counter (ChaCha20 only).

*nOptions*
:   [in] option flags:  

Select one of the following:  

`API_SC_ARCFOUR` to use ARCFOUR (RC4)  

`API_SC_SALSA20` to use Salsa20  

`API_SC_CHACHA20` to use ChaCha20

### Returns (VBA/C)

If successful, the return value is a **non-zero** handle to the new CIPHERSTREAM context.
Returns *zero* if an error occurs.

### .NET Equivalent

[CipherStream.Init Method](#M_CipherStream_Init)  

### Remarks

It is important to check for a zero context handle and stop if one occurs.
Use [`API_ErrorCode`](#API_ErrorCode) to find the [error code](#errorcodes) of the error
that occured.

* **Arcfour:** any length key; specify `null` for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long.
Counter is ignored if IV is 16 bytes.
* See [Stream Ciphers](#streamcipher) for more details

### Example

```

' Ref: `draft-strombergson-chacha-test-vectors-02.txt` TC7: Sequence patterns in key and IV. Rounds: 20
Dim nRet As Long
Dim strFileIn As String
Dim strFileOut As String
Dim abKey() As Byte
Dim abIV() As Byte
Dim abInput() As Byte
Dim lpOutput() As Byte
Dim nKeyLen As Long
Dim nIvLen As Long
Dim strCorrect As String
Dim nDataLen As Long
Dim hContext As Long

' Use incremental functions to encrypt a 65-byte input of zeros in chunks of 1, 62 and 2 bytes
Debug.Print "CHACHA20 (INCREMENTAL):"
strCorrect = "9fadf409c00811d00431d67efbd88fba59218d5d6708b1d685863fabbb0e961eea480fd6fb532bfd494b2151015057423ab60a63fe4f55f7a212e2167ccab931fb"
' Obtain parameters in byte array format
abKey = cnvBytesFromHexStr("00112233445566778899aabbccddeeffffeeddccbbaa99887766554433221100")
abIV = cnvBytesFromHexStr("0f1e2d3c4b5a6978")
nKeyLen = UBound(abKey) + 1
nIvLen = UBound(abIV) + 1
Debug.Print "Key: " & cnvHexStrFromBytes(abKey)
Debug.Print "IV:  " & cnvHexStrFromBytes(abIV)

' Initialize CIPHERSTREAM context
hContext = CIPHER_StreamInit(abKey(0), nKeyLen, abIV(0), nIvLen, 0, API_SC_CHACHA20)
If (hContext = 0) Then
    Debug.Print "ERROR: " + API_ErrorCode()
    Exit Function
End If

' Part 1: block of 1 byte
nDataLen = 1
ReDim abInput(nDataLen - 1)   ' Set to zero by default
ReDim lpOutput(UBound(abInput))
nRet = CIPHER_StreamUpdate(hContext, lpOutput(0), abInput(0), nDataLen)
Debug.Print cnvHexStrFromBytes(lpOutput)

' Part 2: block of 62 bytes
nDataLen = 62
ReDim abInput(nDataLen - 1)
ReDim lpOutput(UBound(abInput))
nRet = CIPHER_StreamUpdate(hContext, lpOutput(0), abInput(0), nDataLen)
Debug.Print cnvHexStrFromBytes(lpOutput)

' Part 3: block of 2 bytes
nDataLen = 2
ReDim abInput(nDataLen - 1)
ReDim lpOutput(UBound(abInput))
nRet = CIPHER_StreamUpdate(hContext, lpOutput(0), abInput(0), nDataLen)
Debug.Print cnvHexStrFromBytes(lpOutput)

Debug.Print "CORRECT="
Debug.Print strCorrect

' We are done with context
nRet = CIPHER_StreamFinal(hContext)
Debug.Print "CIPHER_StreamFinal retrurns " & nRet & " (expecting 0)"

```

This should result in output as follows:

```

CHACHA20 (INCREMENTAL):
Key: 00112233445566778899AABBCCDDEEFFFFEEDDCCBBAA99887766554433221100
IV:  0F1E2D3C4B5A6978
9F
ADF409C00811D00431D67EFBD88FBA59218D5D6708B1D685863FABBB0E961EEA480FD6FB532BFD494B2151015057423AB60A63FE4F55F7A212E2167CCAB9
31FB
CORRECT=
9fadf409c00811d00431d67efbd88fba59218d5d6708b1d685863fabbb0e961eea480fd6fb532bfd494b2151015057423ab60a63fe4f55f7a212e2167ccab931fb
CIPHER_StreamFinal retrurns 0 (expecting 0)

```

### See Also

[`CIPHER_StreamUpdate`](#CIPHER_StreamUpdate)
[`CIPHER_StreamFinal`](#CIPHER_StreamFinal)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_StreamUpdate"></a>CIPHER_StreamUpdate
---------------------------------------------------

Encrypts input using current CIPHERSTREAM context 

### VBA/VB6 Syntax

`Public Declare Function CIPHER_StreamUpdate Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = CIPHER_StreamUpdate(hContext, lpOutput(0), abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  CIPHER_StreamUpdate(long hContext, unsigned char *lpOutput, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] containing the handle to the CIPHERSTREAM context.

*lpOutput*
:   [out] array of sufficient length to receive the output (at least as long as the input).

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] specifying the length of the input data in bytes.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonnegative [error code](#errorcodes).

### .NET Equivalent

[CipherStream.Update Method](#M_CipherStream_Update)  

### Remarks

Only one CIPERSTREAM context can be active at one time in any thread.

### Example

See the example in [`CIPHER_StreamInit`](#CIPHER_StreamInit).

### See Also

[`CIPHER_StreamInit`](#CIPHER_StreamInit)
[`CIPHER_StreamFinal`](#CIPHER_StreamFinal)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_Update"></a>CIPHER_Update
---------------------------------------

Encrypts or decrypts a chunk of input (in incremental mode).  

### VBA/VB6 Syntax

`Public Declare Function CIPHER_Update Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = CIPHER_Update(hContext, lpOutput(0), nOutBytes, lpData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall CIPHER_Update(long hContext, unsigned char *lpOutput, long nOutBytes, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] Handle to the CIPHER context.

*lpOutput*
:   [out] Byte array to receive output.

*nOutBytes*
:   [in] Length of output array in bytes.

*lpData*
:   [in] Input data to be processed.

*nDataLen*
:   [in] Length of input data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherUpdate](#VB_cipherUpdate)(hContext As Long, lpData() As Byte) As Byte()`

### .NET Equivalent

[Cipher.Update Method](#M_Cipher_Update_Byte) (Byte[])  

### C++ (STL) Equivalent

`crsysapi::bvec_t [crsysapi::Cipher::Update](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#ab583533e39762d886d59fb9a9c21d5b8 "External link") (const bvec_t &data)`

### Remarks

The handle *hContext* to the CIPHER context must have been set up with a
prior call to [`CIPHER_Init`](#CIPHER_Init) or [`CIPHER_InitHex`](#CIPHER_InitHex). 

The chunks of data to be en/decrypted must be passed to the Update function in sequential order and only in lengths which are multiples of the block size (16 bytes for AES, 8 for Triple DES).
For ECB and CBC modes, the last block in the sequence must be suitably padded to a length a multiple of the block size. 
For other modes, e.g. CTR, the last block in the sequence may be shorter than a multiple of the block length.
However, once this final, shorter block has been processed, the Update function can no longer be used (well it can, but the output is wrong).

### Example (VBA core function)

```

' Using the "raw" functions
Dim key() As Byte
Dim iv() As Byte
Dim pt() As Byte
Dim ct() As Byte
Dim ok() As Byte
Dim ptlen As Long
Dim ctlen As Long
Dim keylen As Long
Dim ivlen As Long
Dim algstr As String
Dim hContext As Long
Dim nRet As Long

key = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
iv = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
keylen = cnvBytesLen(key)
ivlen = cnvBytesLen(iv)
Debug.Print "KY=" & cnvHexStrFromBytes(key)
Debug.Print "IV=" & cnvHexStrFromBytes(iv)

' TEST 1 - CBC mode
algstr = "Aes128/CBC"
Debug.Print algstr
' Initialize context for repeated chunks
hContext = CIPHER_Init(ENCRYPT, algstr, key(0), keylen, iv(0), ivlen, 0)
Debug.Print "CIPHER_Init returns 0x" & Hex(hContext) & " (expected NON-zero)"
Debug.Assert hContext <> 0

' Pass data in chunks of 16 bytes (or multiples of)
' Part 1...
pt = StrConv("Now is the time for all good men", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ptlen = cnvBytesLen(pt)
ctlen = ptlen
ReDim ct(ctlen - 1)
nRet = CIPHER_Update(hContext, ct(0), ctlen, pt(0), ptlen)
Debug.Print "CIPHER_Update returns " & nRet & " (expected 0)"
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' Part 2...
pt = StrConv(" to come to the aid of the party", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ptlen = cnvBytesLen(pt)
ctlen = ptlen
ReDim ct(ctlen - 1)
nRet = CIPHER_Update(hContext, ct(0), ctlen, pt(0), ptlen)
Debug.Print "CIPHER_Update returns " & nRet & " (expected 0)"
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' We are done
nRet = CIPHER_Final(hContext)
Debug.Print "CIPHER_Final returns " & nRet & " (expected 0)"

```

### Example (VBA wrapper function)

```

' Using the wrapper functions
Dim key() As Byte
Dim iv() As Byte
Dim pt() As Byte
Dim ct() As Byte
Dim algstr As String
Dim hContext As Long
Dim nRet As Long

key = cnvBytesFromHexStr("0123456789ABCDEFF0E1D2C3B4A59687")
iv = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210")
Debug.Print "KY=" & cnvHexStrFromBytes(key)
Debug.Print "IV=" & cnvHexStrFromBytes(iv)

' TEST 1 - CBC mode
algstr = "Aes128/CBC"
Debug.Print algstr
' Initialize context for repeated chunks
hContext = cipherInit(ENCRYPT, algstr, key, iv)
Debug.Print "cipherInit returns 0x" & Hex(hContext) & " (expected NON-zero)"
Debug.Assert hContext <> 0

' Pass data in chunks of 16 bytes (or multiples of)
' Part 1...
pt = StrConv("Now is the time for all good men", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' Part 2...
pt = StrConv(" to come to the aid of the party", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' We are done
nRet = cipherFinal(hContext)
Debug.Print "cipherFinal returns " & nRet & " (expected 0)"

' TEST 2 - ECB mode
algstr = "Aes128/ecb"
Debug.Print algstr
Dim dummy() As Byte
' Initialize context for repeated chunks
hContext = cipherInit(ENCRYPT, algstr, key, dummy)
Debug.Print "cipherInit returns 0x" & Hex(hContext) & " (expected NON-zero)"
Debug.Assert hContext <> 0

' Pass data in chunks of 16 bytes (or multiples of)
' Part 1...
pt = StrConv("Now is the time for all good men", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' Part 2...
pt = StrConv(" to come to the aid of the party", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' We are done
nRet = cipherFinal(hContext)
Debug.Assert nRet = 0

' TEST 3 - CTR mode
algstr = "Aes128/ctr"
Debug.Print algstr
' Initialize context for repeated chunks
hContext = cipherInit(ENCRYPT, algstr, key, iv)
Debug.Print "cipherInit returns 0x" & Hex(hContext) & " (expected NON-zero)"
Debug.Assert hContext <> 0

' Pass data in chunks of 16 bytes (or multiples of)
' Part 1...
pt = StrConv("Now is the time for all good men", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' Part 2...
' In CTR mode (and OFB and CFB) the last block need not be a multiple
pt = StrConv(" to come to the aid of", vbFromUnicode)
Debug.Print "PT=" & cnvHexStrFromBytes(pt)
ct = cipherUpdate(hContext, pt)
Debug.Print "CT=" & cnvHexStrFromBytes(ct)

' We are done
nRet = cipherFinal(hContext)
Debug.Assert nRet = 0

```

```

KY=0123456789ABCDEFF0E1D2C3B4A59687
IV=FEDCBA9876543210FEDCBA9876543210
Aes128/CBC
cipherInit returns 0x2AB4B01D (expected NON-zero)
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=C3153108A8DD340C0BCB1DFE8D25D2320EE0E66BD2BB4A313FB75C5638E9E177
PT=20746F20636F6D6520746F2074686520616964206F6620746865207061727479
CT=211FC26A1FF51CE35741B76A77DB6DE21EE94708B546919999A4557F43AAA2BB
cipherFinal returns 0 (expected 0)
Aes128/ecb
cipherInit returns 0x243820F9 (expected NON-zero)
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=F0D1AD6F901FFFAE5572A6928DAB52B064B25C79F876730321E36DC01011ACCE
PT=20746F20636F6D6520746F2074686520616964206F6620746865207061727479
CT=02D6F240643271217758C44862BB1B6862CD10757387256BC678A1708483862A
Aes128/ctr
cipherInit returns 0x5FFB439 (expected NON-zero)
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
CT=3FAC68CBAE6D774151306E9DB16CE0191C51E91959DA4F082B7CE3498C2D20D7
PT=20746F20636F6D6520746F2074686520616964206F66
CT=8437EC92088FE4C19FB49BDF2BADF7C7FD6FB9A7D52A

```

### See Also

[`CIPHER_Init`](#CIPHER_Init)
[`CIPHER_Final`](#CIPHER_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CIPHER_UpdateHex"></a>CIPHER_UpdateHex
---------------------------------------------

Encrypts or decrypts a chunk of hexadecimal-encoded input (in incremental mode).  

### VBA/VB6 Syntax

`Public Declare Function CIPHER_UpdateHex Lib "diCryptoSys.dll" (ByVal hContext As Long, ByVal strOutput As String, ByVal nOutChars As Long, ByVal strDataHex As String) As Long`

`nRet = CIPHER_UpdateHex(hContext, strOutput, Len(strOutput), strDataHex)`

### C/C++ Syntax

`long __stdcall CIPHER_UpdateHex(long hContext, char *szOutput, long nOutChars, const char *szDataHex);`

### Parameters

*hContext*
:   [in] Handle to the CIPHER context.

*szOutput*
:   [out] String buffer to receive output.

*nOutChars*
:   [in] Length of output buffer in bytes.

*szDataHex*
:   [in] Hex-encoded input data to be processed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cipherUpdateHex](#VB_cipherUpdateHex)(hContext As Long, szInputHex As String) As String`

### .NET Equivalent

[Cipher.Update Method](#M_Cipher_Update_String) (String)  

### Remarks

This function is the equivalent of [`CIPHER_Update`](#CIPHER_Update) except the input and output are hexadecimal-encoded strings.
The functions `CIPHER_Update` and `CIPHER_UpdateHex` 
(and their wrappers `cipherUpdate` and `cipherUpdateHex`)
may be used interchangeably.
For more information, see the remarks section in [`CIPHER_Update`](#CIPHER_Update).

### Example (VBA core function)

```

Dim nRet As Long
Dim hContext As Long
Dim sBlock As String
Dim strHexKey As String
Dim strIV As String
Dim sNext As String
Dim sLast As String
Dim sCorrect As String
Dim j As Integer

' cbc_e_m.txt
' KEYSIZE=128 I=2
' KEY=93286764A85146730E641888DB34EB47
' IV=192D9B3AA10BB2F7846CCBA0085C657A
' PT=983BF6F5A6DFBCDAA19370666E83A99A
' CT=40D8DAF6D1FDA0A073B3BD18B7695D2E

strHexKey = "93286764A85146730E641888DB34EB47"
strIV = "192D9B3AA10BB2F7846CCBA0085C657A"
sBlock = "983BF6F5A6DFBCDAA19370666E83A99A"
sCorrect = "40D8DAF6D1FDA0A073B3BD18B7695D2E"

Debug.Print "AES Monte Carlo CBC Mode Encrypt:"
Debug.Print "KY=" & strHexKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & sBlock

hContext = CIPHER_InitHex(ENCRYPT, "aes128/cbc", strHexKey, strIV, 0)
If hContext = 0 Then
    MsgBox "Failed to set context", vbCritical
    Exit Sub
End If
' Do 10,000 times
sNext = sBlock
For j = 0 To 9999
    sBlock = String(Len(sNext), " ")
    nRet = CIPHER_UpdateHex(hContext, sBlock, Len(sBlock), sNext)
    If j = 0 Then
        sNext = strIV
    Else
        sNext = sLast
    End If
    sLast = sBlock
Next
Debug.Print "CT=" & sBlock
Debug.Print "OK=" & sCorrect
nRet = CIPHER_Final(hContext)

Debug.Assert (sCorrect = sBlock)

```

### Example (VBA wrapper function)

```

' Using the wrapper functions
Dim keyhex As String
Dim ivhex  As String
Dim pthex As String
Dim cthex As String
Dim algstr As String
Dim hContext As Long
Dim nRet As Long

keyhex = "0123456789ABCDEFF0E1D2C3B4A59687"
ivhex = "FEDCBA9876543210FEDCBA9876543210"
Debug.Print "KY=" & keyhex
Debug.Print "IV=" & ivhex

' TEST 4 - Decrypt in CTR mode
algstr = "Aes128/ctr"
Debug.Print algstr
Debug.Print "DECRYPTING..."
' Initialize context for repeated chunks
hContext = cipherInitHex(DECRYPT, algstr, keyhex, ivhex, 0)
Debug.Assert hContext <> 0

' Pass data in chunks of 16 bytes (or multiples of)
' Part 1...
cthex = "3FAC68CBAE6D774151306E9DB16CE0191C51E91959DA4F082B7CE3498C2D20D7"
Debug.Print "CT=" & cthex
' NB switched pt <=> ct
pthex = cipherUpdateHex(hContext, cthex)
Debug.Print "PT=" & pthex
Debug.Print "'" & cnvStringFromHexStr(pthex) & "'"
' Part 2...
cthex = "8437EC92088FE4C19FB49BDF2BADF7C7FD6FB9A7D52A"
Debug.Print "CT=" & cthex
pthex = cipherUpdateHex(hContext, cthex)
Debug.Print "PT=" & pthex
Debug.Print "'" & cnvStringFromHexStr(pthex) & "'"

' We are done
nRet = cipherFinal(hContext)
Debug.Assert nRet = 0

```

```

Aes128/ctr
DECRYPTING...
CT=3FAC68CBAE6D774151306E9DB16CE0191C51E91959DA4F082B7CE3498C2D20D7
PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E
'Now is the time for all good men'
CT=8437EC92088FE4C19FB49BDF2BADF7C7FD6FB9A7D52A
PT=20746F20636F6D6520746F2074686520616964206F66
' to come to the aid of'

```

### See Also

[`CIPHER_Update`](#CIPHER_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_B64Filter"></a>CNV_B64Filter
---------------------------------------

Removes non-base64 characters from a string.

### VBA/VB6 Syntax

`Public Declare Function CNV_B64Filter Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal strInput As String, ByVal nStrLen As Long) As Long`

`nRet = CNV_B64Filter(strOutput, strInput, nStrLen)`

### C/C++ Syntax

`long __stdcall  CNV_B64Filter(char *szOutput, const char *szInput, long nInStrLen);`

### Parameters

*szOutput*
:   [out] to receive filtered characters.

*szInput*
:   [in] to be filtered.

*nInStrLen*
:   [in] specifying the length of the input string.

### Returns (VBA/C)

If successful, the return value is the number of characters in the filtered string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvB64Filter](#VB_cnvB64Filter)(szB64 As String) As String`

### .NET Equivalent

[Cnv.Base64Filter Method](#M_Cnv_Base64Filter)  

### Remarks

For the "raw" function, specify a zero *nOutChars* or a null string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example

### See Also

[`CNV_B64StrFromBytes`](#CNV_B64StrFromBytes)
[`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_B64StrFromBytes"></a>CNV_B64StrFromBytes
---------------------------------------------------

Encodes an array of bytes into a base64-encoded string.

### VBA/VB6 Syntax

`Public Declare Function CNV_B64StrFromBytes Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, 
    ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = CNV_B64StrFromBytes(strOutput, nMaxChars, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  CNV_B64StrFromBytes(char *szOutput, long nMaxChars, const unsigned char *lpInput, long nBytes);`

### Parameters

*szOutput*
:   [out] to receive encoded data.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*lpInput*
:   [in] array of binary data to be encoded.

*nBytes*
:   [in] number of bytes to be encoded.

### Returns (VBA/C)

If successful, the return value is the number of characters in the encoded string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvB64StrFromBytes](#VB_cnvB64StrFromBytes)(lpData() As Byte) As String`

### .NET Equivalent

[Cnv.ToBase64 Method](#M_Cnv_ToBase64_Byte) (Byte[])  

or use the in-built method `System.Convert.ToBase64String` (less forgiving).

### C++ (STL) Equivalent

`static std::string [crsysapi::Cnv::ToBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a7e16727e2e36e4fb9132d3a13ee00b03 "External link") (const bvec_t &bv)  

static std::string [crsysapi::Cnv::ToBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#aea585209477576a176a2200c95e40601 "External link") (const std::string &s)`

### Python Equivalent

`static [Cnv.tobase64](https://cryptosys.net/pydocapi/class-stubs/Cnv.html#crsysapi.Cnv.tobase64 "External link")(data)`

### Remarks

For the "raw" function, specify a zero *nOutChars* or a null string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example

```

Dim strBase64 As String
Dim abData() As Byte
Dim i As Integer
strBase64 = "/ty6mHZUMhA="
' Convert base64 string to bytes
abData = cnvBytesFromB64Str(strBase64)
For i = LBound(abData) To UBound(abData)
   Debug.Print Hex(abData(i));
Next
Debug.Print
strBase64 = ""
' Convert back to a base64 string
strBase64 = cnvB64StrFromBytes(abData)
Debug.Print strBase64

```

Producing the output:

```

FEDCBA9876543210
/ty6mHZUMhA=

```

### See Also

[`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str)
[`CNV_B64Filter`](#CNV_B64Filter)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_BytesFromB64Str"></a>CNV_BytesFromB64Str
---------------------------------------------------

Decodes a base64-encoded string into an array of Bytes.

### VBA/VB6 Syntax

`Public Declare Function CNV_BytesFromB64Str Lib "diCryptoSys.dll" 
    (ByRef lpData As Byte, ByVal nDataLen As Long, ByVal strInput As String) As Long`

`nLen = CNV_BytesFromB64Str(abData(0), nDataLen, strInput)`

### C/C++ Syntax

`long __stdcall  CNV_BytesFromB64Str(unsigned char *lpOutput, long nOutputLen, const char *szInput);`

### Parameters

*lpOutput*
:   [out] array suitably dimensioned to receive output.

*nOutputLen*
:   [in] specifying the length of the byte array.

*szInput*
:   [in] of base64 data to be decoded.

### Returns (VBA/C)

If successful, the return value is the number of bytes in the decoded array; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvBytesFromB64Str](#VB_cnvBytesFromB64Str)(szB64 As String) As Byte()`

### .NET Equivalent

[Cnv.FromBase64 Method](#M_Cnv_FromBase64) 

Or use the in-built method `System.Convert.FromBase64String` (less forgiving).

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Cnv::FromBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a91d63843b7242278db2c5154dd64861d "External link") (const std::string &s)`

### Python Equivalent

`static [Cnv.frombase64](https://cryptosys.net/pydocapi/class-stubs/Cnv.html#crsysapi.Cnv.frombase64 "External link")(s)`

### Remarks

This uses the base64 encoding scheme from [[RFC4648](#RFC4648)].
Pass a zero value for *nOutBytes* to find the required maximum possible number of bytes in the output array.
The final array may be shorter. 

**@warning** [*Changed in v5.2*] This function now returns an error if it finds an illegal character in the input string
	(previously any non-base64 character was just ignored).
	Whitespace characters (space, TAB, LF, CR, VT, FF) are still allowed and ignored 
	but any other non-base64 characters will cause an error.

### Example

```

Dim strBase64 As String
Dim abData() As Byte
Dim i As Integer
strBase64 = "/ty6mHZUMhA="
' Convert base64 string to bytes
abData = cnvBytesFromB64Str(strBase64)
For i = LBound(abData) To UBound(abData)
    Debug.Print Hex(abData(i));
Next
Debug.Print

```

### See Also

[`CNV_B64StrFromBytes`](#CNV_B64StrFromBytes)
[`CNV_B64Filter`](#CNV_B64Filter)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_BytesFromHexStr"></a>CNV_BytesFromHexStr
---------------------------------------------------

Decodes a hexadecimal-encoded string into an array of Bytes.

### VBA/VB6 Syntax

`Public Declare Function CNV_BytesFromHexStr Lib "diCryptoSys.dll" 
    (ByRef lpData As Byte, ByVal nDataLen As Long, ByVal strInput As String) As Long`

`nRet = CNV_BytesFromHexStr(abData(0), nDataLen, strInput)`

### C/C++ Syntax

`long __stdcall  CNV_BytesFromHexStr(unsigned char *lpOutput, long nOutputLen, const char *szInput);`

### Parameters

*lpOutput*
:   [out] array suitably dimensioned to receive output.

*nOutputLen*
:   [in] specifying the length of the byte array.

*szInput*
:   [in] of hexadecimal data to be decoded.

### Returns (VBA/C)

If successful, the return value is the number of bytes in the decoded array; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvBytesFromHexStr](#VB_cnvBytesFromHexStr)(szHex As String) As Byte()`

### .NET Equivalent

[Cnv.FromHex Method](#M_Cnv_FromHex)  

### COM/ASP Equivalent

`conv.BytesFromHex  

Public Function BytesFromHex(ByVal strHex As String) As Variant`

See [`conv.BytesFromHex`](#x_conv_bytesfromhex).

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Cnv::FromHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#ad46a5b3546d7ee7fd4596dfdad91fc17 "External link") (const std::string &s)`

### Python Equivalent

`static [Cnv.fromhex](https://cryptosys.net/pydocapi/class-stubs/Cnv.html#crsysapi.Cnv.fromhex "External link")(s)`

### Remarks

Call the function with a zero *nOutBytes* or NULL *lpOutput* array to find the required length.

**@warning** [*Changed in v5.2*] This function now returns an error if it finds an illegal character in the input string
	(previously any non-hex character was just ignored).
	Whitespace characters and ASCII punctuation characters are still allowed and ignored (so `"DE:AD:BE:EF"` is OK)
	but obviously non-hex characters like those in the range `[G-Zg-z]` will cause an error.

### Example

```

Dim strHex As String
Dim abData() As Byte
Dim i As Integer
strHex = "FEDCAB9876543210"
' Convert hex string to bytes
abData = cnvBytesFromHexStr(strHex)
Debug.Print "{";
For i = LBound(abData) To UBound(abData)
    Debug.Print Hex(abData(i)) & ", ";
Next
Debug.Print "}"
strHex = ""
' Convert back to a hex string
strHex = cnvHexStrFromBytes(abData)
Debug.Print strHex

```

Output:

```

{FE, DC, AB, 98, 76, 54, 32, 10, }
FEDCAB9876543210

```

### See Also

[`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes)
[`CNV_HexFilter`](#CNV_HexFilter)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_HexFilter"></a>CNV_HexFilter
---------------------------------------

Removes non-hexadecimal characters from a string.

### VBA/VB6 Syntax

`Public Declare Function CNV_HexFilter Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal strInput As String, ByVal nStrLen As Long) As Long`

`nRet = CNV_HexFilter(strOutput, strInput, nStrLen)`

### C/C++ Syntax

`long __stdcall  CNV_HexFilter(char *szOutput, const char *szInput, long nInStrLen);`

### Parameters

*szOutput*
:   [out] to receive filtered characters.

*szInput*
:   [in] to be filtered.

*nInStrLen*
:   [in] specifying the length of the input string.

### Returns (VBA/C)

If successful, the return value is the number of characters in the filtered string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvHexFilter](#VB_cnvHexFilter)(szHex As String) As String`

### .NET Equivalent

[Cnv.HexFilter Method](#M_Cnv_HexFilter)  

### Remarks

For the "raw" function, specify a zero *nOutChars* or a null string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example

### See Also

[`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes)
[`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_HexStrFromBytes"></a>CNV_HexStrFromBytes
---------------------------------------------------

Encodes an array of bytes into a hexadecimal-encoded string.

### VBA/VB6 Syntax

`Public Declare Function CNV_HexStrFromBytes Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, ByRef lpData As Byte, ByVal nBytes As Long) As Long`

`nRet = CNV_HexStrFromBytes(strOutput, nMaxChars, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  CNV_HexStrFromBytes(char *szOutput, long nMaxChars, const unsigned char *lpInput, long nBytes);`

### Parameters

*szOutput*
:   [out] to receive encoded data.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*lpInput*
:   [in] array of binary data to be encoded.

*nBytes*
:   [in] number of bytes to be encoded.

### Returns (VBA/C)

If successful, the return value is the number of characters in the encoded string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [cnvHexStrFromBytes](#VB_cnvHexStrFromBytes)(lpData() As Byte) As String`

### .NET Equivalent

[Cnv.ToHex Method](#M_Cnv_ToHex_Byte) (Byte[])  

### COM/ASP Equivalent

`conv.HexFromBytes  

Public Function HexFromBytes(ByVal abData As Variant) As String`

See [`conv.HexFromBytes`](#x_conv_hexfrombytes).

### C++ (STL) Equivalent

`static std::string [crsysapi::Cnv::ToHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a45776fd3a075f9d035c323c22cdd237c "External link") (const bvec_t &bv)  

static std::string [crsysapi::Cnv::ToHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a33d0f961ec85ecce19e8f3948460def4 "External link") (const std::string &s)`

### Python Equivalent

`static [Cnv.tohex](https://cryptosys.net/pydocapi/class-stubs/Cnv.html#crsysapi.Cnv.tohex "External link")(data)`

### Remarks

For the "raw" function, specify a zero *nOutChars* or a null string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example

### See Also

[`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr)
[`CNV_HexFilter`](#CNV_HexFilter)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CNV_ShortPathName"></a>CNV_ShortPathName
-----------------------------------------------

Retrieve the Windows short path form of the specified path.

### VBA/VB6 Syntax

Not available in VBA/VB6 (no useful equivalent).

### C/C++ Syntax

`long __stdcall CNV_ShortPathName(char *szOut, long nOutChars, const wchar_t* szwFilePath);`

### Parameters

*szOut*
:   [out] Buffer to receive output.

*nOutChars*
:   [in] Maximum length of output string in bytes (excluding the terminating null).

*szwFilePath*
:   [in] Path name in wide characters.

### Returns (VBA/C)

Number of characters (bytes) in or required for the output string; 
otherwise it returns a negative [error code](#errorcodes).

### .NET Equivalent

[Cnv.ShortPathName Method](#M_Cnv_ShortPathName)  

### C++ (STL) Equivalent

`static std::string [crsysapi::Cnv::ShortPathName](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a5d9ddd076ab0a313c968322364974a22 "External link") (const std::wstring &filePath)`

### Python Equivalent

`static [Cnv.shortpathname](https://cryptosys.net/pydocapi/class-stubs/Cnv.html#crsysapi.Cnv.shortpathname "External link")(pathName)`

### Remarks

Use this function to find the ASCII equivalent file path for a path represented in "Unicode" UTF-16 `wchar_t` characters.
Then use this ASCII short name as an argument for an input file in any of the functions in this library that require a file name.

The file must exist. The output path is guaranteed to be in ASCII characters, and the base name and each folder name will be 8 characters or fewer. 
It may not give the same value on a different system. Windows only.

For the "raw" function, pass a NULL *szOut* or zero *nOutChars* to find the required output length in bytes. 
ANSI C users [must add one to this value](#cusersaddone) when allocating memory.

### Example

```

#include <wchar.h>
long nchars;
wchar_t *wfname;
char *shortname;
// Path name with Chinese characters
wfname = L"你好.txt";
// Find required output length
nchars = CNV_ShortPathName(NULL, 0, wfname);
printf("CNV_ShortPathName returns %ld\n", nchars);
assert(nchars >= 0);
shortname = malloc(nchars + 1);
nchars = CNV_ShortPathName(shortname, nchars, wfname);
assert(nchars >= 0);
// Output should be in ASCII
printf("ShortPath='%s'\n", shortname);
// ShortPath='FC0F~1.TXT'
free(shortname);

```

```

#include <string>
// Path name with Chinese characters
std::wstring wfname = L"你好.txt";
std::string shortname = crsysapi::Cnv::ShortPathName(wfname);
cout << "ShortPath='" << shortname << "'" << endl;

```

```

ShortPath='FC0F~1.TXT'

```

Note that the short path name may be different on your system.

### See Also

[[Contents](#topofpage)] [[Index](#index)]

<a id="COMPR_Compress"></a>COMPR_Compress
-----------------------------------------

Compress data using compression algorithm.

### VBA/VB6 Syntax

`Public Declare Function COMPR_Compress Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByVal nOptions As Long) As Long`

`nRet = COMPR_Compress(lpOutput(0), nOutputLen, lpInput(0), nInputLen, nOptions)`

### C/C++ Syntax

`long __stdcall COMPR_Compress(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive output data.

*nOutBytes*
:   [in] size of the output buffer in bytes.

*lpInput*
:   [in] input data to be compressed.

*nInputLen*
:   [in] length of input array in bytes.

*nOptions*
:   [in] option flags. Select one of:  

`API_COMPR_ZLIB` (0) to use the zlib algorithm (default)  

`API_COMPR_ZSTD` to use the Zstandard algorithm

### Returns (VBA/C)

The number of bytes successfully copied into the output buffer or the required size in bytes. 
If an error occurs, it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [comprCompress](#VB_comprCompress)(lpInput() As Byte, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Compr.Compress Method](#M_Compr_Compress)  

### Python Equivalent

`static [Compr.compress](https://cryptosys.net/pydocapi/class-stubs/Compr.html#crsysapi.Compr.compress "External link")(data, alg=Alg.ZLIB)`

### Remarks

To determine the required size of the output buffer, call the function with *nOutBytes* set to zero (or *lpOutput* set to NULL).

**VB6/VBA users:** Note the '(0)' in lpOutput(0) and abInput(0).

### Example (VBA core function)

```

Dim strPlain As String
Dim strBack As String
Dim abPlain() As Byte
Dim abCompressed() As Byte
Dim nCompLen As Long
Dim nUncompLen As Long
Dim nRet As Long

' COMPRESSSION (deflation)

' Set the plaintext message
strPlain = "hello, hello, hello. This is a 'hello world' message " & _
    "for the world, repeat, for the world."
' Convert to an array of bytes
abPlain = StrConv(strPlain, vbFromUnicode)
nUncompLen = UBound(abPlain) + 1
' Find required compressed length by calling with zero length value
nCompLen = COMPR_Compress(0, 0, abPlain(0), nUncompLen, 0)
ReDim abCompressed(nCompLen - 1)
' Now compress plaintext
Call COMPR_Compress(abCompressed(0), nCompLen, abPlain(0), nUncompLen, 0)
Debug.Print "Compressed " & nUncompLen & " bytes to " & nCompLen

' DECOMPRESSSION (inflation)

' Uncompress the compressed data
' Find the required length of uncompressed data
nUncompLen = COMPR_Uncompress(0, 0, abCompressed(0), nCompLen, 0)
Debug.Print "Required uncompressed length is " & nUncompLen & " bytes"
ReDim abPlain(nUncompLen - 1)
nRet = COMPR_Uncompress(abPlain(0), nUncompLen, abCompressed(0), nCompLen, 0)

' Convert back to a string
strBack = StrConv(abPlain, vbUnicode)
Debug.Print strBack

```

```

Compressed 90 bytes to 68
Required uncompressed length is 90 bytes
hello, hello, hello. This is a 'hello world' message for the world, repeat, for the world.

```

### Example (VBA wrapper function)

```

Dim strPlain As String
Dim lpToCompress() As Byte
Dim lpCompressed() As Byte
Dim lpUncompressed() As Byte
strPlain = "hello, hello, hello. This is a 'hello world' message " & _
	"for the world, repeat, for the world."
lpToCompress = StrConv(strPlain, vbFromUnicode)

' Using default zlib algorithm
lpCompressed = comprCompress(lpToCompress)
Debug.Print "COMPRESSED(ZLIB)=" & cnvHexStrFromBytes(lpCompressed)
' 789CCB48CDC9C9D751C840A2F4144232328B15802851411D2CA2509E5F9493A2AE909B5A5C9C989EAA90965FA45092910A11D651284A2D484D2CD14115D6030086D11F4E
lpUncompressed = comprUncompress(lpCompressed)
Debug.Print "'" & StrConv(lpUncompressed, vbUnicode); "'"

' Using Zstandard algorithm
lpCompressed = comprCompress(lpToCompress, API_COMPR_ZSTD)
Debug.Print "COMPRESSED(ZSTD)=" & cnvHexStrFromBytes(lpCompressed)
' 28B52FFD205A1D0200540368656C6C6F2C202E20546869732069732061202720776F726C6427206D65737361676520666F72207468652C207265706561742C2E0400409E3AB1E1D97E71C508
lpUncompressed = comprUncompress(lpCompressed, API_COMPR_ZSTD)
Debug.Print "'" & StrConv(lpUncompressed, vbUnicode); "'"

```

Note that for this example with a short string, the zstd algorithm produces a longer result than zlib. 
However, in most cases, zstd produces shorter results.

### See Also

[`COMPR_Uncompress`](#COMPR_Uncompress)

[[Contents](#topofpage)] [[Index](#index)]

<a id="COMPR_Uncompress"></a>COMPR_Uncompress
---------------------------------------------

Uncompress data using compression algorithm.

### VBA/VB6 Syntax

`Public Declare Function COMPR_Uncompress Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByVal nOptions As Long) As Long`

`nRet = COMPR_Uncompress(lpOutput(0), nOutputLen, lpInput(0), nInputLen, nOptions)`

### C/C++ Syntax

`long __stdcall COMPR_Uncompress(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive output data.

*nOutBytes*
:   [in] size of the output buffer in bytes.

*lpInput*
:   [in] input data to be uncompressed.

*nInputLen*
:   [in] length of input array in bytes.

*nOptions*
:   [in] option flags. Select one of:  

`API_COMPR_ZLIB` (0) to use the zlib algorithm (default)  

`API_COMPR_ZSTD` to use the Zstandard algorithm

### Returns (VBA/C)

The number of bytes successfully copied into the output buffer or the required size in bytes. 
If an error occurs, it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [comprUncompress](#VB_comprUncompress)(lpInput() As Byte, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Compr.Uncompress Method](#M_Compr_Uncompress)  

### Python Equivalent

`static [Compr.uncompress](https://cryptosys.net/pydocapi/class-stubs/Compr.html#crsysapi.Compr.uncompress "External link")(data, alg=Alg.ZLIB)`

### Remarks

To determine the required size of the output buffer, call the function with *nOutBytes* set to zero (or *lpOutput* set to NULL).

**VB6/VBA users:** Note the '(0)' in lpOutput(0) and abInput(0).

### Example (VBA core function)

See [`COMPR_Compress`](#COMPR_Compress).

### Example (VBA wrapper function)

See [`COMPR_Compress`](#COMPR_Compress).

### See Also

[`COMPR_Compress`](#COMPR_Compress)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CRC_Bytes"></a>CRC_Bytes
-------------------------------

Computes the CRC-32 checksum of an array of bytes.

### VBA/VB6 Syntax

`Public Declare Function CRC_Bytes Lib "diCryptoSys.dll" 
    (ByRef lpInput As Byte, ByVal nBytes As Long, ByVal nOptions As Long) As Long`

`nRet = CRC_Bytes(abData(0), nBytes, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`int32_t __stdcall  CRC_Bytes(const unsigned char *lpInput, long nBytes, long nOptions);`

### Parameters

*lpInput*
:   [in] array of bytes containing input data.

*nBytes*
:   [in] specifying the number of bytes in the input.

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

The value of the CRC-32 checksum.

### .NET Equivalent

[Crc.Data Method](#M_Crc_Data_Byte) (Byte[])  

### C++ (STL) Equivalent

`static int [crsysapi::Crc::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#a435134cbae3789b8a7fe8177a1e0a955 "External link") (const bvec_t &data)`

### Python Equivalent

`static [Crc.bytes](https://cryptosys.net/pydocapi/class-stubs/Crc.html#crsysapi.Crc.bytes "External link")(data)`

### Remarks

The CRC-32 checksum is a 32-bit integer value.
The CRC-32 algorithm uses the polynomial `0x04C11DB7` and is the one specified in ISO 3309 and ITU-T V.42 and used by WinZip.

### Examples

```

Dim abData() As Byte
Dim nLen As Long
Dim nCRC As Long
Dim i As Long

nLen = 9
ReDim abData(nLen - 1)
' Create a 9-byte array equal to "123456789"
For i = 0 To nLen - 1
	abData(i) = i + Asc("1")
Next
nCRC = CRC_Bytes(abData(0), nLen, 0)
Debug.Print "CRC32=" & Hex(nCRC)

```

### See Also

[`CRC_String`](#CRC_String)
[`CRC_File`](#CRC_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CRC_File"></a>CRC_File
-----------------------------

Computes the CRC-32 checksum of a file.

### VBA/VB6 Syntax

`Public Declare Function CRC_File Lib "diCryptoSys.dll" 
    (ByVal strFileName As String, ByVal nOptions As Long) As Long`

`nRet = CRC_File(strFileName, nOptions)`

### C/C++ Syntax

`int32_t __stdcall  CRC_File(const char *szFileName, long nOptions);`

### Parameters

*szFileName*
:   [in] specifying the input file.

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

The value of the CRC-32 checksum.

### .NET Equivalent

[Crc.File Method](#M_Crc_File)  

### COM/ASP Equivalent

`crc32.FileHex  

Public Function FileHex(ByVal strFileName As String) As String`

See [`crc32.FileHex`](#x_crc32_filehex).

### C++ (STL) Equivalent

`static int [crsysapi::Crc::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#ad00b9be8e20180f9b248d147522d949b "External link") (const std::string &fileName)`

### Python Equivalent

`static [Crc.file](https://cryptosys.net/pydocapi/class-stubs/Crc.html#crsysapi.Crc.file "External link")(filename)`

### Remarks

The CRC-32 checksum is a 32-bit integer value.
The CRC-32 algorithm uses the polynomial `0x04C11DB7` and is the one specified in ISO 3309 and ITU-T V.42 and used by WinZip.

A return value of zero probably indicates that the file could not be found, or that the file is empty. 
The chances of a file with random contents giving a CRC checksum of zero is one in 4.5 billion, but it is not difficult to
construct a file with such a checksum.

### Example

```

Dim nCRC As Long
nCRC = CRC_File("hello.txt", 0)
Debug.Print "CRC32('hello.txt')=" & Hex(nCRC)

```

### See Also

[`CRC_Bytes`](#CRC_Bytes)
[`CRC_String`](#CRC_String)

[[Contents](#topofpage)] [[Index](#index)]

<a id="CRC_String"></a>CRC_String
---------------------------------

Computes the CRC-32 checksum of an ANSI string.

### VBA/VB6 Syntax

`Public Declare Function CRC_String Lib "diCryptoSys.dll" 
    (ByVal strInput As String, ByVal nOptions As Long) As Long`

`nRet = CRC_String(strData, nOptions)`

### C/C++ Syntax

`int32_t __stdcall  CRC_String(const char *szInput, long nOptions);`

### Parameters

*szInput*
:   [in] ANSI string input.

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

The value of the CRC-32 checksum.

### .NET Equivalent

[Crc.Data Method](#M_Crc_Data_String) (String)  

### COM/ASP Equivalent

`crc32.StringHex  

Public Function StringHex(ByVal strData As String) As String`

See [`crc32.StringHex`](#x_crc32_stringhex).

### C++ (STL) Equivalent

`static int [crsysapi::Crc::String](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#ad2360320a20354ea3f06f94f7caefc1e "External link") (const std::string &s)`

### Remarks

The CRC-32 checksum is a 32-bit integer value.
The CRC-32 algorithm uses the polynomial `0x04C11DB7` and is the one specified in ISO 3309 and ITU-T V.42 and used by WinZip.

### Examples

```

Dim strData As String
Dim nCRC As Long

strData = "123456789"
nCRC = CRC_String(strData, 0)
Debug.Print "CRC32(" & strData & ")=" & Hex(nCRC)

```

should output

```

CRC32(123456789)=CBF43926

```

### See Also

[`CRC_Bytes`](#CRC_Bytes)
[`CRC_File`](#CRC_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_B64Mode"></a>DES_B64Mode
-----------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function DES_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = DES_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  DES_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Encrypt Method](#M_Des_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Des.Decrypt Method](#M_Des_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (8 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 8 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* must also represent exactly 8 bytes, the required key length.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strIV As String
Dim sCorrect As String

' Key:        "0123456789abcdef"
' IV:         "1234567890abcdef"
' Plaintext:  "Now is the time for all "
'             "4e6f77206973207468652074696d6520666f7220616c6c20"
' Ciphertext: "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6"
strInput = "Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwg"
strKey = "ASNFZ4mrze8="
strIV = "EjRWeJCrze8="
sCorrect = "5cfN3ocr8nxD6TQAjDicD2g3iEmafAX2"

' Set strOutput to be same length as strInput
strOutput = String(Len(strInput), " ")

Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
' Encrypt in one-off process
nRet = DES_B64Mode(strOutput, strInput, strKey, True, "CBC", strIV)
Debug.Print "CT=" & strOutput
Debug.Print "OK=" & sCorrect

' Now decrypt back to plain text
strInput = strOutput
nRet = DES_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
Debug.Print "P'=" & strOutput

```

This should result in output as follows:

```

KY=ASNFZ4mrze8=
IV=EjRWeJCrze8=
PT=Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwg
CT=5cfN3ocr8nxD6TQAjDicD2g3iEmafAX2
OK=5cfN3ocr8nxD6TQAjDicD2g3iEmafAX2
P'=Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwg

```

### See Also

[`DES_HexMode`](#DES_HexMode)
[`DES_BytesMode`](#DES_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_Bytes"></a>DES_Bytes
-------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`DES_BytesMode`](#DES_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function DES_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean) As Long`

`nRet = DES_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  DES_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Encrypt Method](#M_Des_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Des.Decrypt Method](#M_Des_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* must be exactly 8 bytes long.
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

This example uses a test vector from [[FIPS 81](#FIPS81)].

```

    Dim nRet As Long
    Dim strInput As String
    Dim strKey As String
    Dim sCorrect As String
    Dim nKeyLen As Long
    Dim abKey() As Byte
    Dim lpOutput() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long
    
    ' Define test vectors in hex
    strKey = "0123456789abcdef"
    strInput = "4e6f77206973207468652074696d6520666f7220616c6c20"
    sCorrect = "3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53"
    
    ' Convert to byte arrays and compute lengths
    nKeyLen = Len(strKey) \ 2
    abKey = cnvBytesFromHexStr(strKey)
    nDataLen = Len(strInput) \ 2
    abData = cnvBytesFromHexStr(strInput)
    
    ' Dimension array for output
    ReDim lpOutput(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = DES_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), ENCRYPT)
    Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput), nRet
    Debug.Print "OK=" & sCorrect
    Debug.Assert (sCorrect = cnvHexStrFromBytes(lpOutput))
    
    ' Now decrypt back
    nRet = DES_Bytes(abData(0), lpOutput(0), nDataLen, abKey(0), DECRYPT)
    Debug.Print "P'=" & cnvHexStrFromBytes(abData), nRet
    Debug.Assert (strInput = cnvHexStrFromBytes(abData))

```

This should result in output as follows:

```

KY=0123456789ABCDEF
PT=4E6F77206973207468652074696D6520666F7220616C6C20
CT=3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53 0
OK=3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53
P'=4E6F77206973207468652074696D6520666F7220616C6C20 0

```

### See Also

[`DES_BytesMode`](#DES_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_BytesMode"></a>DES_BytesMode
---------------------------------------

Encrypts or decrypts an array of Bytes
in one step
using a specified mode.

### VBA/VB6 Syntax

`Public Declare Function DES_BytesMode Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = DES_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  DES_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the
initialization vector (IV), or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Encrypt Method](#M_Des_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Des.Decrypt Method](#M_Des_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* must be exactly 8 bytes long.
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim strHexIV As String
    Dim sCorrect As String
    Dim nDataLen As Long
    Dim abKey() As Byte
    Dim lpOutput() As Byte
    Dim abData() As Byte
    Dim abInitV() As Byte
    
    strKey = "0123456789abcdef"
    strHexIV = "1234567890abcdef"
    strInput = "Now is the time for all "
    sCorrect = "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6"
    
    ' Convert to byte arrays and compute lengths
    abKey = cnvBytesFromHexStr(strKey)
    abInitV = cnvBytesFromHexStr(strHexIV)
    abData = StrConv(strInput, vbFromUnicode)
    nDataLen = Len(strInput)
    
    ' Dimension array for output
    ReDim lpOutput(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    
    ' Encrypt in one-off process
    nRet = DES_BytesMode(lpOutput(0), abData(0), nDataLen, _
        abKey(0), True, "CBC", abInitV(0))
    Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput), nRet
    Debug.Print "OK=" & sCorrect
    Debug.Assert (sCorrect = cnvHexStrFromBytes(lpOutput))
    
    ' Now decrypt back
    nRet = DES_BytesMode(abData(0), lpOutput(0), nDataLen, _
        abKey(0), DECRYPT, "CBC", abInitV(0))
    strOutput = StrConv(abData(), vbUnicode)
    Debug.Print "P'=" & "[" & strOutput & "]"
    Debug.Assert (strOutput = strInput)

```

This should result in output as follows:

```

KY=0123456789ABCDEF
IV=1234567890ABCDEF
PT=4E6F77206973207468652074696D6520666F7220616C6C20
CT=E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6      0 
OK=e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6
P'=[Now is the time for all ]

```

### See Also

[`DES_Bytes`](#DES_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_CheckKey"></a>DES_CheckKey
-------------------------------------

Checks for weak or invalid-length DES or TDEA keys.

### VBA/VB6 Syntax

`Public Declare Function DES_CheckKey Lib "diCryptoSys.dll" 
    (ByRef lpKey As Byte, ByVal nKeyBytes As Long) As Long`

`nRet = DES_CheckKey(abKey(0), nKeyBytes)`

### C/C++ Syntax

`long __stdcall  DES_CheckKey(const unsigned char *lpKey, long nKeyLen);`

### Parameters

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] containing the length of the key in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.CheckKey Method (Byte[])](#M_Des_CheckKey_Byte)  

[Tdea.CheckKey Method (Byte[])](#M_Tdea_CheckKey_Byte)  

### Remarks

`DES_CheckKey` verifies that the key size is valid for a single, double or triple DES key -
i.e. is 8, 16 or 24 bytes long - and that no part of the key is a weak or semi-weak DES key.

### Example

```

    Dim abKey() As Byte
    Dim nKeyBytes As Long
    Dim nRet As Long
    
    nKeyBytes = 8
    ReDim abKey(nKeyBytes - 1)
    ' Generate a random DES key
    nRet = RNG_KeyBytes(abKey(0), nKeyBytes, "", 0)
    Debug.Print cnvHexStrFromBytes(abKey)
    ' Check if it's OK
    nRet = DES_CheckKey(abKey(0), nKeyBytes)
    Debug.Print "DES_CheckKey returns " & nRet & " (" & apiErrorLookup(nRet) & ")"
    If nRet <> 0 Then
        ' Error...
    End If

```

This should produce output similar to:

```

5305A0FA4CC94A82
DES_CheckKey returns 0 (OK, success, no error)

```

unless the key generated is weak (a 1 in 4500 billion chance!).

### See Also

[`DES_CheckKeyHex`](#DES_CheckKeyHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_CheckKeyHex"></a>DES_CheckKeyHex
-------------------------------------------

Checks for weak or invalid-length DES or TDEA keys in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function DES_CheckKeyHex Lib "diCryptoSys.dll" 
    (ByVal strHexKey As String) As Long`

`nRet = DES_CheckKeyHex(strHexKey)`

### C/C++ Syntax

`long __stdcall  DES_CheckKeyHex(const char *szHexKey);`

### Parameters

*szHexKey*
:   [in] containing the key in hexadecimal format.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.CheckKey Method (String)](#M_Des_CheckKey_String)  

[Tdea.CheckKey Method (String)](#M_Tdea_CheckKey_String)  

### Remarks

`DES_CheckKey` verifies that the key size is valid for a single, double or triple DES key -
i.e. is 8, 16 or 24 bytes long - and that no part of the key is a weak or semi-weak DES key.

### Example

```

    Dim nRet As Long
    Dim strKeyHex As String
    
    ' Weak key
    strKeyHex = "0101010101010101"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Valid key by one bit
    strKeyHex = "0101010101010102"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Another weak key
    strKeyHex = "01fe01fe01fe01fe"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Weak double key in 1st half
    strKeyHex = "01010101010101010001112223334455"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Weak triple key in 3rd part
    strKeyHex = "000111222333444555666777888999aa0101010101010101"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Valid key
    strKeyHex = "000111222333444555666777888999aaabbbcccdddeeefff"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

    ' Wrong key length (missing 'f' at end)
    strKeyHex = "000111222333444555666777888999aaabbbcccdddeeeff"
    nRet = DES_CheckKeyHex(strKeyHex)
    Debug.Print strKeyHex & " is " & IIf(nRet = 0, "OK", "BAD") & " (" & apiErrorLookup(nRet) & ")"

```

This should produce the output:

```

0101010101010101 is BAD (Weak key)
0101010101010102 is OK (OK, success, no error)
01fe01fe01fe01fe is BAD (Weak key)
01010101010101010001112223334455 is BAD (Weak key)
000111222333444555666777888999aa0101010101010101 is BAD (Weak key)
000111222333444555666777888999aaabbbcccdddeeefff is OK (OK, success, no error)
000111222333444555666777888999aaabbbcccdddeeeff is BAD (Invalid key length)

```

### See Also

[`DES_CheckKey`](#DES_CheckKey)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_File"></a>DES_File
-----------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function DES_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = DES_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  DES_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The key *lpKey* must be exactly 8 bytes long.
The initialization vector
byte array *lpInitV* must be exactly the block size of 8 bytes long,
except for ECB mode, where it is ignored (use `0`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

```

    Const MY_PATH As String = "C:\Test\"
    Dim abKey() As Byte
    Dim strFileOut As String, strFileIn As String, strFileChk As String
    Dim nRet As Long

    ' Construct full path names to files
    strFileIn = MY_PATH & "hello.txt"
    strFileOut = MY_PATH & "hello.des.enc.dat"
    strFileChk = MY_PATH & "hello.des.chk.txt"

    ' Create the key as an array of bytes
    ' This creates an array of 8 bytes {&HFE, &HDC, ... &H10}
    abKey = cnvBytesFromHexStr("fedcba9876543210")

    ' Encrypt plaintext file to cipher
    ' Output file = 16-byte ciphertext file hello.enc
    nRet = DES_File(strFileOut, strFileIn, abKey(0), ENCRYPT, "ECB", 0)
    Debug.Print nRet

    ' Now decrypt it
    nRet = DES_File(strFileChk, strFileOut, abKey(0), DECRYPT, "ECB", 0)
    Debug.Print nRet

```

### See Also

[`DES_FileExt`](#DES_FileExt)
[`DES_FileHex`](#DES_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_FileExt"></a>DES_FileExt
-----------------------------------

Encrypts or decrypts a file using a specified mode with extended options.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function DES_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = DES_FileExt(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  DES_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`DES_File`](#DES_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

For the default behaviour, see [`DES_File`](#DES_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

### Example

```

```

### See Also

[`DES_File`](#DES_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_FileHex"></a>DES_FileHex
-----------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function DES_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = DES_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  DES_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

Both the key string *szHexKey* and the initialization vector *szHexIV*
must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes),
unless *szMode* is `ECB`, 
in which case *szIV* is ignored (use `""`).

Valid hexadecimal characters are [0-9A-Fa-f].

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the key
`0xfedcba9876543210` and initialization vector
`0x0123456789abcdef`. The output file "bigfile.cbc" will be created or
overwritten. It then decrypts the ciphertext file as a check, creating or
overwriting the file "bigfile.chk".

```

    Dim nRet As Long

    nRet = DES_FileHex("bigfile.cbc", "bigfile.dat", _
        "fedcba9876543210", ENCRYPT, "CBC", "0123456789abcdef")
    Debug.Print nRet

    ' and decrypt it as a check
    nRet = DES_FileHex("bigfile.chk", "bigfile.cbc", _
        "fedcba9876543210fedcba9876543210", DECRYPT, "CBC", "0123456789abcdef")
    Debug.Print nRet

```

### See Also

[`DES_File`](#DES_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_Final"></a>DES_Final
-------------------------------

Closes and clears the DES context.

### VBA/VB6 Syntax

`Public Declare Function DES_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = DES_Final(hContext)`

### C/C++ Syntax

`long __stdcall  DES_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the DES context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Dispose Method](#M_Des_Dispose)  

### Remarks

### Example

See [`DES_UpdateHex`](#DES_UpdateHex).

### See Also

[`DES_Init`](#DES_Init)
[`DES_InitHex`](#DES_InitHex)
[`DES_UpdateHex`](#DES_UpdateHex)
[`DES_Update`](#DES_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_Hex"></a>DES_Hex
---------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`DES_HexMode`](#DES_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function DES_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = DES_Hex(strOutput, strInput, strKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  DES_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Encrypt Method](#M_Des_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Des.Decrypt Method](#M_Des_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
The key string *szKey* must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes). The parity bit is ignored.
The output string *szOutput* must be set up with at least the same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim sCorrect As String

    ' "Now is t" in hex
    strInput = "4e6f772069732074"
    strKey = "0123456789abcdef"
    sCorrect = "3fa40e8a984d4815"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = DES_Hex(strOutput, strInput, strKey, ENCRYPT)
    Debug.Print "CT=" & strOutput
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = DES_Hex(strOutput, strInput, strKey, DECRYPT)
    Debug.Print "P'=" & strOutput

```

This should result in output as follows:

```

KY=0123456789abcdef
PT=4e6f772069732074
CT=3FA40E8A984D4815
OK=3fa40e8a984d4815
P'=4E6F772069732074

```

### See Also

[`DES_HexMode`](#DES_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_HexMode"></a>DES_HexMode
-----------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function DES_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strHexKey As String, ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = DES_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  DES_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Encrypt Method](#M_Des_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Des.Decrypt Method](#M_Des_Decrypt_StringStringModeString) (String, String, Mode, String)  

### COM/ASP Equivalent

`des.HexMode  

Public Function HexMode(ByVal strInput As String, ByVal strHexKey As String, ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As String`

See [`des.HexMode`](#x_hexmode).

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
Both the key string *szHexKey* and the initialization vector *szHexIV*
must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes), unless *szMode* is `ECB`, 
in which case *szIV* is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim strIV As String
    Dim sCorrect As String

    ' "Now is the time for all " in hex
    strInput = "4e6f77206973207468652074696d6520666f7220616c6c20"
    strKey = "0123456789abcdef"
    strIV = "1234567890abcdef"
    sCorrect = "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "IV=" & strIV
    Debug.Print "PT=" & strInput
    ' Encrypt in one-off process
    nRet = DES_HexMode(strOutput, strInput, strKey, True, "CBC", strIV)
    Debug.Print "CT=" & strOutput
    Debug.Print "OK=" & sCorrect

    ' Now decrypt back to plain text
    strInput = strOutput
    nRet = DES_HexMode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
    Debug.Print "P'=" & strOutput

```

This should result in output as follows:

```

KY=0123456789abcdef
IV=1234567890abcdef
PT=4e6f77206973207468652074696d6520666f7220616c6c20
CT=E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6
OK=e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6
P'=4E6F77206973207468652074696D6520666F7220616C6C20

```

### See Also

[`DES_Hex`](#DES_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_Init"></a>DES_Init
-----------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the DES function.
The key and IV data are provided in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function DES_Init Lib "diCryptoSys.dll" 
    (ByRef lpKey As Byte, ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`hContext = DES_Init(abKey, bEncrypt, strMode, abInitV)`

### C/C++ Syntax

`long __stdcall  DES_Init(const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`DES_Update`, `DES_UpdateHex` or `DES_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Des.InitEncrypt Method](#M_Des_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Des.InitDecrypt Method](#M_Des_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The key *lpKey* must be exactly 24 bytes long and the IV, if required, exactly 8 bytes long.
Unlike most other functions in this API, `DES_Init` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling a DES_Update function.

### Example

See [`DES_Update`](#DES_Update).

### See Also

[`DES_InitHex`](#DES_InitHex)
[`DES_UpdateHex`](#DES_UpdateHex)
[`DES_Update`](#DES_Update)
[`DES_Final`](#DES_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_InitError"></a>DES_InitError
---------------------------------------

Returns the error code after an unsuccessful call to
`DES_Init` or `DES_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function DES_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = DES_InitError()`

### C/C++ Syntax

`long __stdcall  DES_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`DES_Init` or `DES_InitHex`.

### .NET Equivalent

[Des.ErrCode Property](#M_Des_ErrCodeProperty)  

### Remarks

### Example

See [`DES_Update`](#DES_Update).

### See Also

<a id="DES_InitHex"></a>DES_InitHex
-----------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the DES function.
The key and IV data are provided in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function DES_InitHex Lib "diCryptoSys.dll"
    (ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`hContext = DES_InitHex(strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  DES_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector
 in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`DES_Update`, `DES_UpdateHex` or `DES_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Des.InitEncrypt Method](#M_Des_InitEncrypt_StringModeString) (String, Mode, String)  

[Des.InitDecrypt Method](#M_Des_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The key string *szHexKey* must be exactly 16 hex characters long (i.e. representing exactly 8 bytes/64 bits).
The initialization vector
string *szHexIV* must be exactly 16 hex characters long
(i.e. representing exactly the block size of 8 bytes), except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `DES_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling a DES_Update function.

### Example

See [`DES_UpdateHex`](#DES_UpdateHex).

### See Also

[`DES_Init`](#DES_Init)
[`DES_UpdateHex`](#DES_UpdateHex)
[`DES_Update`](#DES_Update)
[`DES_Final`](#DES_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_Update"></a>DES_Update
---------------------------------

Carries out the DES transformation function on a byte array
according to the direction
and mode set up by an earlier call to `DES_Init()` or `DES_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function DES_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = DES_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  DES_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the DES context set up by an earlier call to
	`DES_Init()` or `DES_InitHex()`.

*lpData*
:   [in,out] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Update Method](#M_Des_Update_Byte) (Byte[])  

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
Note that the output overwrites the input.

### Example

```

' From FIPS 81 Appendix C
' AN EXAMPLE OF THE CIPHER BLOCK CHAINING (CBC) MODE
    Dim nRet As Long
    Dim hContext As Long
    Dim sCorrect As String
    Dim abKey() As Byte
    Dim abInitV() As Byte
    Dim abBlock() As Byte
    Dim vntPlain(2) As Variant
    Dim vntCipher(2) As Variant
    Dim i As Integer
    
    sCorrect = "683788499a7c05f6"
    abKey = cnvBytesFromHexStr("0123456789abcdef")
    abInitV = cnvBytesFromHexStr("1234567890abcdef")
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    
    ' The plain text is the ASCII code for "Now is the time for all ".
    ' We will store in an array of arrays (!)
    vntPlain(0) = cnvBytesFromHexStr("4e6f772069732074")
    vntPlain(1) = cnvBytesFromHexStr("68652074696d6520")
    vntPlain(2) = cnvBytesFromHexStr("666f7220616c6c20")
    
    ' Initialise context
    hContext = DES_Init(abKey(0), ENCRYPT, "CBC", abInitV(0))
    If hContext = 0 Then
        nRet = DES_InitError()
        Debug.Print "DES_Init Failed: " & apiErrorLookup(nRet)
        Exit Function
    End If
    
    For i = 0 To 2
        ' Get next block of plaintext from array
        abBlock = vntPlain(i)
        Debug.Print "PT(" & i & ")=" & cnvHexStrFromBytes(abBlock)
        nRet = DES_Update(hContext, abBlock(0), 8)
        Debug.Print "CT(" & i & ")=" & cnvHexStrFromBytes(abBlock)
        vntCipher(i) = abBlock
    Next
    Debug.Print "OK   =" & sCorrect
    
    ' Clear the context
    nRet = DES_Final(hContext)
    
    ' Now do in decrypt mode
    hContext = DES_Init(abKey(0), DECRYPT, "CBC", abInitV(0))
    If hContext = 0 Then
        nRet = DES_InitError()
        Debug.Print "DES_Init Failed: " & apiErrorLookup(nRet)
        Exit Function
    End If
    
    For i = 0 To 2
        ' Get next block of ciphertext from array
        abBlock = vntCipher(i)
        Debug.Print "CT(" & i & ")=" & cnvHexStrFromBytes(abBlock)
        nRet = DES_Update(hContext, abBlock(0), 8)
        Debug.Print "PT(" & i & ")=" & cnvHexStrFromBytes(abBlock) & " [" & StrConv(abBlock, vbUnicode) & "]"
    Next
    nRet = DES_Final(hContext)

```

This should result in output as follows:

```

KY=0123456789ABCDEF
IV=1234567890ABCDEF
PT(0)=4E6F772069732074
CT(0)=E5C7CDDE872BF27C
PT(1)=68652074696D6520
CT(1)=43E934008C389C0F
PT(2)=666F7220616C6C20
CT(2)=683788499A7C05F6
OK   =683788499a7c05f6
CT(0)=E5C7CDDE872BF27C
PT(0)=4E6F772069732074 [Now is t]
CT(1)=43E934008C389C0F
PT(1)=68652074696D6520 [he time ]
CT(2)=683788499A7C05F6
PT(2)=666F7220616C6C20 [for all ]

```

### See Also

[`DES_Init`](#DES_Init)
[`DES_InitHex`](#DES_InitHex)
[`DES_UpdateHex`](#DES_UpdateHex)
[`DES_Final`](#DES_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="DES_UpdateHex"></a>DES_UpdateHex
---------------------------------------

Carries out the DES transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `DES_Init()` or `DES_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function DES_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = DES_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  DES_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the DES context set up by an earlier call to
	`DES_Init()` or `DES_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the DES function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Des.Update Method](#M_Des_Update_String) (String)  

### Remarks

*szHexString* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f]. Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

```

    Dim nRet As Long
    Dim hContext As Long
    Dim strKey As String
    Dim strHexString As String
    Dim sCorrect As String

    strKey = "0123456789abcdef"
    Debug.Print "KY=" & strKey

    ' Initialise the context
    hContext = DES_InitHex(strKey, True, "ECB", "")
    If hContext = 0 Then
        ' Always check for error
        MsgBox "Unable to initialise DES context", vbCritical
        Exit Function
    End If

    strHexString = "4e6f772069732074"
    Debug.Print "PT=" & strHexString
    nRet = DES_UpdateHex(hContext, strHexString)
    Debug.Print "CT=" & strHexString
    Debug.Print "OK=" & "3fa40e8a984d4815"

    strHexString = "68652074696d6520666f7220616c6c20"
    Debug.Print "PT=" & strHexString
    nRet = DES_UpdateHex(hContext, strHexString)
    Debug.Print "CT=" & strHexString
    Debug.Print "OK=" & "6a271787ab8883f9893d51ec4b563b53"

    nRet = DES_Final(hContext)

```

This should result in output as follows:

```

KY=0123456789abcdef
PT=4e6f772069732074
CT=3FA40E8A984D4815
OK=3fa40e8a984d4815
PT=68652074696d6520666f7220616c6c20
CT=6A271787AB8883F9893D51EC4B563B53
OK=6a271787ab8883f9893d51ec4b563b53

```

### See Also

[`DES_Init`](#DES_Init)
[`DES_InitHex`](#DES_InitHex)
[`DES_Update`](#DES_Update)
[`DES_Final`](#DES_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_Decrypt"></a>GCM_Decrypt
-----------------------------------

Decrypts authenticated ciphertext using the Galois/Counter Mode (GCM) of operation
with the AES algorithm (AES-GCM). 
All the input and output parameters are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function GCM_Decrypt Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByRef lpTag As Byte, ByVal nTagLen As Long, ByVal nOptions As Long) As Long`

`nRet = GCM_Decrypt(lpOutput(0), nOutLen, abData(0), nDataLen, 
	abKey(0), nKeyLen, abIV(0), nIvLen, abAAD(0), nAadLen, abTag(0), nTagLen, nOptions)`

### C/C++ Syntax

`long __stdcall  GCM_Decrypt(unsigned char *lpOutput, long nOutLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen, const unsigned char *lpTag, long nTagLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the ciphertext output.

*nOutLen*
:   [in] specifying the required length of the output in bytes.

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] equal to length of the key in *bytes*. 
	Must be one of 16, 24 or 32 corresponding to the required key bytes for AES-128, AES-192 or AES-256, respectively.

*lpIV*
:   [in] containing the initialization vector (IV).

*nIvLen*
:   [in] equal to length of the IV in bytes.

*lpAAD*
:   [in] array containing the Additional Authenticated Data (AAD).

*nAadLen*
:   [in] equal to length of the AAD in bytes.

*lpTag*
:   [in] array containing the tag.

*nTagLen*
:   [in] equal to the length of the tag in bytes.

*nOptions*
:   [in] for future use. Specify zero.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Gcm.Decrypt Method](#M_Gcm_Decrypt)  

### Remarks

This is a one-off, stateless function. If you need to use the same key repeatedly, use
[`GCM_InitKey`](#GCM_InitKey) - 
[`GCM_NextEncrypt`](#GCM_NextDecrypt) -
[`GCM_FinishKey`](#GCM_FinishKey) instead.
The output *lpOutput* must be at least as long as the input.
The authenticated decryption operation has five inputs: the secret key, an initialization vector (IV), 
the ciphertext itself, the additional authentication data (AAD), which can be zero-length; and the tag. The IV and AAD are passed in the clear.
There is one output: the plaintext, which is exactly the same length as the ciphertext.
If the inputs are not authentic, the function returns the non-zero error code
`DECRYPT_ERROR` `AUTH_FAIL_ERROR`.

*Changed in [v5.1]:* Note that the error code on authentication fail has changed from  
`DECRYPT_ERROR` (-18) to `AUTH_FAIL_ERROR` (-40).

### Example

See [`GCM_Decrypt`](#GCM_Decrypt).

### See Also

[`GCM_Encrypt`](#GCM_Encrypt)
[`GCM_InitKey`](#GCM_InitKey)
[`GCM_NextEncrypt`](#GCM_NextEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_Encrypt"></a>GCM_Encrypt
-----------------------------------

Provides authenticated encryption using the Galois/Counter Mode (GCM) of operation
with the AES algorithm (AES-GCM). It can also provide a stand-alone message authentication code (GMAC).
All the input and output parameters are in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function GCM_Encrypt Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByRef lpTagOut As Byte, ByVal nTagLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, ByVal nOptions As Long) As Long`

`nRet = GCM_Encrypt(lpOutput(0), nOutLen, abTagOut(0), nTagLen, abData(0), nDataLen, 
	abKey(0), nKeyLen, abIV(0), nIvLen, abAAD(0), nAadLen, nOptions)`

### C/C++ Syntax

`long __stdcall  GCM_Encrypt(unsigned char *lpOutput, long nOutLen, unsigned char *lpTagOut, long nTagLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the ciphertext output.

*nOutLen*
:   [in] specifying the required length of the output in bytes.

*lpTagOut*
:   [out] array of sufficient length to receive the tag, at least 4 bytes long.

*nTagLen*
:   [in] specifying the required length of the tag in bytes.

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] equal to length of the key in *bytes*. 
	Must be one of 16, 24 or 32 corresponding to the required key bytes for AES-128, AES-192 or AES-256, respectively.

*lpIV*
:   [in] containing the initialization vector (IV).

*nIvLen*
:   [in] equal to length of the IV in bytes.

*lpAAD*
:   [in] array containing the optional Additional Authenticated Data (AAD).

*nAadLen*
:   [in] equal to length of the AAD in bytes.

*nOptions*
:   [in] for future use. Specify zero.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Gcm.Encrypt Method](#M_Gcm_Encrypt)  

### Remarks

This is a one-off, stateless function. If you need to use the same key repeatedly, use
[`GCM_InitKey`](#GCM_InitKey) - 
[`GCM_NextEncrypt`](#GCM_NextEncrypt) -
[`GCM_FinishKey`](#GCM_FinishKey) instead.
The output *lpOutput* must be at least as long as the input, or zero length for GMAC.
There are four inputs for authenticated encryption: the secret key, an initialization vector (IV), 
the plaintext itself, and optional additional authentication data (AAD). The IV and AAD are passed in the clear.
There are two outputs: the ciphertext, which is exactly the same length as the plaintext, and 
an authentication tag (the "tag").
The tag length can be any length from 4 to 16 bytes (`API_MAX_GMAC_BYTES`); that is, 32 to 128 bits. 
You can truncate the tag value afterwards should you wish, at the cost of reduced security.
The IV can, in principle, be any length, but 12 bytes (96 bits) is recommended as the algorithm is optimised for that length.
The AES algorithm is decided by the length of key you pass: 16 bytes for AES-128, 24 for AES-192, 32 for AES-256; otherwise an error.
See [Security considerations for AEAD encryption](#aeadsecurity).

#### GMAC

To produce a message authentication code (GMAC), pass an empty or null string for the plaintext input *lpData* 
and a zero length *nOutLen* for the output ciphertext.
The "message" is passed in the AAD parameter and the GMAC value is output in the tag.
A unique IV is still required.

### Example

This is Test Case 4 from Appendix B of [[MCGR05](#MCGR05)].

```

Dim abKey() As Byte
Dim abPlain() As Byte
Dim abAAD() As Byte
Dim abIV() As Byte
Dim abTag() As Byte
Dim abCipher() As Byte
Dim abCheck() As Byte
Dim nKeyLen As Long
Dim nDataLen As Long
Dim nIVLen As Long
Dim nAadLen As Long
Dim nTagLen As Long
Dim nRet As Long
' Test Case 4:
' Convert test vectors from hex to byte array format
abKey = cnvBytesFromHexStr("feffe9928665731c6d6a8f9467308308")
abPlain = cnvBytesFromHexStr("d9313225f88406e5a55909c5aff5269a" & _
    "86a7a9531534f7da2e4c303d8a318a72" & _
    "1c3c0c95956809532fcf0e2449a6b525" & _
    "b16aedf5aa0de657ba637b39")
abAAD = cnvBytesFromHexStr("feedfacedeadbeeffeedfacedeadbeef" & _
    "abaddad2")
abIV = cnvBytesFromHexStr("cafebabefacedbaddecaf888")
' and compute lengths
nKeyLen = UBound(abKey) + 1
nDataLen = UBound(abPlain) + 1
nIVLen = UBound(abIV) + 1
nAadLen = UBound(abAAD) + 1

' Dimension output arrays
nTagLen = API_MAX_GMAC_BYTES
ReDim abTag(nTagLen - 1)
ReDim abCipher(nDataLen - 1)

' Do the business
nRet = GCM_Encrypt(abCipher(0), nDataLen, abTag(0), nTagLen, _
    abPlain(0), nDataLen, _
    abKey(0), nKeyLen, abIV(0), nIVLen, abAAD(0), nAadLen, 0)
Debug.Print "GCM_Encrypt returns " & nRet & " (expecting 0)"
Debug.Print "CT =" & cnvHexStrFromBytes(abCipher)
Debug.Print "TAG=" & cnvHexStrFromBytes(abTag)

' Check we can decrypt
ReDim abCheck(nDataLen - 1)
nRet = GCM_Decrypt(abCheck(0), nDataLen, abCipher(0), nDataLen, _
    abKey(0), nKeyLen, abIV(0), nIVLen, abAAD(0), nAadLen, _
    abTag(0), nTagLen, 0)
Debug.Print "GCM_Decrypt returns " & nRet & " (expecting 0)"
Debug.Print "PT'=" & cnvHexStrFromBytes(abCheck)
Debug.Print "PT =" & cnvHexStrFromBytes(abPlain)	

```

This should result in output as follows:

```

GCM_Encrypt returns 0 (expecting 0)
CT =42831EC2217774244B7221B784D0D49CE3AA212F2C02A4E035C17E2329ACA12E21D514B25466931C7D8F6A5AAC84AA051BA30B396A0AAC973D58E091
TAG=5BC94FBC3221A5DB94FAE95AE7121A47
GCM_Decrypt returns 0 (expecting 0)
PT'=D9313225F88406E5A55909C5AFF5269A86A7A9531534F7DA2E4C303D8A318A721C3C0C95956809532FCF0E2449A6B525B16AEDF5AA0DE657BA637B39
PT =D9313225F88406E5A55909C5AFF5269A86A7A9531534F7DA2E4C303D8A318A721C3C0C95956809532FCF0E2449A6B525B16AEDF5AA0DE657BA637B39

```

This is a GMAC test vector:

```

Dim abKey() As Byte
Dim abAAD() As Byte
Dim abIV() As Byte
Dim abTag() As Byte
Dim nKeyLen As Long
Dim nAadLen As Long
Dim nIvLen As Long
Dim nTagLen As Long
Dim nRet As Long
' Source: http://www.mail-archive.com/stds-p1619@listserv.ieee.org/msg00321.html
' KEY feffe9928665731c6d6a8f9467308308
' IV  cafebabefacedbaddecaf888
' AAD feedfacedeadbeeffeedfacedeadbeef
' TAG 54df474f4e71a9ef8a09bf30da7b1a92
abKey = cnvBytesFromHexStr("feffe9928665731c6d6a8f9467308308")
abIV = cnvBytesFromHexStr("cafebabefacedbaddecaf888")
abAAD = cnvBytesFromHexStr("feedfacedeadbeeffeedfacedeadbeef")
nKeyLen = UBound(abKey) + 1
nIvLen = UBound(abIV) + 1
nAadLen = UBound(abAAD) + 1

Debug.Print "KEY " & cnvHexStrFromBytes(abKey)
Debug.Print "IV  " & cnvHexStrFromBytes(abIV)
Debug.Print "AAD " & cnvHexStrFromBytes(abAAD)

' Dimension output array
nTagLen = API_MAX_GMAC_BYTES
ReDim abTag(nTagLen - 1)

' GMAC := Encrypt with no CT output or PT input. GMAC value is in tag.
nRet = GCM_Encrypt(0, 0, abTag(0), nTagLen, 0, 0, _
    abKey(0), nKeyLen, abIV(0), nIvLen, abAAD(0), nAadLen, 0)
Debug.Print "TAG " & cnvHexStrFromBytes(abTag)
Debug.Print "OK  " & "54df474f4e71a9ef8a09bf30da7b1a92"

```

This should result in output as follows:

```

KEY FEFFE9928665731C6D6A8F9467308308
IV  CAFEBABEFACEDBADDECAF888
AAD FEEDFACEDEADBEEFFEEDFACEDEADBEEF
TAG 54DF474F4E71A9EF8A09BF30DA7B1A92
OK  54df474f4e71a9ef8a09bf30da7b1a92	

```

### See Also

[`GCM_Decrypt`](#GCM_Decrypt)
[`GCM_InitKey`](#GCM_InitKey)
[`GCM_NextEncrypt`](#GCM_NextEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_FinishKey"></a>GCM_FinishKey
---------------------------------------

Closes the GCM context and destroys the key.

### VBA/VB6 Syntax

`Public Declare Function GCM_FinishKey Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = GCM_FinishKey(hContext)`

### C/C++ Syntax

`long __stdcall  GCM_FinishKey(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the GCM context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Gcm.Dispose Method](#M_Gcm_Dispose)  

### Remarks

### Example

See the examples in
[`GCM_InitKey`](#GCM_InitKey) and
[`GCM_NextEncrypt`](#GCM_NextEncrypt).

### See Also

[`GCM_InitKey`](#GCM_InitKey)
[`GCM_NextEncrypt`](#GCM_NextEncrypt)
[`GCM_NextDecrypt`](#GCM_NextDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_InitKey"></a>GCM_InitKey
-----------------------------------

Initializes the context with the key ready for repeated operations of 
[`GCM_NextEncrypt`](#GCM_NextEncrypt) and
[`GCM_NextDecrypt`](#GCM_NextDecrypt).

### VBA/VB6 Syntax

`Public Declare Function GCM_InitKey Lib "diCryptoSys.dll" (ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal nOptions As Long) As Long`

`nRet = GCM_InitKey(abKey(0), nKeyLen, nOptions)`

### C/C++ Syntax

`long __stdcall  GCM_InitKey(const unsigned char *lpKey, long nKeyLen, long nOptions);`

### Parameters

*lpKey*
:   [in] array containing the key.

*nKeyLen*
:   [in] equal to length of the key in *bytes*. 
	Must be one of 16, 24 or 32 corresponding to the required key bytes for AES-128, AES-192 or AES-256, respectively.

*nOptions*
:   [in] for future use. Specify zero.

### Returns (VBA/C)

non-zero handle of the GCM context `hContext`. Returns *zero if an error occurs*.

### .NET Equivalent

[Gcm.InitKey Method](#M_Gcm_InitKey)  

### Remarks

It is important to check for a zero context handle and stop if one occurs.

### Example

```

Dim abKey() As Byte
Dim nKeyLen As Long
Dim hContext As Long
Dim nCode As Long

' Initialise with a valid key
abKey = cnvBytesFromHexStr("feffe9928665731c6d6a8f9467308308")
nKeyLen = UBound(abKey) + 1
hContext = GCM_InitKey(abKey(0), nKeyLen, 0)
Debug.Print "GCM_InitKey returns " & Hex(hContext) & " (expected non-0)"
If hContext <> 0 Then
    '... do something here...
    ' Destroy the key
    Call GCM_FinishKey(hContext)
End If

' Now try an invalid key (length must be 16,24, or 32 bytes)
abKey = cnvBytesFromHexStr("badace")
nKeyLen = UBound(abKey) + 1
hContext = GCM_InitKey(abKey(0), nKeyLen, 0)
Debug.Print "GCM_InitKey returns " & Hex(hContext)
' Use API_ErrorCode to find the error value
nCode = API_ErrorCode()
Debug.Print "API_ErrorCode returns " & nCode & ": " & apiErrorLookup(nCode)

```

This should result in output as follows:

```

GCM_InitKey returns 3C8D3BD3 (expected non-0)
GCM_InitKey returns 0
API_ErrorCode returns 33: Invalid key length (BAD_KEY_LEN_ERROR)

```

### See Also

[`GCM_NextEncrypt`](#GCM_NextEncrypt)
[`GCM_NextDecrypt`](#GCM_NextDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_NextDecrypt"></a>GCM_NextDecrypt
-------------------------------------------

Carries out the GCM authenticated decryption operation using the key 
set up by an earlier call to [`GCM_InitKey`](#GCM_InitKey).

### VBA/VB6 Syntax

`Public Declare Function GCM_NextDecrypt Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpOutput As Byte, ByVal nOutLen As Long, 
ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpIV As Byte, ByVal nIvLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long, 
ByRef lpTag As Byte, ByVal nTagLen As Long) As Long`

`nRet = GCM_NextDecrypt(hContext, lpOutput(0), nOutLen, abData(0), nDataLen, 
abIV(0), nIvLen, abAAD(0), nAadLen, abTag(0), nTagLen)`

### C/C++ Syntax

`long __stdcall  GCM_NextDecrypt(long hContext, unsigned char *lpOutput, long nOutLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen, const unsigned char *lpTag, long nTagLen);`

### Parameters

*hContext*
:   [in] handle to the GCM context set up by an earlier call to [GCM_InitKey](#GCM_InitKey).

*lpOutput*
:   [out] array of sufficient length to receive the ciphertext output.

*nOutLen*
:   [in] specifying the required length of the output in bytes.

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

*lpIV*
:   [in] containing the initialization vector (IV).

*nIvLen*
:   [in] equal to length of the IV in bytes.

*lpAAD*
:   [in] array containing the Additional Authenticated Data (AAD).

*nAadLen*
:   [in] equal to length of the AAD in bytes.

*lpTag*
:   [in] array containing the tag.

*nTagLen*
:   [in] equal to the length of the tag in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Gcm.NextDecrypt Method](#M_Gcm_NextDecrypt)  

### Remarks

See the remarks for [`GCM_Decrypt`](#GCM_Decrypt) and the 
[Security considerations for AEAD encryption](#aeadsecurity).

### Example

### See Also

[`GCM_InitKey`](#GCM_InitKey)
[`GCM_NextDecrypt`](#GCM_NextEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="GCM_NextEncrypt"></a>GCM_NextEncrypt
-------------------------------------------

Carries out the GCM authenticated encryption operation using the key 
set up by an earlier call to [`GCM_InitKey`](#GCM_InitKey).

### VBA/VB6 Syntax

`Public Declare Function GCM_NextEncrypt Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpOutput As Byte, ByVal nOutLen As Long, 
ByRef lpTagOut As Byte, ByVal nTagLen As Long, ByRef lpData As Byte, ByVal nDataLen As Long, 
ByRef lpIV As Byte, ByVal nIvLen As Long, ByRef lpAAD As Byte, ByVal nAadLen As Long) As Long`

`nRet = GCM_NextEncrypt(hContext, lpOutput(0), nOutLen, abTagOut(0), nTagLen, abData(0), nDataLen, 
abIV(0), nIvLen, abAAD(0), nAadLen)`

### C/C++ Syntax

`long __stdcall  GCM_NextEncrypt(long hContext, unsigned char *lpOutput, long nOutLen, unsigned char *lpTagOut, long nTagLen, const unsigned char *lpData, long nDataLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen);`

### Parameters

*hContext*
:   [in] handle to the GCM context set up by an earlier call to [GCM_InitKey](#GCM_InitKey).

*lpOutput*
:   [out] array of sufficient length to receive the ciphertext output.

*nOutLen*
:   [in] specifying the required length of the output in bytes.

*lpTagOut*
:   [out] array of sufficient length to receive the tag, at least 4 bytes long.

*nTagLen*
:   [in] specifying the required length of the tag in bytes.

*lpData*
:   [in] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

*lpIV*
:   [in] containing the initialization vector (IV).

*nIvLen*
:   [in] equal to length of the IV in bytes.

*lpAAD*
:   [in] array containing the optional Additional Authenticated Data (AAD).

*nAadLen*
:   [in] equal to length of the AAD in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Gcm.NextEncrypt Method](#M_Gcm_NextEncrypt)  

### Remarks

See the remarks for [`GCM_Encrypt`](#GCM_Encrypt) and the 
[Security considerations for AEAD encryption](#aeadsecurity).

### Example

This example uses AES-GCM to create some demo authenticated payloads for IPsec.

```

Public Sub Test_GCM_IPsec()
' Refs: RFC4106, RFC4303, RFC3602
    Dim abKey() As Byte
    Dim abSPI() As Byte
    Dim abSalt() As Byte
    Dim abIV() As Byte
    Dim abNonce() As Byte
    Dim nKeyLen As Long
    Dim nDataLen As Long
    Dim nNonceLen As Long
    Dim nAadLen As Long
    Dim nTagLen As Long
    Dim nRet As Long
    Dim hContext As Long
    Dim abTail() As Byte
    Dim nSeq As Long
    Dim abPlain() As Byte
    Dim abAAD() As Byte
    Dim abTag() As Byte
    Dim abCipher() As Byte
    Dim abPayload() As Byte
    Dim abCheck() As Byte
    Dim strCheck As String
    
    Dim asBlocks As Variant
    Dim nBlocks As Long
    ' Data we will send = text in blocks of 44 bytes
    ' (We use an array of strings here for our demo
    ' -- in practice, deal with input and its length as it comes)
    asBlocks = Array( _
        "From fairest creatures we desire increase,  ", _
        "That thereby beauty's rose might never die, ", _
        "But as the riper should by time decease,    ", _
        "His tender heir might bear his memory:      " _
    )
    nBlocks = UBound(asBlocks) + 1

    ' Test values -- in practice, these should be generated uniquely
    abKey = cnvBytesFromHexStr("90d382b410eeba7ad938c46cec1a82bf")
    abSalt = cnvBytesFromHexStr("e96e8c08")
    abSPI = cnvBytesFromHexStr("00004321")
    
    ' Constant lengths
    nKeyLen = 16
    nNonceLen = 12
    nAadLen = 8
    nTagLen = 8
    
    ReDim abTag(nTagLen - 1)
    
    ' IP padding + pad length + next header
    ' -- in this case always the same
    abTail = cnvBytesFromHexStr("01020201")
    
    ' Initialize AES-GCM key
    hContext = GCM_InitKey(abKey(0), nKeyLen, 0)
    If hContext = 0 Then
        Debug.Print "ERROR: GCM_InitKey failed"
        Exit Sub
    End If
    Debug.Print "KEY=" & cnvHexStrFromBytes(abKey)
    
    ' Process each block of data
    For nSeq = 1 To nBlocks
        Debug.Print "Seq #=" & nSeq
        ' 8-byte IV to ESP = 4-byte SPI || 4-byte SeqNum
        abIV = BytesConcat(abSPI, BytesFromWord32(nSeq))
        Debug.Print "IV =" & cnvHexStrFromBytes(abIV)
        ' 12-byte nonce to AES-GCM = 4-byte salt || 8-byte IV
        abNonce = BytesConcat(abSalt, abIV)
        Debug.Print "NON=" & cnvHexStrFromBytes(abNonce)
        ' Create AAD = 4-byte SPI || 4-byte SeqNum
        abAAD = BytesConcat(abSPI, BytesFromWord32(nSeq))
        Debug.Print "AAD=" & cnvHexStrFromBytes(abAAD)
        ' Create pre-encryption data = text block converted to byte array || tail
        abPlain = StrConv(asBlocks(nSeq - 1), vbFromUnicode)
        ' in this case, the padding is always the same...
        abPlain = BytesConcat(abPlain, abTail)
        Debug.Print "Pre-encryption Data (" & UBound(abPlain) + 1 & " bytes):" & vbCrLf & cnvHexStrFromBytes(abPlain)
        nDataLen = UBound(abPlain) + 1
        ' Encrypt it
        ReDim abCipher(nDataLen - 1)
        nRet = GCM_NextEncrypt(hContext, abCipher(0), nDataLen, abTag(0), nTagLen, _
            abPlain(0), nDataLen, abNonce(0), nNonceLen, abAAD(0), nAadLen)
        Debug.Print "GCM_NextEncrypt returns " & nRet & " (expected 0)"
        ' Display the parts...
        Debug.Print "IP DATAGRAM PAYLOAD:"
        Debug.Print "SPI/Seq #: " & cnvHexStrFromBytes(abSPI) & " " & cnvHexStrFromBytes(BytesFromWord32(nSeq))
        Debug.Print "IV: " & cnvHexStrFromBytes(abIV)
        Debug.Print "Encrypted Data (" & UBound(abCipher) + 1 & " bytes):" & vbCrLf & cnvHexStrFromBytes(abCipher)
        Debug.Print "ICV: " & cnvHexStrFromBytes(abTag)
        ' Compose IP payload
        abPayload = BytesConcat(abSPI, BytesFromWord32(nSeq))
        abPayload = BytesConcat(abPayload, abIV)
        abPayload = BytesConcat(abPayload, abCipher)
        abPayload = BytesConcat(abPayload, abTag)
        Debug.Print "Payload (" & UBound(abPayload) + 1 & " bytes):" & vbCrLf & cnvHexStrFromBytes(abPayload)
        
        ' To show this works, decrypt it as we go
        ' -- in practice, you'd need to recreate the nonce and the AAD
        ReDim abCheck(nDataLen - 1)
        nRet = GCM_NextDecrypt(hContext, abCheck(0), nDataLen, abCipher(0), nDataLen, _
            abNonce(0), nNonceLen, abAAD(0), nAadLen, abTag(0), nTagLen)
        Debug.Print "GCM_NextDecrypt returns " & nRet & " (expected 0)"
        strCheck = StrConv(abCheck, vbUnicode)
        ' -- in practice, you'd need to strip the padding, but we fudge here...
        Debug.Print "PT: [" & Left(strCheck, 44) & "]"
        
    Next
    
    Call GCM_FinishKey(hContext)

End Sub

' Some helper functions to deal with Byte arrays...
Private Function BytesConcat(ab1() As Byte, ab2() As Byte) As Variant
' Return ab1 || ab2
    Dim ab3() As Byte
    Dim i As Long
    ab3 = ab1
    ReDim Preserve ab3(UBound(ab1) + UBound(ab2) + 1)
    For i = 0 To UBound(ab2)
        ab3(i + UBound(ab1) + 1) = ab2(i)
    Next
    BytesConcat = ab3
End Function

Private Function BytesFromWord32(ByVal w As Long) As Variant
' Split 32-bit word w into 4-byte long Byte array (network order)
    Dim abArray() As Byte
    ReDim abArray(3)
    abArray(0) = CByte(((w And &HFF000000) \ &H1000000) And &HFF)
    abArray(1) = CByte(((w And &HFF0000) \ &H10000) And &HFF)
    abArray(2) = CByte(((w And &HFF00) \ &H100) And &HFF)
    abArray(3) = CByte((w And &HFF) And &HFF)
    BytesFromWord32 = abArray
End Function

```

### See Also

[`GCM_InitKey`](#GCM_InitKey)
[`GCM_NextDecrypt`](#GCM_NextDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_AddBytes"></a>HASH_AddBytes
---------------------------------------

Adds an array of bytes to be digested in the HASH context.

### VBA/VB6 Syntax

`Public Declare Function HASH_AddBytes Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = HASH_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall HASH_AddBytes(long hContext, const void *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] Handle to the HASH context.

*lpData*
:   [in] Byte array containing the next part of the message.

*nDataLen*
:   [in] Number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashAddBytes](#VB_hashAddBytes)(hContext As Long, lpData() As Byte) As Long`

`Public Function [hashAddString](#VB_hashAddString)(hContext As Long, szData As String) As Long`

### .NET Equivalent

[Hash.AddData Method](#M_Hash_AddData_Byte) (Byte[])  

[Hash.AddData Method](#M_Hash_AddData_String) (String)  

### C++ (STL) Equivalent

`int [crsysapi::Hash::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a7ce2fe7f104b3840474b946e164a3afb "External link") (bvec_t data)  

int [crsysapi::Hash::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a9fb5f9a9936309add9eda61f2e9ae2f5 "External link") (std::string s)`

### Remarks

The handle *hContext* to the context must have been set up with a
prior call to [`HASH_Init`](#HASH_Init). 
The `HASH_AddBytes` function may be called many times before creating
the final message digest with [`HASH_Final`](#HASH_Final).

VBA users can use the more convenient wrapper functions `hashAddBytes` and `hashAddString`.

### Example (VBA core function)

```

Dim hContext As Long
Dim r As Long
Dim nBytes As Long
Dim lpMessage1() As Byte
Dim lpMessage2() As Byte
Dim lpDigest() As Byte

hContext = HASH_Init(API_HASH_SHA1)
Debug.Print "HASH_Init returns 0x" & Hex(hContext)
' Check for an invalid handle
If hContext = 0 Then
  MsgBox "Failed to set context"
  Exit Sub
End If

' Create two arrays of bytes to digest (long way!)
ReDim lpMessage1(0) ' 1 bytes long
lpMessage1(0) = &H61     ' ASCII 'a'
ReDim lpMessage2(1) ' 2 bytes long
lpMessage2(0) = &H62     ' ASCII 'b'
lpMessage2(1) = &H63     ' ASCII 'c'

' Add data in parts (the string "abc")
r = HASH_AddBytes(hContext, lpMessage1(0), 1)
r = HASH_AddBytes(hContext, lpMessage2(0), 2)
nBytes = HASH_DigestLength(hContext)
Debug.Print "HASH_DigestLength=" & nBytes
ReDim lpDigest(nBytes - 1)
nBytes = HASH_Final(lpDigest(0), nBytes, hContext)
Debug.Print "DIG=" & cnvHexStrFromBytes(lpDigest)
Debug.Print "OK= " & "A9993E364706816ABA3E25717850C26C9CD0D89D"

```

### Example (VBA wrapper function)

```

Dim hContext As Long
Dim lpDigest() As Byte
' Initialize context to use SHA-3-256 (NB HASH_ func)
hContext = hashInit(API_HASH_SHA3_256)
Debug.Print "hashInit returns 0x" & Hex(hContext)
' Check for an invalid handle
If hContext = 0 Then
  MsgBox "Failed to set context"
  Exit Sub
End If
' Add "abc" in parts
Call hashAddBytes(hContext, cnvBytesFromHexStr("61"))   ' ASCII "a"
Call hashAddString(hContext, "")    ' Empty string => No effect
Call hashAddBytes(hContext, cnvBytesFromHexStr(""))    ' Empty byte array => No effect
Call hashAddString(hContext, "bc")  ' Add a string directly
' Get final digest value
lpDigest = hashFinal(hContext)
Debug.Print "DIG=" & cnvHexStrFromBytes(lpDigest)
Debug.Print "OK= " & "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"

```

### See Also

[`HASH_Init`](#HASH_Init)
[`HASH_Final`](#HASH_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_Bytes"></a>HASH_Bytes
---------------------------------

Creates a message digest hash as a byte array from byte data.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_Bytes Lib "diCryptoSys.dll" 
    (ByRef lpDigest As Byte, ByVal nDigLen As Long, ByRef lpMessage As Byte, 
    ByVal nMsgLen As Long, ByVal nOptions As Long) As Long`

`nRet = HASH_Bytes(abDigest(0), nDigLen, abMessage(0), nMsgLen, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  HASH_Bytes(unsigned char *lpOutput, long nOutLen, const void *lpMessage, long nMsgLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array to receive the hash digest.

*nOutLen*
:   [in] specifying the length in bytes of the output array.

*lpMessage*
:   [in] array containing the message data

*nMsgLen*
:   [in] specifying length of the message data in bytes.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_MD5` to use the MD5 algorithm  

`API_HASH_MD2` to use the MD2 algorithm (legacy)  

`API_HASH_RMD160` to use the RIPEMD-160 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm  

`API_HASH_ASCON_HASH` to use the ASCON-HASH algorithm  

`API_HASH_ASCON_HASHA` to use the ASCON-HASHA algorithm

### Returns (VBA/C)

If successful, the return value is the number of bytes in the hash digest array; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashBytes](#VB_hashBytes)(lpMessage() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Hash.BytesFromBytes Method](#M_Hash_BytesFromBytes)  

### Python Equivalent

`static [Hash.data](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.data "External link")(data, alg=Alg.SHA1)`

### Remarks

Specify a zero *nDigLen* parameter to find out the required length of the output array.
The maximum possible length is `API_MAX_HASH_BYTES`.
Hint: SHA-1 requires 20 bytes; MD5 and MD2 require 16 bytes; SHA-512 requires 64. 
The final digest will be truncated to the specified length if less than the expected size. 

### Example (VBA core function)

```

Dim nRet As Long
Dim abDigest() As Byte
Dim abMessage() As Byte
Dim nMsgLen As Long

' Set up message to be hashed
abMessage = StrConv("abc", vbFromUnicode)
nMsgLen = UBound(abMessage) + 1
' Pre-dimension digest array (NB zero-based so subtract one)
ReDim abDigest(API_MAX_HASH_BYTES - 1)

' Create default hash (SHA-1)
nRet = HASH_Bytes(abDigest(0), API_MAX_HASH_BYTES, abMessage(0), nMsgLen, 0)
If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
Debug.Print nRet, cnvHexStrFromBytes(abDigest)

' Repeat for MD5
ReDim abDigest(API_MAX_HASH_BYTES - 1)
nRet = HASH_Bytes(abDigest(0), API_MAX_HASH_BYTES, abMessage(0), nMsgLen, API_HASH_MD5)
If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
Debug.Print nRet, cnvHexStrFromBytes(abDigest)

' Repeat for SHA-3-384
ReDim abDigest(API_MAX_HASH_BYTES - 1)
nRet = HASH_Bytes(abDigest(0), API_MAX_HASH_BYTES, abMessage(0), nMsgLen, API_HASH_SHA3_384)
If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
Debug.Print nRet, cnvHexStrFromBytes(abDigest)

```

The above example should produce the following output:

```

 20           A9993E364706816ABA3E25717850C26C9CD0D89D
 16           900150983CD24FB0D6963F7D28E17F72
 48           EC01498288516FC926459F58E2C6AD8DF9B473CB0FC08C2596DA7CF0E49BE4B298D88CEA927AC7F539F1EDF228376D25

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
lpMessage = StrConv("abc", vbFromUnicode)
Debug.Print "lpMessage=" & cnvHexStrFromBytes(lpMessage)

Debug.Print "OK:" & vbCrLf & "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
Debug.Print hashHexFromBytes(lpMessage, API_HASH_SHA256)
Debug.Print hashHexFromHex("616263", API_HASH_SHA256)
Debug.Print hashHexFromFile("abc.txt", API_HASH_SHA256)
Debug.Print cnvHexStrFromBytes(hashBytes(lpMessage, API_HASH_SHA256))
Debug.Print cnvHexStrFromBytes(hashFile("abc.txt", API_HASH_SHA256))
```

### See Also

[`HASH_HexFromBytes`](#HASH_HexFromBytes)
[`HASH_HexFromHex`](#HASH_HexFromHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_DigestLength"></a>HASH_DigestLength
-----------------------------------------------

Returns the number of bytes in the hash output for the algorithm defined in the current HASH context.

### VBA/VB6 Syntax

`Public Declare Function HASH_DigestLength Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nLen = HASH_DigestLength(hContext)`

### C/C++ Syntax

`long _stdcall HASH_DigestLength(long hContext);`

### Parameters

*hContext*

:   [in] handle to the current HASH context.

### Returns (VBA/C)

The number of bytes in the hash output for the algorithm defined in the current HASH context, 
or a negative [error code](#errorcodes).

### .NET Equivalent

[Hash.LengthInBytes Property](#M_Hash_LengthInBytes)  

### Remarks

### Example

```

Dim h As Long
Dim nLen As Long
h = HASH_Init(API_HASH_SHA256)
nLen = HASH_DigestLength(h)
Debug.Print "HASH_DigestLength = " & nLen

```

```

HASH_DigestLength = 32

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_File"></a>HASH_File
-------------------------------

Creates a message digest hash in byte format for a file.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_File Lib "diCryptoSys.dll" 
    (ByRef lpDigest As Byte, ByVal nDigLen As Long, ByVal strFileName As String, 
    ByVal nOptions As Long) As Long`

`nRet = HASH_File(abDigest(0), nDigLen, strFileName, nOptions)`

### C/C++ Syntax

`long __stdcall  HASH_File(unsigned char *lpOutput, long nOutLen, const char *szFileName, long nOptions);`

### Parameters

*lpOutput*
:   [out] array to receive the hash digest.

*nOutLen*
:   [in] specifying the length in bytes of the output array.

*szFileName*
:   [in] containing the name of the file.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_MD5` to use the MD5 algorithm  

`API_HASH_MD2` to use the MD2 algorithm (legacy)  

`API_HASH_RMD160` to use the RIPEMD-160 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm  

and add 

`API_HASH_MODE_TEXT` to hash in "text" mode instead of default "binary" mode

### Returns (VBA/C)

If successful, the return value is the number of bytes in the hash digest array; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashFile](#VB_hashFile)(szFileName As String, nOptions As Long) As Byte()`

### .NET Equivalent

[Hash.BytesFromFile Method](#M_Hash_BytesFromFile)  

### Python Equivalent

`static [Hash.file](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.file "External link")(filename, alg=Alg.SHA1)`

### Remarks

Specify a zero *nDigLen* parameter to find out the required length of the output array.
The maximum size will be `API_MAX_HASH_BYTES`. 
The final digest will be truncated to the specified length if less than the expected size. 
Add the option `API_HASH_MODE_TEXT` to work in "text" mode where CR-LF pairs are treated
as a single newline (LF) character. 
Use this option to pass hash digests of text file between Windows and Unix systems.
The default mode is "binary" where each byte is treated individually.
Only ANSI file names and paths are supported (but see [CNV_ShortPathName](#CNV_ShortPathName) as a work around).
Note that Ascon-Hash is not available with this function.

### Examples

```

    Dim nRet As Long
    Dim abDigest() As Byte
    Dim sFileName As String
    
    ' File to be hashed contains a total of 13 bytes: "hello world" plus CR-LF
    ' 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a   hello world..

    sFileName = "C:\Test\hello.txt"
    
    ' Pre-dimension digest array - do this each time
    ReDim abDigest(API_MAX_HASH_BYTES)
    
    ' Create default hash (SHA1) in binary mode
    nRet = HASH_File(abDigest(0), API_MAX_HASH_BYTES, sFileName, 0)
    If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
    Debug.Print nRet, cnvHexStrFromBytes(abDigest)
    
    ' Use SHA1 in "text" mode
    ReDim abDigest(API_MAX_HASH_BYTES)
    nRet = HASH_File(abDigest(0), API_MAX_HASH_BYTES, sFileName, API_HASH_MODE_TEXT)
    If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
    Debug.Print nRet, cnvHexStrFromBytes(abDigest)
    
    ' Use MD5
    ReDim abDigest(API_MAX_HASH_BYTES)
    nRet = HASH_File(abDigest(0), API_MAX_HASH_BYTES, sFileName, API_HASH_MD5)
    If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
    Debug.Print nRet, cnvHexStrFromBytes(abDigest)
    
    ' Use MD5 in "text" mode
    ReDim abDigest(API_MAX_HASH_BYTES)
    nRet = HASH_File(abDigest(0), API_MAX_HASH_BYTES, sFileName, API_HASH_MD5 Or API_HASH_MODE_TEXT)
    If nRet > 0 Then ReDim Preserve abDigest(nRet - 1)
    Debug.Print nRet, cnvHexStrFromBytes(abDigest)

```

This should produce the following output:

```

 20           88A5B867C3D110207786E66523CD1E4A484DA697
 20           22596363B3DE40B06F981FB85D82312E8C0ED511
 16           A0F2A3C1DCD5B1CAC71BF0C03F2FF1BD
 16           6F5902AC237024BDD0C176CB93063DC4

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
lpMessage = StrConv("abc", vbFromUnicode)
Debug.Print "lpMessage=" & cnvHexStrFromBytes(lpMessage)

Debug.Print "OK:" & vbCrLf & "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
Debug.Print hashHexFromBytes(lpMessage, API_HASH_SHA256)
Debug.Print hashHexFromHex("616263", API_HASH_SHA256)
Debug.Print hashHexFromFile("abc.txt", API_HASH_SHA256)
Debug.Print cnvHexStrFromBytes(hashBytes(lpMessage, API_HASH_SHA256))
Debug.Print cnvHexStrFromBytes(hashFile("abc.txt", API_HASH_SHA256))
```

### See Also

[`HASH_HexFromFile`](#HASH_HexFromFile)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_Final"></a>HASH_Final
---------------------------------

Returns the final message digest value from the HASH context.

### VBA/VB6 Syntax

`Public Declare Function HASH_Final Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByVal hContext As Long) As Long`

`nRet = HASH_Final(lpOutput(0), nOutLen, hContext)` 

### C/C++ Syntax

`long __stdcall HASH_Final(unsigned char *lpOutput, long nOutLen, long hContext);`

### Parameters

*lpOutput*
:   [out] array to receive message digest.

*nOutLen*
:   [in] length in bytes of the output array.

*hContext*
:   [in] handle to the current HASH context.

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output array;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashFinal](#VB_hashFinal)(hContext As Long) As Byte()`

### .NET Equivalent

[Hash.Final Method](#M_Hash_Final)  

### C++ (STL) Equivalent

`bvec_t [crsysapi::Hash::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a2e5f4533e2645dc5dd8459ed25885a4f "External link") ()`

### Remarks

Computes the result of all [`HASH_AddBytes`](#HASH_AddBytes) calls since [`HASH_Init`](#HASH_Init).
Once called, the context is destroyed.

### Example

See [`HASH_AddBytes`](#HASH_AddBytes).

### See Also

[`HASH_Init`](#HASH_Init)
[`HASH_AddBytes`](#HASH_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_HexFromBits"></a>HASH_HexFromBits
---------------------------------------------

Creates a message digest hash in hexadecimal format from bit-oriented input.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_HexFromBits Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByRef lpData As Byte, 
ByVal nDataBitLen As Long, ByVal nOptions As Long) As Long`

`nRet = HASH_HexFromBits(strOutput, nOutChars, abData(0), nDataBitLen, nOptions)`

### C/C++ Syntax

`long __stdcall  HASH_HexFromBits(char *szOutput, long nMaxChars, const unsigned char *lpData, long nDataBitLen, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive hash digest in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*lpData*
:   [in] array containing the message data

*nDataBitLen*
:   [in] specifying length of the message data in *bits*.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashHexFromBits](#VB_hashHexFromBits)(lpData() As Byte, nDataBitLen As Long, nOptions As Long) As String`

### .NET Equivalent

[Hash.HexFromBits Method](#M_Hash_HexFromBits)  

### Python Equivalent

`static [Hash.hex_from_bits](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.hex_from_bits "External link")(data, databitlen, alg=Alg.SHA1)`

### Remarks

Pass a bitstring as an array of bytes in *lpData* in big-endian order with the most-significant bit first. 
The bitstring will be truncated to the number of bits specified in *nDataBitlen* and
extraneous bits on the right will be ignored.

For example, the byte array `(0x)717F8C` with `nDataBitLen=23`
represents the 23-bit bitstring `0111 0001 0111 1111 1000 110`,
and the byte array `(0x)5180` with `nDataBitLen=9`
represents the 9-bit bitstring `0101 0001 1`.

The number of bytes in the array *lpData* must be at least `ceil(nDataBitLen / 8)`.
Only the SHA family of hash functions is supported in bit-oriented mode.

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty (`""`) or NULL *szOutput* parameter 
to find out the required length of the output string (or use the appropriate `API_SHAnnn_CHARS` constant).
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

### Example (VBA core function)

```

Dim strDigest As String
Dim nRet As Long
Dim abData() As Byte
Dim nDataBitLen As Long

' SHA-1
strDigest = String(API_SHA1_CHARS, " ")
abData = cnvBytesFromHexStr("5180")
nDataBitLen = 9
Debug.Print "[SHA-1]"
Debug.Print "[L = " & API_SHA1_BYTES & "]"
Debug.Print "Len = " & nDataBitLen
Debug.Print "Msg = " & cnvHexStrFromBytes(abData)
nRet = HASH_HexFromBits(strDigest, Len(strDigest), abData(0), nDataBitLen, API_HASH_SHA1)
Debug.Print "MD = " & strDigest

```

The above example should produce the following output:

```

[SHA-1]
[L = 20]
Len = 9
Msg = 5180
MD = 0f582fa68b71ecdf1dcfc4946019cf5a18225bd2

```

This example uses SHA-3-256 on a 22-bit message from the NIST SHAVS-SHA3 test vectors. 
Note that the convention for representing bit strings in hex used by NIST is different from our big-endian convention.
For more details see [Notes on SHA-3](#sha3notes).

```

' Ref: SHAVS-SHA3 CAVS 19.0 "SHA3-256 ShortMsg" information for "SHA3AllBits1-28-16"
' Len = 22
' Msg = 259028*
' MD = d5863d4b1ff41551c92a9e08c52177e32376c9bd100c611c607db840096eb22f

' * NB NIST convention for bit strings is different from CryptoSys API
' NIST "259028" => API "2590A0"

Dim strDigest As String
Dim nRet As Long
Dim abData() As Byte
Dim nDataBitLen As Long

strDigest = String(API_SHA256_CHARS, " ")
abData = cnvBytesFromHexStr("2590A0")
nDataBitLen = 22
Debug.Print "[L = " & API_SHA256_BYTES * 8 & "]"
Debug.Print "Len = " & nDataBitLen
Debug.Print "Msg = " & cnvHexStrFromBytes(abData)
nRet = HASH_HexFromBits(strDigest, Len(strDigest), abData(0), nDataBitLen, API_HASH_SHA3_256)
Debug.Print "MD = " & strDigest

```

```

[L = 256]
Len = 22
Msg = 2590A0
MD = d5863d4b1ff41551c92a9e08c52177e32376c9bd100c611c607db840096eb22f

```

### Example (VBA wrapper function)

```

Dim strDigest As String
Dim lpData() As Byte

' SHA-1
lpData = cnvBytesFromHexStr("5180")
strDigest = hashHexFromBits(lpData, 9, API_HASH_SHA1)
Debug.Print "MD = " & strDigest
Debug.Print "OK = 0f582fa68b71ecdf1dcfc4946019cf5a18225bd2"

' SHAVS-SHA3 CAVS 19.0 "SHA3-256 ShortMsg"
lpData = cnvBytesFromHexStr("2590A0")
strDigest = hashHexFromBits(lpData, 22, API_HASH_SHA3_256)
Debug.Print "MD = " & strDigest
Debug.Print "OK = d5863d4b1ff41551c92a9e08c52177e32376c9bd100c611c607db840096eb22f"
```

### See Also

[`HASH_HexFromBytes`](#HASH_HexFromBytes)
[`HASH_Bytes`](#HASH_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_HexFromBytes"></a>HASH_HexFromBytes
-----------------------------------------------

Creates a message digest hash in hexadecimal format from byte (or string) data.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_HexFromBytes Lib "diCryptoSys.dll" 
(ByVal strOutput As String, ByVal nOutChars As Long, ByRef lpMessage As Byte, ByVal nMsgLen As Long, 
ByVal nOptions As Long) As Long`

Alternative for Visual Basic (VB6/VBA) only:-  

`Public Declare Function HASH_HexFromString Lib "diCryptoSys.dll" Alias "HASH_HexFromBytes" 
(ByVal strOutput As String, ByVal nOutChars As Long, ByVal strMessage As String, ByVal nMsgLen As Long, 
ByVal nOptions As Long) As Long`

`nRet = HASH_HexFromBytes(strOutput, nOutChars, abMessage(0), nMsgLen, nOptions)  

nRet = HASH_HexFromString(strOutput, nOutChars, strMessage, nMsgLen, nOptions)`

### C/C++ Syntax

`long __stdcall  HASH_HexFromBytes(char *szOutput, long nMaxChars, const void *lpMessage, long nMsgLen, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive hash digest in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*lpMessage*
:   [in] array containing the message data; or

*nMsgLen*
:   [in] specifying length of the message data in bytes.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_MD5` to use the MD5 algorithm  

`API_HASH_MD2` to use the MD2 algorithm (legacy)  

`API_HASH_RMD160` to use the RIPEMD-160 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm  

`API_HASH_ASCON_HASH` to use the ASCON-HASH algorithm  

`API_HASH_ASCON_HASHA` to use the ASCON-HASHA algorithm

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashHexFromBytes](#VB_hashHexFromBytes)(lpMessage() As Byte, nOptions As Long) As String`

### .NET Equivalent

[Hash.HexFromBytes Method](#M_Hash_HexFromBytes)  

[Hash.HexFromString Method](#M_Hash_HexFromString)  

### Python Equivalent

`static [Hash.hex_from_data](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.hex_from_data "External link")(data, alg=Alg.SHA1)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The maximum number of characters is `API_MAX_HASH_CHARS`.
The final digest will be truncated to the specified length if less than the
expected size. Only lower-case letters [a-f] are used in the output string.

### Examples

```

Dim nRet As Long
Dim sDigest As String
Dim abMessage() As Byte
' Set up message to be hashed in unambiguous Byte format
abMessage = StrConv("abc", vbFromUnicode)
' Pre-dimension digest string
sDigest = String(API_MAX_HASH_CHARS, " ")
' Create default hash (SHA1)
nRet = HASH_HexFromBytes(sDigest, Len(sDigest), abMessage(0), 3, 0)
Debug.Print nRet, Left(sDigest, nRet)
' Explicitly use SHA1
nRet = HASH_HexFromBytes(sDigest, Len(sDigest), abMessage(0), 3, API_HASH_SHA1)
Debug.Print nRet, Left(sDigest, nRet)
' Pre-dimension digest string and use MD5
sDigest = String(API_MD5_CHARS, " ")
nRet = HASH_HexFromBytes(sDigest, Len(sDigest), abMessage(0), 3, API_HASH_MD5)
Debug.Print nRet, sDigest
' Pre-dimension digest string and use MD2
sDigest = String(API_MD5_CHARS, " ")
nRet = HASH_HexFromBytes(sDigest, Len(sDigest), abMessage(0), 3, API_HASH_MD2)
Debug.Print nRet, sDigest
' Make output string shorter - only get back that many chars
sDigest = String(16, " ")
nRet = HASH_HexFromBytes(sDigest, Len(sDigest), abMessage(0), 3, API_HASH_SHA1)
Debug.Print nRet, sDigest

```

The above example should produce the following output:

```

 40 a9993e364706816aba3e25717850c26c9cd0d89d
 40 a9993e364706816aba3e25717850c26c9cd0d89d
 32 900150983cd24fb0d6963f7d28e17f72
 32 da853b0d3f88d99b30283a69e6ded6bb
 16 a9993e364706816a

```

Alternative using `String` type directly (assumes 8-bit ANSI characters in strMessage):

```

Dim nRet As Long
Dim sDigest As String
Dim strMessage As String

strMessage = "abc"
' Pre-dimension digest string
sDigest = String(40, " ")
' Create default hash (SHA1)
nRet = HASH_HexFromString(sDigest, Len(sDigest), strMessage, Len(strMessage), 0)
Debug.Print nRet, sDigest

```

Example in C code (in C we are less fussed about the distinction between `char`
and `unsigned char` types when dealing with non-zero ANSI characters):

```

long lRet;
char szDigest[API_MAX_HASH_CHARS+1]; /* NB add one */
char message[] = "abc";

/* Compute default SHA-1 digest */
lRet = HASH_HexFromBytes(szDigest, sizeof(szDigest)-1, 
	(unsigned char*)message, strlen(message), 0);
assert(lRet > 0);
printf("SHA1('abc')=%s\n", szDigest);
/* Compute MD5 digest */
lRet = HASH_HexFromBytes(szDigest, sizeof(szDigest)-1, 
	(unsigned char*)message, strlen(message), API_HASH_MD5);
assert(lRet > 0);
printf("MD5('abc')=%s\n", szDigest);
/* Compute MD2 digest */
lRet = HASH_HexFromBytes(szDigest, sizeof(szDigest)-1, 
	(unsigned char*)message, strlen(message), API_HASH_MD2);
assert(lRet > 0);
printf("MD2('abc')=%s\n", szDigest);

```

This should produce the output

```

SHA1('abc')=a9993e364706816aba3e25717850c26c9cd0d89d
MD5('abc')=900150983cd24fb0d6963f7d28e17f72
MD2('abc')=da853b0d3f88d99b30283a69e6ded6bb

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
lpMessage = StrConv("abc", vbFromUnicode)
Debug.Print "lpMessage=" & cnvHexStrFromBytes(lpMessage)

Debug.Print "OK:" & vbCrLf & "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
Debug.Print hashHexFromBytes(lpMessage, API_HASH_SHA256)
Debug.Print hashHexFromHex("616263", API_HASH_SHA256)
Debug.Print hashHexFromFile("abc.txt", API_HASH_SHA256)
Debug.Print cnvHexStrFromBytes(hashBytes(lpMessage, API_HASH_SHA256))
Debug.Print cnvHexStrFromBytes(hashFile("abc.txt", API_HASH_SHA256))
```

### See Also

[`HASH_HexFromFile`](#HASH_HexFromFile)
[`HASH_Bytes`](#HASH_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_HexFromFile"></a>HASH_HexFromFile
---------------------------------------------

Creates a message digest hash in hexadecimal format for a file.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_HexFromFile Lib "diCryptoSys.dll" 
(ByVal strOutput As String, ByVal nOutChars As Long, ByVal strFileName As String, 
ByVal nOptions As Long) As Long`

`nRet = HASH_HexFromFile(strOutput, nOutChars, strFileName, nOptions)`

### C/C++ Syntax

`long __stdcall  HASH_HexFromFile(char *szOutput, long nMaxChars, const char *szFileName, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive hash digest in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received in characters.

*szFileName*
:   [in] containing the name of the file.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_MD5` to use the MD5 algorithm  

`API_HASH_MD2` to use the MD2 algorithm (legacy)  

`API_HASH_RMD160` to use the RIPEMD-160 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm  

and add 

`API_HASH_MODE_TEXT` to hash in "text" mode instead of default "binary" mode

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashHexFromFile](#VB_hashHexFromFile)(szFileName As String, nOptions As Long) As String`

### .NET Equivalent

[Hash.HexFromFile Method](#M_Hash_HexFromFile)  

### Python Equivalent

`static [Hash.hex_from_file](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.hex_from_file "External link")(filename, alg=Alg.SHA1)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The maximum number of characters will be `API_MAX_HASH_CHARS`. C/C++ users should add one to this value
before allocating memory. The final digest will be truncated to the specified length if less than the
expected size. Only lower-case letters [a-f] are used.

Add the option `API_HASH_MODE_TEXT` to work in "text" mode where CR-LF pairs are treated
as a single newline character. The default mode is "binary" where each byte is treated individually.
Only ANSI file names and paths are supported (but see [CNV_ShortPathName](#CNV_ShortPathName) as a work around).
Note that Ascon-Hash is not available with this function.

### Examples

```

Dim nRet As Long
Dim sDigest As String
Dim sFileName As String

' File to be hashed contains a total of 13 bytes: "hello world" plus CR-LF
' 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a   hello world..

sFileName = "C:\Test\hello.txt"

' Pre-dimension digest string
sDigest = String(API_MAX_HASH_CHARS, " ")

' Create default hash (SHA1) in binary mode
nRet = HASH_HexFromFile(sDigest, Len(sDigest), sFileName, 0)
Debug.Print nRet, Left(sDigest, nRet)
' Use SHA1 in "text" mode
nRet = HASH_HexFromFile(sDigest, Len(sDigest), sFileName, API_HASH_MODE_TEXT)
Debug.Print nRet, Left(sDigest, nRet)
' Use MD5
nRet = HASH_HexFromFile(sDigest, Len(sDigest), sFileName, API_HASH_MD5)
Debug.Print nRet, Left(sDigest, nRet)
' Use MD5 in "text" mode
nRet = HASH_HexFromFile(sDigest, Len(sDigest), sFileName, API_HASH_MD5 Or API_HASH_MODE_TEXT)
Debug.Print nRet, Left(sDigest, nRet)

```

This should produce the following output:

```

 40           88a5b867c3d110207786e66523cd1e4a484da697
 40           22596363b3de40b06f981fb85d82312e8c0ed511
 32           a0f2a3c1dcd5b1cac71bf0c03f2ff1bd
 32           6f5902ac237024bdd0c176cb93063dc4

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
lpMessage = StrConv("abc", vbFromUnicode)
Debug.Print "lpMessage=" & cnvHexStrFromBytes(lpMessage)

Debug.Print "OK:" & vbCrLf & "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
Debug.Print hashHexFromBytes(lpMessage, API_HASH_SHA256)
Debug.Print hashHexFromHex("616263", API_HASH_SHA256)
Debug.Print hashHexFromFile("abc.txt", API_HASH_SHA256)
Debug.Print cnvHexStrFromBytes(hashBytes(lpMessage, API_HASH_SHA256))
Debug.Print cnvHexStrFromBytes(hashFile("abc.txt", API_HASH_SHA256))
```

### See Also

[`HASH_HexFromBytes`](#HASH_HexFromBytes)
[`HASH_File`](#HASH_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_HexFromHex"></a>HASH_HexFromHex
-------------------------------------------

Creates a message digest hash in hexadecimal format from data in a 
hexadecimal-encoded string.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function HASH_HexFromHex Lib "diCryptoSys.dll" 
(ByVal strOutput As String, ByVal nMaxChars As Long, ByVal strMsgHex As String, ByVal nOptions As Long) As Long`

`nRet = HASH_HexFromHex(strOutput, nMaxChars, strMsgHex, nOptions)`

### C/C++ Syntax

`long __stdcall  HASH_HexFromHex(char *szOutput, long nMaxChars, const char *szMsgHex, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive hash digest in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*szMsgHex*
:   [in] containing the message data in hexadecimal-encoded format.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_MD5` to use the MD5 algorithm  

`API_HASH_MD2` to use the MD2 algorithm (legacy)  

`API_HASH_RMD160` to use the RIPEMD-160 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm  

`API_HASH_ASCON_HASH` to use the ASCON-HASH algorithm  

`API_HASH_ASCON_HASHA` to use the ASCON-HASHA algorithm

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashHexFromHex](#VB_hashHexFromHex)(szMsgHex As String, nOptions As Long) As String`

### .NET Equivalent

[Hash.HexFromHex Method](#M_Hash_HexFromHex)  

### Python Equivalent

`static [Hash.hex_from_hex](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.hex_from_hex "External link")(datahex, alg=Alg.SHA1)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The maximum number of characters is `API_MAX_HASH_CHARS`.
The final digest will be truncated to the specified length if less than the
expected size. Only lower-case letters [a-f] are used in the output.

### Example (VBA core function)

```

Dim strDigest As String
Dim nRet As Long
Dim strData As String
strDigest = String(API_SHA1_CHARS, " ")
strData = "616263"
nRet = HASH_HexFromHex(strDigest, Len(strDigest), strData, API_HASH_SHA1)
Debug.Print strDigest

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
lpMessage = StrConv("abc", vbFromUnicode)
Debug.Print "lpMessage=" & cnvHexStrFromBytes(lpMessage)

Debug.Print "OK:" & vbCrLf & "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
Debug.Print hashHexFromBytes(lpMessage, API_HASH_SHA256)
Debug.Print hashHexFromHex("616263", API_HASH_SHA256)
Debug.Print hashHexFromFile("abc.txt", API_HASH_SHA256)
Debug.Print cnvHexStrFromBytes(hashBytes(lpMessage, API_HASH_SHA256))
Debug.Print cnvHexStrFromBytes(hashFile("abc.txt", API_HASH_SHA256))
```

### See Also

[`HASH_HexFromBytes`](#HASH_HexFromBytes)
[`HASH_Bytes`](#HASH_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_Init"></a>HASH_Init
-------------------------------

Initialises the HASH context ready for subsequent calls with
`HASH_AddBytes` and `HASH_Final`.

### VBA/VB6 Syntax

`Public Declare Function HASH_Init Lib "diCryptoSys.dll" (ByVal nAlg As Long) As Long`

`Dim hContext As Long  

    hContext = HASH_Init(nAlg)`

### C/C++ Syntax

`long _stdcall HASH_Init(long nAlg);`

### Parameters

*nAlg*
:   [in] Algorithm to be used. Select one of:  

`API_HASH_SHA1` (0) to use the SHA-1 algorithm (default)  

`API_HASH_SHA224` to use the SHA-224 algorithm  

`API_HASH_SHA256` to use the SHA-256 algorithm  

`API_HASH_SHA384` to use the SHA-384 algorithm  

`API_HASH_SHA512` to use the SHA-512 algorithm  

`API_HASH_SHA3_224` to use the SHA-3-224 algorithm  

`API_HASH_SHA3_256` to use the SHA-3-256 algorithm  

`API_HASH_SHA3_384` to use the SHA-3-384 algorithm  

`API_HASH_SHA3_512` to use the SHA-3-512 algorithm

### Returns (VBA/C)

Non-zero handle of the HASH context, or *zero* if an error occurs.

### .NET Equivalent

[Hash.Init Method](#M_Hash_Init)  

### C++ (STL) Equivalent

`bool [crsysapi::Hash::Init](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a96bd905a5b16dba31732fe104d257492 "External link") (Alg alg)`

### Remarks

Only the SHA-1, SHA-2 and SHA-3 families of hash algorithms are supported.
While the context handle is valid, add data to be digested in blocks of any length using [`HASH_AddBytes`](#HASH_AddBytes).
VBA users can use the wrapper functions `hashAddBytes` and `hashAddString`.

### Example

See [`HASH_AddBytes`](#HASH_AddBytes).

### See Also

[`HASH_AddBytes`](#HASH_AddBytes)
[`HASH_Final`](#HASH_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_Length"></a>HASH_Length
-----------------------------------

Return length of message digest output in bytes.

### VBA/VB6 Syntax

`Public Declare Function HASH_Length Lib "diCryptoSys.dll" (ByVal nAlgId As Long) As Long`

`nRet = HASH_Length(nAlgId)`

### C/C++ Syntax

`long __stdcall HASH_Length(long nAlgId);`

### Parameters

*nAlgId*
:   [in] Algorithm Id flag. Select one of `API_HASH_*`:  

`API_HASH_SHA1` SHA-1 algorithm  

`API_HASH_SHA224` SHA-224 algorithm  

`API_HASH_SHA256` SHA-256 algorithm  

`API_HASH_SHA384` SHA-384 algorithm  

`API_HASH_SHA512` SHA-512 algorithm  

`API_HASH_SHA3_224` SHA-3-224 algorithm  

`API_HASH_SHA3_256` SHA-3-256 algorithm  

`API_HASH_SHA3_384` SHA-3-384 algorithm  

`API_HASH_SHA3_512` SHA-3-512 algorithm  

`API_HASH_MD5` MD5 algorithm  

`API_HASH_MD2` MD2 algorithm  

`API_HASH_RMD160` RIPEMD-160 algorithm  

`API_HASH_ASCON_HASH`ASCON-HASH algorithm  

`API_HASH_ASCON_HASHA` ASCON-HASHA algorithm

### Returns (VBA/C)

Length of the hash function output in bytes; 
else a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [hashLength](#VB_hashLength) (nAlgId As Long) As Long`

### .NET Equivalent

[Hash.LengthInBytes Method](#M_Hash_LengthInBytes)  

### Python Equivalent

`static [Hash.length](https://cryptosys.net/pydocapi/class-stubs/Hash.html#crsysapi.Hash.length "External link")(alg)`

### Remarks

*[New in v6.21]*

### Example (VBA core function)

```

Debug.Print Hash_Length(API_HASH_SHA512)
' 64

```

### Example (VBA wrapper function)

```

Debug.Print hashLength(API_HASH_ASCON_HASH)
' 32

```

### See Also

[[Contents](#topofpage)] [[Index](#index)]

<a id="HASH_Reset"></a>HASH_Reset
---------------------------------

Resets the HASH context.

### VBA/VB6 Syntax

`Public Declare Function HASH_Reset Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = HASH_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  HASH_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the HASH context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Hash.Reset Method](#M_Hash_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

This trivial example creates a context handle for SHA-1, gets the output length in bytes (expecting 20), and then destroys it.

```

Dim hContext As Long
Dim r As Long

hContext = HASH_Init(API_HASH_SHA1)
Debug.Print "HASH_Init returns 0x" & Hex(hContext) & " (expected nonzero)"
Debug.Print "HASH_DigestLength = " & HASH_DigestLength(hContext)
r = HASH_Reset(hContext)
Debug.Print "After reset, HASH_DigestLength returns " & HASH_DigestLength(hContext)
Debug.Print "API_ErrorCode=" & API_ErrorCode() & ": " & apiErrorLookup(API_ErrorCode())

hContext = HASH_Init(&HFF)  ' Invalid hash alg code
Debug.Print "HASH_Init(INVALID) returns 0x" & Hex(hContext)
Debug.Print "API_ErrorCode=" & API_ErrorCode() & ": " & apiErrorLookup(API_ErrorCode())

```

```

HASH_Init returns 0x19050DD5 (expected nonzero)
HASH_DigestLength = 20
After reset, HASH_DigestLength returns -64
API_ErrorCode=64: Invalid context handle (INVALID_HANDLE_ERROR)
HASH_Init(INVALID) returns 0x0
API_ErrorCode=19: Item is not supported (NOT_SUPPORTED_ERROR)

```

### See Also

[`HASH_Init`](#HASH_Init)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_AddBytes"></a>MAC_AddBytes
-------------------------------------

Adds an array of bytes to be authenticated in the MAC context.

### VBA/VB6 Syntax

`Public Declare Function MAC_AddBytes Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = MAC_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall MAC_AddBytes(long hContext, const void *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] Handle to the MAC context.

*lpData*
:   [in] Byte array containing the next part of the message.

*nDataLen*
:   [in] Number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [macAddBytes](#VB_macAddBytes)(hContext As Long, lpData() As Byte) As Long`

`Public Function [macAddString](#VB_macAddString)(hContext As Long, szData As String) As Long`

### .NET Equivalent

[Mac.AddData Method](#M_Mac_AddData_Byte) (Byte[])  

[Mac.AddData Method](#M_Mac_AddData_String) (String)  

### C++ (STL) Equivalent

`int [crsysapi::Mac::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a2b019edcd6d0826100d8f9145dce951f "External link") (bvec_t data)  

int [crsysapi::Mac::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a6fe5fba860d553101ae251c44db3ad84 "External link") (std::string s)`

### Remarks

The handle *hContext* to the context must have been set up with a
prior call to [`MAC_Init`](#MAC_Init). 
The `MAC_AddBytes` function may be called many times before creating
the final message digest with [`MAC_Final`](#MAC_Final).

VBA users can use the more convenient wrapper functions `macAddBytes` and `macAddString`.

### Example (VBA core function)

### Example (VBA wrapper function)

```

' Test case 4 from RFC 2202 and RFC 4231
' key =           0x0102030405060708090a0b0c0d0e0f10111213141516171819
' key_len         25
' data =          0xcd repeated 50 times
' data_len =      50
Dim hContext As Long
Dim r As Long
Dim lpKey() As Byte
Dim lpMsg10() As Byte
Dim lpDigest() As Byte
Dim i As Long
lpKey = cnvBytesFromHexStr("0102030405060708090a0b0c0d0e0f10111213141516171819")
lpMsg10 = cnvBytesFromHexStr("cdcdcdcdcdcdcdcdcdcd")    ' 0xcd repeated 10 times

' HMAC-SHA-1
hContext = macInit(lpKey, API_HMAC_SHA1)
Debug.Print "macInit returns 0x" & Hex(hContext) & " (expected nonzero)"
For i = 1 To 5
    r = macAddBytes(hContext, lpMsg10)
    Debug.Print "macAddBytes returns " & r
Next
lpDigest = macFinal(hContext)
Debug.Print "MAC=" & cnvHexStrFromBytes(lpDigest)
Debug.Print "OK= " & "4c9007f4026250c6bc8414f9bf50c86c2d7235da"

' HMAC-SHA-256
hContext = macInit(lpKey, API_HMAC_SHA256)
Debug.Print "macInit returns 0x" & Hex(hContext) & " (expected nonzero)"
For i = 1 To 5
    r = macAddBytes(hContext, lpMsg10)
    'Debug.Print "macAddBytes returns " & r
Next
lpDigest = macFinal(hContext)
Debug.Print "MAC=" & cnvHexStrFromBytes(lpDigest)
Debug.Print "OK= " & "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"

Dim strData As String
Dim strKey As String
' Test case 2 from RFC 2202 and RFC 4231
strData = "what do ya want for nothing?"
strKey = "Jefe"
lpKey = StrConv(strKey, vbFromUnicode)
hContext = macInit(lpKey, API_HMAC_SHA512)
' Split input into parts
r = macAddString(hContext, "what do ya")
r = macAddString(hContext, " want for ")
r = macAddString(hContext, "nothing?")
lpDigest = macFinal(hContext)
Debug.Print "MAC=" & cnvHexStrFromBytes(lpDigest)
Debug.Print "OK =" _
& "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554" _
& "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" 

```

### See Also

[`MAC_Init`](#MAC_Init)
[`MAC_Final`](#MAC_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_Bytes"></a>MAC_Bytes
-------------------------------

Creates a keyed message authentication code (MAC)
as a byte array from byte data.
The MAC algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function MAC_Bytes Lib "diCryptoSys.dll" 
(ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpMessage As Byte, 
ByVal nMsgLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal nOptions As Long) As Long`

`nRet = MAC_Bytes(lpOutput(0), nOutBytes, abMessage(0), nMsgLen, abKey(0), nKeyLen, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  MAC_Bytes(unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive the MAC value.

*nOutBytes*
:   [in] size of output buffer in bytes.

*lpMessage*
:   [in] byte array containing the message (input) data

*nMsgLen*
:   [in] length of the input data in bytes.

*lpKey*
:   [in] byte array containing the key

*nKeyLen*
:   [in] length of the key in bytes.

*nOptions*
:   [in] Option flags. Select one of:  

**HMAC algorithms:** 

`API_HMAC_SHA1` (0) to use HMAC-SHA-1 (default)  

`API_HMAC_SHA224` to use HMAC-SHA-224  

`API_HMAC_SHA256` to use HMAC-SHA-256  

`API_HMAC_SHA384` to use HMAC-SHA-384  

`API_HMAC_SHA512` to use HMAC-SHA-512  

`API_HMAC_MD5` to use HMAC-MD5 (legacy)  

`API_HMAC_RMD160` to use HMAC-RIPEMD160  

`API_HMAC_SHA3_224` to use HMAC-SHA3-224  

`API_HMAC_SHA3_256` to use HMAC-SHA3-256  

`API_HMAC_SHA3_384` to use HMAC-SHA3-384  

`API_HMAC_SHA3_512` to use HMAC-SHA3-512  

**CMAC algorithms:** 

`API_CMAC_TDEA`  to use the Triple DES (DES-EDE) block cipher  

`API_CMAC_AES128`  to use the AES-128 block cipher  

`API_CMAC_AES192` to use the AES-192 block cipher  

`API_CMAC_AES256` to use the AES-256 block cipher  

**Other:** 

`API_MAC_POLY1305` to use the Poly1305 algorithm [*New in v5.0*]  

`API_KMAC_128` to use KMAC128 with a fixed-length output of 256 bits (32 bytes) [*New in v5.3*]  

`API_KMAC_256` to use KMAC256 with a fixed-length output of 512 bits (64 bytes) [*New in v5.3*]

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output array; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [macBytes](#VB_macBytes)(lpMessage() As Byte, lpKey() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Mac.BytesFromBytes Method](#M_Mac_BytesFromBytes)  

### Python Equivalent

`static [Mac.data](https://cryptosys.net/pydocapi/class-stubs/Mac.html#crsysapi.Mac.data "External link")(data, key, alg=Alg.HMAC_SHA1)`

### Remarks

Specify a zero *nOutBytes* parameter to find out the required length of the output array.
The maximum possible output length is `API_MAX_MAC_BYTES`.
The final MAC value will be truncated to the specified length if less than the expected size 
(except for KMAC which *must not* be truncated).

To use KMAC with variable-length output or a customization string, use [`PRF_Bytes`](#PRF_Bytes).

### Example (VBA core function)

```

Dim abData() As Byte
Dim abKey() As Byte
Dim nDataLen As Long
Dim nKeyLen As Long
Dim abDigest() As Byte
Dim nDigLen As Long
Dim nRet As Long
Dim i As Long

' Test case 4 from RFC 2202 and RFC 4231
' key =           0x0102030405060708090a0b0c0d0e0f10111213141516171819
' key_len         25
' data =          0xcd repeated 50 times
' data_len =      50

nKeyLen = 25
ReDim abKey(nKeyLen - 1)
For i = 0 To nKeyLen - 1
    abKey(i) = CByte(i + 1)
Next
Debug.Print "Key=" & cnvHexStrFromBytes(abKey)
nDataLen = 50
ReDim abData(nDataLen - 1)
For i = 0 To nDataLen - 1
    abData(i) = &HCD
Next

' Compute default HMAC (HMAC-SHA-1)
nDigLen = API_SHA1_BYTES
ReDim abDigest(nDigLen - 1)
nRet = MAC_Bytes(abDigest(0), nDigLen, abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_SHA1)
If nRet <= 0 Then Exit Sub ' ERROR
Debug.Print "HMAC-SHA-1  =" & cnvHexStrFromBytes(abDigest)
Debug.Print "CORRECT     =" & "4c9007f4026250c6bc8414f9bf50c86c2d7235da"

' Compute HMAC-MD5
nDigLen = API_MD5_BYTES
ReDim abDigest(nDigLen - 1)
nRet = MAC_Bytes(abDigest(0), nDigLen, abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_MD5)
If nRet <= 0 Then Exit Sub ' ERROR
Debug.Print "HMAC-MD5    =" & cnvHexStrFromBytes(abDigest)
Debug.Print "CORRECT     =" & "697eaf0aca3a3aea3a75164746ffaa79"

' Compute HMAC-SHA-256
nDigLen = API_SHA256_BYTES
ReDim abDigest(nDigLen - 1)
nRet = MAC_Bytes(abDigest(0), nDigLen, abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_SHA256)
If nRet <= 0 Then Exit Sub ' ERROR
Debug.Print "HMAC-SHA-256=" & cnvHexStrFromBytes(abDigest)
Debug.Print "CORRECT     =" & "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"

```

The above example should produce the following output:

```

Key=0102030405060708090A0B0C0D0E0F10111213141516171819
HMAC-SHA-1  =4C9007F4026250C6BC8414F9BF50C86C2D7235DA
CORRECT     =4c9007f4026250c6bc8414f9bf50c86c2d7235da
HMAC-MD5    =697EAF0ACA3A3AEA3A75164746FFAA79
CORRECT     =697eaf0aca3a3aea3a75164746ffaa79
HMAC-SHA-256=82558A389A443C0EA4CC819899F2083A85F0FAA3E578F8077A2E3FF46729665B
CORRECT     =82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
Dim lpKey() As Byte
lpMessage = StrConv("what do ya want for nothing?", vbFromUnicode)
lpKey = StrConv("Jefe", vbFromUnicode)

Debug.Print "OK:" & vbCrLf & "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
Debug.Print macHexFromBytes(lpMessage, lpKey, API_HMAC_SHA256)
Debug.Print macHexFromHex(cnvHexStrFromBytes(lpMessage), cnvHexStrFromBytes(lpKey), API_HMAC_SHA256)
Debug.Print cnvHexStrFromBytes(macBytes(lpMessage, lpKey, API_HMAC_SHA256))
```

### See Also

[`MAC_HexFromBytes`](#MAC_HexFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_CodeLength"></a>MAC_CodeLength
-----------------------------------------

Returns the number of bytes in the output for the algorithm defined in the current MAC context.

### VBA/VB6 Syntax

`Public Declare Function MAC_CodeLength Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nLen = MAC_CodeLength(hContext)`

### C/C++ Syntax

`long _stdcall MAC_CodeLength(long hContext);`

### Parameters

*hContext*

:   [in] handle to the current MAC context.

### Returns (VBA/C)

The number of bytes in the hash output for the algorithm defined in the current MAC context, 
or a negative [error code](#errorcodes).

### .NET Equivalent

### Remarks

### Example

```

Dim hContext As Long
hContext = MAC_Init(lpKey(0), cnvBytesLen(lpKey), API_HMAC_SHA256)
Debug.Print "MAC_CodeLength = " & MAC_CodeLength(hContext)

```

```

MAC_CodeLength = 32

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_Final"></a>MAC_Final
-------------------------------

Returns the final message digest value from the MAC context.

### VBA/VB6 Syntax

`Public Declare Function MAC_Final Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutLen As Long, ByVal hContext As Long) As Long`

`nRet = MAC_Final(lpOutput(0), nOutLen, hContext)` 

### C/C++ Syntax

`long __stdcall MAC_Final(unsigned char *lpOutput, long nOutLen, long hContext);`

### Parameters

*lpOutput*
:   [out] array to receive message digest.

*nOutLen*
:   [in] length in bytes of the output array.

*hContext*
:   [in] handle to the current MAC context.

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output array;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [macFinal](#VB_macFinal)(hContext As Long) As Byte()`

### .NET Equivalent

[Mac.Final Method](#M_Mac_Final)  

### C++ (STL) Equivalent

`bvec_t [crsysapi::Mac::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a2f0784f5560451049e9eda267e623da9 "External link") ()`

### Remarks

Computes the result of all [`MAC_AddBytes`](#MAC_AddBytes) calls since [`MAC_Init`](#MAC_Init).
Once called, the context is destroyed.

### Example

See [`MAC_AddBytes`](#MAC_AddBytes).

### See Also

[`MAC_Init`](#MAC_Init)
[`MAC_AddBytes`](#MAC_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_HexFromBytes"></a>MAC_HexFromBytes
---------------------------------------------

Creates a keyed-hash based message authentication code (HMAC) 
 in hexadecimal format from byte data.
The hash algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function MAC_HexFromBytes Lib "diCryptoSys.dll" 
(ByVal strOutput As String, ByVal nOutChars As Long, ByRef lpMessage As Byte, 
ByVal nMsgLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal nOptions As Long) As Long`

`nRet = MAC_HexFromBytes(strOutput, nOutChars, abMessage(0), nMsgLen, abKey(0), nKeyLen, nOptions)`

### C/C++ Syntax

`long __stdcall  MAC_HexFromBytes(char *szOutput, long nMaxChars, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive output in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*lpMessage*
:   [in] array containing the message data in a byte array

*nMsgLen*
:   [in] specifying length of the message data in bytes.

*lpKey*
:   [in] array containing the key in a byte array

*nKeyLen*
:   [in] specifying length of the key in bytes.

*nOptions*
:   [in] Option flags. Select one of:  

**HMAC algorithms:** 

`API_HMAC_SHA1` (0) to use the SHA-1 hash algorithm (default)  

`API_HMAC_SHA224` to use the SHA-224 algorithm  

`API_HMAC_SHA256` to use the SHA-256 algorithm  

`API_HMAC_SHA384` to use the SHA-384 algorithm  

`API_HMAC_SHA512` to use the SHA-512 algorithm  

`API_HMAC_MD5` to use the MD5 algorithm  

`API_HMAC_RMD160` to use the RIPEMD-160 algorithm  

`API_HMAC_SHA3_224` to use the SHA-3-224 algorithm  

`API_HMAC_SHA3_256` to use the SHA-3-256 algorithm  

`API_HMAC_SHA3_384` to use the SHA-3-384 algorithm  

`API_HMAC_SHA3_512` to use the SHA-3-512 algorithm  

**CMAC algorithms:** 

`API_CMAC_TDEA`  to use the Triple DES (DES-EDE) block cipher  

`API_CMAC_AES128`  to use the AES-128 block cipher  

`API_CMAC_AES192` to use the AES-192 block cipher  

`API_CMAC_AES256` to use the AES-256 block cipher  

**Other:** 

`API_MAC_POLY1305` to use the Poly1305 algorithm [*New in v5.0*]  

`API_KMAC_128` to use KMAC128 with a fixed-length output of 256 bits (32 bytes) [*New in v5.3*]  

`API_KMAC_256` to use KMAC256 with a fixed-length output of 512 bits (64 bytes) [*New in v5.3*]

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [macHexFromBytes](#VB_macHexFromBytes)(lpMessage() As Byte, lpKey() As Byte, nOptions As Long) As String`

### .NET Equivalent

[Mac.HexFromBytes Method](#M_Mac_HexFromBytes)  

### Python Equivalent

`static [Mac.hex_from_data](https://cryptosys.net/pydocapi/class-stubs/Mac.html#crsysapi.Mac.hex_from_data "External link")(data, key, alg=Alg.HMAC_SHA1)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The maximum number of characters is `API_MAX_MAC_CHARS`.
The final digest will be truncated to the specified length if less than the
expected size (except for KMAC which *must not* be truncated).

### Examples

```

Dim strData As String
Dim strKey As String
Dim abData() As Byte
Dim abKey() As Byte
Dim nDataLen As Long
Dim nKeyLen As Long
Dim strDigest As String
Dim nRet As Long

' Test case 2 from RFC 2202 and RFC 4231
strData = "what do ya want for nothing?"
strKey = "Jefe"

' Convert message and key into Byte format
abData = StrConv(strData, vbFromUnicode)
abKey = StrConv(strKey, vbFromUnicode)
nDataLen = UBound(abData) - LBound(abData) + 1
nKeyLen = UBound(abKey) - LBound(abKey) + 1

' Dimension the output string to receive the digest
strDigest = String(API_MAX_HASH_CHARS, " ")

' Compute default HMAC (HMAC-SHA-1)
nRet = MAC_HexFromBytes(strDigest, Len(strDigest), abData(0), nDataLen, abKey(0), nKeyLen, 0)
If nRet <= 0 Then Exit Sub ' ERROR
strDigest = Left(strDigest, nRet)
Debug.Print "HMAC-SHA-1  =" & strDigest
Debug.Print "CORRECT     =" & "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"

' Compute HMAC-MD5
strDigest = String(API_MAX_HASH_CHARS, " ")
nRet = MAC_HexFromBytes(strDigest, Len(strDigest), abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_MD5)
If nRet <= 0 Then Exit Sub ' ERROR
strDigest = Left(strDigest, nRet)
Debug.Print "HMAC-MD5    =" & strDigest
Debug.Print "CORRECT     =" & "750c783e6ab0b503eaa86e310a5db738"

' Compute HMAC-SHA-256
strDigest = String(API_MAX_HASH_CHARS, " ")
nRet = MAC_HexFromBytes(strDigest, Len(strDigest), abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_SHA256)
If nRet <= 0 Then Exit Sub ' ERROR
strDigest = Left(strDigest, nRet)
Debug.Print "HMAC-SHA-256=" & strDigest
Debug.Print "CORRECT     =" & "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"

' Compute HMAC-SHA-512
strDigest = String(API_MAX_HASH_CHARS, " ")
nRet = MAC_HexFromBytes(strDigest, Len(strDigest), abData(0), nDataLen, abKey(0), nKeyLen, API_HASH_SHA512)
If nRet <= 0 Then Exit Sub ' ERROR
strDigest = Left(strDigest, nRet)
Debug.Print "HMAC-SHA-512=" & strDigest
Debug.Print "CORRECT     =" _
& "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554" _
& "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" _

```

The above example should produce the following output:

```

HMAC-SHA-1  =effcdf6ae5eb2fa2d27416d5f184df9c259a7c79
CORRECT     =effcdf6ae5eb2fa2d27416d5f184df9c259a7c79
HMAC-MD5    =750c783e6ab0b503eaa86e310a5db738
CORRECT     =750c783e6ab0b503eaa86e310a5db738
HMAC-SHA-256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
CORRECT     =5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
HMAC-SHA-512=164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737
CORRECT     =164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
Dim lpKey() As Byte
lpMessage = StrConv("what do ya want for nothing?", vbFromUnicode)
lpKey = StrConv("Jefe", vbFromUnicode)

Debug.Print "OK:" & vbCrLf & "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
Debug.Print macHexFromBytes(lpMessage, lpKey, API_HMAC_SHA256)
Debug.Print macHexFromHex(cnvHexStrFromBytes(lpMessage), cnvHexStrFromBytes(lpKey), API_HMAC_SHA256)
Debug.Print cnvHexStrFromBytes(macBytes(lpMessage, lpKey, API_HMAC_SHA256))
```

### See Also

[`MAC_Bytes`](#MAC_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_HexFromHex"></a>MAC_HexFromHex
-----------------------------------------

Creates a message authentication code (MAC) 
in hexadecimal format from hex-encoded data and a hex-encoded key.
The MAC algorithm to use is passed in the options parameter.

### VBA/VB6 Syntax

`Public Declare Function MAC_HexFromHex Lib "diCryptoSys.dll" 
(ByVal strOutput As String, ByVal nOutChars As Long, 
ByVal strMsgHex As String, ByVal strKeyHex As String, ByVal nOptions As Long) As Long`

`nRet = MAC_HexFromHex(strOutput, nOutChars, strMsgHex, strKeyHex, nOptions)`

### C/C++ Syntax

`long __stdcall  MAC_HexFromHex(char *szOutput, long nMaxChars, const char *szMsgHex, const char *szKeyHex, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive output in hexadecimal format.

*nMaxChars*
:   [in] specifying the maximum number of characters to be received.

*szMsgHex*
:   [in] array containing the message data in hexadecimal-encoded format.

*szKeyHex*
:   [in] array containing the key in hexadecimal-encoded format.

*nOptions*
:   [in] Option flags. Select one of:  

**HMAC algorithms:** 

`API_HMAC_SHA1` (0) to use the SHA-1 hash algorithm (default)  

`API_HMAC_SHA224` to use the SHA-224 algorithm  

`API_HMAC_SHA256` to use the SHA-256 algorithm  

`API_HMAC_SHA384` to use the SHA-384 algorithm  

`API_HMAC_SHA512` to use the SHA-512 algorithm  

`API_HMAC_MD5` to use the MD5 algorithm  

`API_HMAC_RMD160` to use the RIPEMD-160 algorithm  

`API_HMAC_SHA3_224` to use the SHA-3-224 algorithm  

`API_HMAC_SHA3_256` to use the SHA-3-256 algorithm  

`API_HMAC_SHA3_384` to use the SHA-3-384 algorithm  

`API_HMAC_SHA3_512` to use the SHA-3-512 algorithm  

**CMAC algorithms:** 

`API_CMAC_TDEA`  to use the Triple DES (DES-EDE) block cipher  

`API_CMAC_AES128`  to use the AES-128 block cipher  

`API_CMAC_AES192` to use the AES-192 block cipher  

`API_CMAC_AES256` to use the AES-256 block cipher  

**Other:** 

`API_MAC_POLY1305` to use the Poly1305 algorithm [*New in v5.0*]  

`API_KMAC_128` to use KMAC128 with a fixed-length output of 256 bits (32 bytes) [*New in v5.3*]  

`API_KMAC_256` to use KMAC256 with a fixed-length output of 512 bits (64 bytes) [*New in v5.3*]

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [macHexFromHex](#VB_macHexFromHex)(szMsgHex As String, szKeyHex As String, nOptions As Long) As String`

### .NET Equivalent

[Mac.HexFromHex Method](#M_Mac_HexFromHex)  

### Python Equivalent

`static [Mac.hex_from_hex](https://cryptosys.net/pydocapi/class-stubs/Mac.html#crsysapi.Mac.hex_from_hex "External link")(datahex, keyhex, alg=Alg.HMAC_SHA1)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 

Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The maximum number of characters is `API_MAX_MAC_CHARS`.
 
The final digest will be truncated to the specified length if less than the expected size 
(except for KMAC which *must not* be truncated). 

### Example (VBA core function)

```

Dim strKeyHex As String
Dim strMsgHex As String
Dim strMAC As String
Dim nRet As Long

' SP800-38: compute CMAC_AES-128 on Example 2: Mlen = 128
strKeyHex = "2b7e151628aed2a6abf7158809cf4f3c"
strMsgHex = "6bc1bee22e409f96e93d7e117393172a"
' Output MAC size in hex is double the block length of the cipher
strMAC = String(API_BLK_AES_BYTES * 2, " ")
nRet = MAC_HexFromHex(strMAC, Len(strMAC), strMsgHex, strKeyHex, API_CMAC_AES128)
If nRet > 0 Then
    Debug.Print "CMAC-AES-128(K128, M128)=" & Left$(strMAC, nRet)
Else
    Debug.Print "Error code " & nRet
End If

```

This should produce the output

```

CMAC-AES-128(K128, M128)=070a16b46b4d4144f79bdd9dd04a287c

```

Example using Poly1305 algorithm.

```

' Ref: Test vector from `draft-irtf-cfrg-chacha20-poly1305-06.txt`
Dim nRet As Long
Dim strDigest As String
Dim strMsgHex As String

' Convert ASCII message string to hex format
strMsgHex = cnvHexStrFromString("Cryptographic Forum Research Group")
' Dimension digest string to receive 32 characters
strDigest = String(API_POLY1305_CHARS, " ")
' Create authentication tag using 256-bit key material
nRet = MAC_HexFromHex(strDigest, Len(strDigest), strMsgHex, _
    "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b", API_MAC_POLY1305)
Debug.Print "Poly1305 Tag: " & strDigest

```

This should produce the output

```

Poly1305 Tag: a8061dc1305136c6c22b8baf0c0127a9

```

Example using HMAC-SHA3-256.

```

' Ref: NIST Computer Security Division
' "Keyed-Hash Message Authentication Code (HMAC) - using SHA3-256"
' `HMAC_SHA3-256.pdf` 2016-03-28
Dim strText As String
Dim strKeyHex As String
Dim strMsgHex As String
Dim strMAC As String
Dim nLen As Long
'Sample #1 Block length = 136, Key length = 32, Tag length = 32
strText = "Sample message for keylen<blocklen"
strKeyHex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
strMsgHex = cnvHexStrFromString(strText)
Debug.Print "Text is " & strMsgHex
Debug.Print "Key is " & strKeyHex
' Get required output length
nLen = MAC_HexFromHex("", 0, strMsgHex, strKeyHex, API_HASH_SHA3_256)
strMAC = String(nLen, " ")
nLen = MAC_HexFromHex(strMAC, Len(strMAC), strMsgHex, strKeyHex, API_HASH_SHA3_256)
Debug.Print "Mac is " & strMAC

```

```

Text is 53616D706C65206D65737361676520666F72206B65796C656E3C626C6F636B6C656E
Key is 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
Mac is 4fe8e202c4f058e8dddc23d8c34e467343e23555e24fc2f025d598f558f67205

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
Dim lpKey() As Byte
lpMessage = StrConv("what do ya want for nothing?", vbFromUnicode)
lpKey = StrConv("Jefe", vbFromUnicode)

Debug.Print "OK:" & vbCrLf & "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
Debug.Print macHexFromBytes(lpMessage, lpKey, API_HMAC_SHA256)
Debug.Print macHexFromHex(cnvHexStrFromBytes(lpMessage), cnvHexStrFromBytes(lpKey), API_HMAC_SHA256)
Debug.Print cnvHexStrFromBytes(macBytes(lpMessage, lpKey, API_HMAC_SHA256))
```

### See Also

[`MAC_Bytes`](#MAC_Bytes)
[`MAC_HexFromBytes`](#MAC_HexFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_Init"></a>MAC_Init
-----------------------------

Initialises the MAC context ready for subsequent calls with
`MAC_AddBytes` and `MAC_Final`.

### VBA/VB6 Syntax

`Public Declare Function MAC_Init Lib "diCryptoSys.dll" (ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal nAlg As Long) As Long`

`hContext = MAC_Init(lpKey, nKeyLen, nAlg)`

### C/C++ Syntax

`long __stdcall MAC_Init(const void *lpKey, long nKeyLen, long nAlg);`

### Parameters

*lpKey*
:   [in] Key in byte format.

*nKeyLen*
:   [in] Length of key in bytes.

*nAlg*
:   [in] Algorithm to be used. Select one of:  

`API_HMAC_SHA1` (0) to use the HMAC-SHA-1 algorithm (default)  

`API_HMAC_SHA224` to use the HMAC-SHA-224 algorithm  

`API_HMAC_SHA256` to use the HMAC-SHA-256 algorithm  

`API_HMAC_SHA384` to use the HMAC-SHA-384 algorithm  

`API_HMAC_SHA512` to use the HMAC-SHA-512 algorithm

### Returns (VBA/C)

Non-zero handle of the MAC context, or *zero* if an error occurs.

### VBA Wrapper Syntax

`Public Function [macInit](#VB_macInit)(lpKey() As Byte, nAlg As Long) As Long`

### .NET Equivalent

[Mac.Init Method](#M_Mac_Init)  

### C++ (STL) Equivalent

`bool [crsysapi::Mac::Init](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a80b29ab03fc8d9c07a20a7838552efa8 "External link") (bvec_t key, Alg alg)`

### Remarks

Only the HMAC-SHA-1 and HMAC-SHA-2 families of MAC algorithms are currently supported.
While the context handle is valid, add data to be digested in blocks of any length using [`MAC_AddBytes`](#MAC_AddBytes).
VBA users can use the wrapper functions `macAddBytes` and `macAddString`.

### Example

See [`MAC_AddBytes`](#MAC_AddBytes).

### See Also

[`MAC_AddBytes`](#MAC_AddBytes)
[`MAC_Final`](#MAC_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MAC_Reset"></a>MAC_Reset
-------------------------------

Resets the MAC context.

### VBA/VB6 Syntax

`Public Declare Function MAC_Reset Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = MAC_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  MAC_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the MAC context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Mac.Reset Method](#M_Mac_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

### See Also

[`MAC_Init`](#MAC_Init)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_AddBytes"></a>MD5_AddBytes
-------------------------------------

Adds an array of bytes to the digest.

### VBA/VB6 Syntax

`Public Declare Function MD5_AddBytes Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = MD5_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  MD5_AddBytes(long hContext, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the MD5 context.

*lpData*
:   [in] array containing the next part of the message
to be hashed.

*nDataLen*
:   [in] containing the number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.AddData Method](#M_Md5_AddData_Byte) (Byte[])  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `MD5_Init`. This function may be called many times before creating
the final message digest with `MD5_HexDigest`.
`MD5_AddString` may also be called.

### Example

This example creates the hash of the three-character string "abc" using a mixture of calls
to `MD5_AddBytes` and `MD5_AddString`.

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long
    Dim abData(2) As Byte

    ' Set context handle
    hContext = MD5_Init()
    ' Remember to check for an invalid handle
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Set up a test array of bytes
    abData(0) = Asc("a")
    abData(1) = &H62    ' same as Asc("b")
    ' Add mixture of bytes and strings
    nRet = MD5_AddBytes(hContext, abData(0), 2)
    nRet = MD5_AddString(hContext, "c")

    ' Set strDigest to be 32 chars
    strDigest = String(32, " ")
    nRet = MD5_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

900150983cd24fb0d6963f7d28e17f72

```

### See Also

[`MD5_Init`](#MD5_Init)
[`MD5_AddString`](#MD5_AddString)
[`MD5_HexDigest`](#MD5_HexDigest)
[`MD5_Reset`](#MD5_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_AddString"></a>MD5_AddString
---------------------------------------

Adds a string of ascii characters to the digest.

### VBA/VB6 Syntax

`Public Declare Function MD5_AddString Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strMessage As String) As Long`

`nRet = MD5_AddString(hContext, strMessage)`

### C/C++ Syntax

`long __stdcall  MD5_AddString(long hContext, const char *szMessage);`

### Parameters

*hContext*
:   [in] handle to the MD5 context.

*szMessage*
:   [in] containing the next part of the message
to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.AddData Method](#M_Md5_AddData_String) (String)  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `MD5_Init`. This function may be called many times before creating
the final message digest with `MD5_HexDigest`
This function should only be used to hash "printable" strings.
To hash a string that contains binary characters, such as ascii zero, use `MD5_AddBytes`.

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long
    Dim i As Long
    Dim sA1000 As String

    ' Set context handle
    hContext = MD5_Init()
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Create a string of 1000 'a's
    sA1000 = String(1000, "a")

    ' Add 1000 times => one million repetitions of "a"
    For i = 1 To 1000
        nRet = MD5_AddString(hContext, sA1000)
    Next

    ' Set strDigest to be 32 chars - don't forget!!
    strDigest = String(32, " ")
    nRet = MD5_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

7707d6ae4e027c70eea2a935c2296f21

```

Note that the actual value of the handle is not important, just that it should not be zero.

### See Also

[`MD5_Init`](#MD5_Init)
[`MD5_AddBytes`](#MD5_AddBytes)
[`MD5_HexDigest`](#MD5_HexDigest)
[`MD5_Reset`](#MD5_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_BytesHash"></a>MD5_BytesHash
---------------------------------------

Creates an MD5 message digest in `Byte` array format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function MD5_BytesHash Lib "diCryptoSys.dll"
    (ByRef lpDigest As Byte, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = MD5_BytesHash(abDigest(0), abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.BytesHash Method](#M_Md5_BytesHash)  

### C/C++ Syntax

`long __stdcall  MD5_BytesHash(unsigned char *digest, const unsigned char *lpData, long nDataLen);`

### Parameters

*digest*
:   [out] array to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Remarks

This function differs from other MD5 functions in that it creates a digest in `Byte` array
format. This is particularly useful when you need to carry out repeated hash operations.
*lpDigest* must be at least 16 (`API_MAX_MD5_BYTES`) bytes long. 

### Examples

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(15) As Byte ' Create 16-byte array to receive digest
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute MD5 hash digest
    nRet = MD5_BytesHash(abDigest(0), abData(0), 3)
    
    ' Print resulting bytes in hex format
    Debug.Print nRet; cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

 0 900150983CD24FB0D6963F7D28E17F72

```

This second example shows how to carry out repeated hashes of the digest.

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(15) As Byte ' Create 16-byte array to receive digest
    Dim i As Integer
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute MD5 hash digest of input
    nRet = MD5_BytesHash(abDigest(0), abData(0), 3)
    
    ' Now carry out repeated hashes of the 16-byte-long digest
    For i = 2 To 1000
        nRet = MD5_BytesHash(abDigest(0), abDigest(0), 16)
    Next
   
    ' Print H(1000) in hex format
    Debug.Print cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

1375514E02C36AAE265B2FE20CCADAFB

```

### See Also

[`SHA1_BytesHash`](#SHA1_BytesHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_BytesHexHash"></a>MD5_BytesHexHash
---------------------------------------------

Creates an MD5 message digest in hexadecimal format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function MD5_BytesHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = MD5_BytesHexHash(strDigest, abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  MD5_BytesHexHash(char *szDigest, const unsigned char *lpData, long nDataLen);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.HexHash Method](#M_Md5_HexHash_Byte) (Byte[])  

### COM/ASP Equivalent

`md5.HexHexHash  

Public Function HexHexHash(ByVal strHexData As String) As String`

See [`md5.HexHexHash`](#x_hexhexhash).

### Remarks

*szDigest* must be at least 32 (`API_MAX_MD5_CHARS`) characters long (33 in a C program).

### Example

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    ' Alternative way of making sure string is 32 chars long
    Dim strDigest As String * 32

    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")

    nRet = MD5_BytesHexHash(strDigest, abData(0), 3)
    Debug.Print nRet; strDigest

```

This should result in output as follows:

```

 0 900150983cd24fb0d6963f7d28e17f72

```

### See Also

[`MD5_StringHexHash`](#MD5_StringHexHash)
[`MD5_FileHexHash`](#MD5_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_FileHexHash"></a>MD5_FileHexHash
-------------------------------------------

Creates an MD5 message digest in hexadecimal format
from a file.

### VBA/VB6 Syntax

`Public Declare Function MD5_FileHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strFileName As String, ByVal strMode As String) As Long`

`nRet = MD5_FileHexHash(strDigest, strFileName, strMode)`

### C/C++ Syntax

`long __stdcall  MD5_FileHexHash(char *szDigest, const char *szFileName, const char *szMode);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szFileName*
:   [in] with full path name of file.

*szMode*
:   [in] to set mode: "t" or "b"

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.FileHexHash Method](#M_Md5_FileHexHash)  

[Md5.FileTextHexHash Method](#M_Md5_FileTextHexHash)  

### COM/ASP Equivalent

`md5.FileHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String  

md5.FileTextHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String`

See [md5.FileHexHash](#x_filehexhash), [`md5.FileTextHexHash`](#x_filetexthexhash).

### Remarks

*szDigest* must be at least 32 (`API_MAX_MD5_CHARS`) characters long (33 in a C program).
Setting *szMode* equal
to "t" or "T" will hash file in "text" mode treating a CR-LF pair as a single newline character.
Setting *szMode* equal to "b" or "B" will hash file in "binary" mode treating
CR-LF as two binary characters (default).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim strFileName As String

    strFileName = "hello.txt"
    ' Set strDigest to be 32 chars
    strDigest = String(32, " ")
    ' Make md5sum in text mode (treating CR-LF as single NL)
    nRet = MD5_FileHexHash(strDigest, strFileName, "t")
    Debug.Print "t " & nRet; strDigest
    ' Do in binary mode (treating CR-LF as two binary bytes)
    nRet = MD5_FileHexHash(strDigest, strFileName, "b")
    Debug.Print "b " & nRet; strDigest

```

For a 13-byte text file "hello.txt" in the default directory containing the 11 characters
"hello world" followed by CR-LF this
should result in output as follows:

```

t  0 6f5902ac237024bdd0c176cb93063dc4
b  0 a0f2a3c1dcd5b1cac71bf0c03f2ff1bd

```

### See Also

[`MD5_StringHexHash`](#MD5_StringHexHash)
[`MD5_BytesHexHash`](#MD5_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_HexDigest"></a>MD5_HexDigest
---------------------------------------

Returns the final message digest value as a hex string.

### VBA/VB6 Syntax

`Public Declare Function MD5_HexDigest Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal hContext As Long) As Long`

`nRet = MD5_HexDigest(strDigest, hContext)`

### C/C++ Syntax

`long __stdcall  MD5_HexDigest(char *szDigest, long hContext);`

### Parameters

*szDigest*
:   [out] variable long enough to receive the final message digest.

*hContext*
:   [in] handle to the MD5 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.HexDigest Method](#M_Md5_HexDigest)  

### Remarks

This operation delivers the result of Add operations since the last Init or Reset operation.
The handle to the context *hContext* must have been set up with a
prior call to `MD5_Init`. 
The string variable *szDigest* must
have been set up with at least 32 (`API_MAX_MD5_CHARS`) characters (33 in a C program) 
to receive the digest value in hex format.
Note that this digest operation is a destructive, read-once operation.
Once it has been performed,
the context must be reset before being used to calculate another digest value.

### Example

See [`MD5_AddString`](#MD5_AddString) and
[`MD5_AddBytes`](#MD5_AddBytes)

### See Also

[`MD5_Init`](#MD5_Init)
[`MD5_AddString`](#MD5_AddString)
[`MD5_AddBytes`](#MD5_AddBytes)
[`MD5_Reset`](#MD5_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_Hmac"></a>MD5_Hmac
-----------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the MD5 hash function.

### VBA/VB6 Syntax

`Public Declare Function MD5_Hmac Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long) As Long`

`nRet = MD5_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  MD5_Hmac(char *szDigest, const unsigned char *textBytes, long textLen, const unsigned char *lpKeyBytes, long keyLen);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*textBytes*
:   [in] array containing the text of the message.

*textLen*
:   [in] containing the number of bytes in the array

*lpKeyBytes*
:   [in] array containing the key.

*keyLen*
:   [in] containing the number of bytes in the key

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.Hmac Method](#M_Md5_Hmac_ByteByte) (Byte[], Byte[])  

### Remarks

*szDigest* must be at least 32 (`API_MAX_MD5_CHARS`) characters long (33 in a C program).

### Example

This example reproduces the three test vectors from RFC 2104.

```

    Dim nRet As Long
    Dim abData() As Byte
    Dim abKey() As Byte
    Dim i As Integer
    Dim nDataLen As Long, nKeyLen As Long
    Dim strDigest As String * 32

    ' Test No 1.
    ' Set key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HB
    Next
    ' Convert string to byte array
    abData() = StrConv("Hi There", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    ' Create HMAC digest
    nRet = MD5_Hmac(strDigest, abData(0), nDataLen, abKey(0), 16)
    Debug.Print 1; nRet; strDigest

    ' Test No 2.
    abKey() = StrConv("Jefe", vbFromUnicode)
    nKeyLen = UBound(abKey) + 1
    abData() = StrConv("what do ya want for nothing?", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    nRet = MD5_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
    Debug.Print 2; nRet; strDigest

    ' Test No 3.
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HAA
    Next
    ReDim abData(49)
    For i = 0 To 49
        abData(i) = &HDD
    Next
    nRet = MD5_Hmac(strDigest, abData(0), 50, abKey(0), 16)
    Debug.Print 3; nRet; strDigest

```

This should result in output as follows:

```

 1  0 9294727a3638bb1c13f48ef8158bfc9d
 2  0 750c783e6ab0b503eaa86e310a5db738
 3  0 56be34521d144c88dbb8c733f0e8b3f6

```

### See Also

-

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_HmacHex"></a>MD5_HmacHex
-----------------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the MD5 hash function, passing its arguments in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function MD5_HmacHex Lib "diCryptoSys.dll" 
    (ByVal strDigest As String, ByVal strHexData As String, 
    ByVal strHexKey As String) As Long`

`nRet = MD5_HmacHex(strDigest, strHexData, strHexKey)`

### C/C++ Syntax

`long __stdcall  MD5_HmacHex(char *szDigest, const char *szHexText, const char *szHexKey);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*szHexText*
:   [in] containing the text of the message in hexadecimal format.

*szHexKey*
:   [in] containing the key in hexadecimal format.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.Hmac Method](#M_Md5_Hmac_StringString) (String, String)  

### COM/ASP Equivalent

`md5.HmacHex  

Public Function HmacHex(ByVal strHexText As String, ByVal strHexKey As String) As String`

See [`md5.HmacHex`](#x_hmachex).

### Remarks

*szDigest* must be at least 32 (`API_MAX_MD5_CHARS`) characters long (33 in a C program).
*szData* and *szKey* are expected to be an even number of characters long, 
i.e. representing complete byte values. Any trailing odd character will be ignored.

### Example

```

'    Test No 1. from RFC 2104
'    key =         0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
'    key_len =     16 bytes
'    Data = "Hi There"
'    data_len =    8  bytes
'    digest =      0x9294727a3638bb1c13f48ef8158bfc9d

    Dim nRet As Long
    Dim strDigest As String * 32
    Dim strMessage As String
    Dim sHexMsg As String
    Dim sCorrect As String
    
    sCorrect = "9294727a3638bb1c13f48ef8158bfc9d"
    
    ' Convert data to hex format
    sHexMsg = cnvHexStrFromString("Hi There")
    nRet = MD5_HmacHex(strDigest, sHexMsg, "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
    Debug.Print "Digest =" & strDigest
    Debug.Print "Correct=" & sCorrect
    Debug.Assert (strDigest = sCorrect)

```

This should result in output as follows:

```

Digest =9294727a3638bb1c13f48ef8158bfc9d
Correct=9294727a3638bb1c13f48ef8158bfc9d

```

### See Also

[`MD5_Hmac`](#MD5_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_Init"></a>MD5_Init
-----------------------------

Initialises the MD5 context ready for subsequent calls with
`MD5_AddString`, `MD5_AddBytes`, and `MD5_HexDigest`.

### VBA/VB6 Syntax

`Public Declare Function MD5_Init Lib "diCryptoSys.dll"
    () As Long`

`Dim hContext As Long  

    hContext = MD5_Init()`

### C/C++ Syntax

`long __stdcall  MD5_Init(void);`

### Parameters

None.

### Returns (VBA/C)

non-zero handle of the MD5 context *hContext*.
Returns zero if an error occurs.

### .NET Equivalent

[Md5.Init Method](#M_Md5_Init)  

### Remarks

It is important to check for a zero context handle and stop if one occurs.

### Example

See [`MD5_HexDigest`](#MD5_HexDigest)

### See Also

[`MD5_AddString`](#MD5_AddString)
[`MD5_AddBytes`](#MD5_AddBytes)
[`MD5_HexDigest`](#MD5_HexDigest)
[`MD5_Reset`](#MD5_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_Reset"></a>MD5_Reset
-------------------------------

Resets the context.

### VBA/VB6 Syntax

`Public Declare Function MD5_Reset Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = MD5_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  MD5_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the SHA-1 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.Reset Method](#M_Md5_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

This trivial example creates a context handle and then destroys it.

```

    Dim nRet As Long
    Dim hContext As Long

    hContext = MD5_Init()
    nRet = MD5_Reset(hContext)

```

### See Also

[`MD5_Init`](#MD5_Init)
[`MD5_AddString`](#MD5_AddString)
[`MD5_AddBytes`](#MD5_AddBytes)
[`MD5_HexDigest`](#MD5_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="MD5_StringHexHash"></a>MD5_StringHexHash
-----------------------------------------------

Creates an MD5 message digest in hexadecimal format
from a message of `String` type.

### VBA/VB6 Syntax

`Public Declare Function MD5_StringHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strMessage As String) As Long`

`nRet = MD5_StringHexHash(strDigest, strMessage)`

### C/C++ Syntax

`long __stdcall  MD5_StringHexHash(char *szDigest, const char *szMessage);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szMessage*
:   [in] containing the message to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Md5.HexHash Method](#M_Md5_HexHash_String) (String)  

### COM/ASP Equivalent

`md5.StringHexHash  

Public Function StringHexHash(ByVal strData As String) As String`

See [`md5.StringHexHash`](#x_stringhexhash).

### Remarks

*szDigest* must be at least 32 (`API_MAX_MD5_CHARS`) characters long (33 in a C program).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    ' Set strDigest to be 32 chars
    strDigest = String(32, " ")
    nRet = MD5_StringHexHash(strDigest, "abc")
    Debug.Print strDigest

    nRet = MD5_StringHexHash(strDigest, _
        "abcdefghijklmnopqrstuvwxyz")
    Debug.Print strDigest

```

This should result in output as follows:

```

900150983cd24fb0d6963f7d28e17f72
c3fcd3d76192e4007dfb496cca67e13b

```

### See Also

[`MD5_FileHexHash`](#MD5_FileHexHash)
[`MD5_BytesHexHash`](#MD5_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PAD_BytesBlock"></a>PAD_BytesBlock
-----------------------------------------

Creates an input block suitably padded for encryption by a block cipher in ECB or CBC mode. 

### VBA/VB6 Syntax

`Public Declare Function PAD_BytesBlock Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutputLen As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByVal nBlockLen As Long, ByVal nOptions As Long) As Long`

`nRet = PAD_BytesBlock(lpOutput(0), nOutputLen, abInput(0), nInputLen, nBlockLen, 0)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  PAD_BytesBlock(unsigned char *lpOutput, long nOutputLen, const unsigned char *lpInput, long nBytes, long nBlkLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array to be filled with padded encryption block.

*nOutputLen*
:   [in] specifying the size of the output array in bytes.

*lpInput*
:   [in] array containing the plaintext bytes to be padded.

*nBytes*
:   [in] specifying the length of the plaintext in bytes.

*nBlkLen*
:   [in] specifying the cipher block length in bytes (8 or 16).

*nOptions*
:   [in] Option flags. Select one of:  

`API_PAD_DEFAULT` (0) to use the default PKCS5 padding 

`API_PAD_1ZERO` to use OneAndZeroes padding  

`API_PAD_AX923` to use ANSIX923 padding  

`API_PAD_W3C` to use W3C padding

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [padBytesBlock](#VB_padBytesBlock)(lpInput() As Byte, nBlkLen As Long, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Cipher.Pad Method](#M_Cipher_Pad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding)  

or use the method associated with the relevant encryption algorithm class:

[Aes128.Pad Method](#M_Aes128_Pad_Byte) (Byte[])  

[Blowfish.Pad Method](#M_Blowfish_Pad_Byte) (Byte[])  

[Des.Pad Method](#M_Des_Pad_Byte) (Byte[])  

[Tdea.Pad Method](#M_Tdea_Pad_Byte) (Byte[])  

### Python Equivalent

`static [Cipher.pad](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.pad "External link")(data, alg, pad=Pad.PKCS5)`

### Remarks

If *nOutBytes* is set to zero or *lpOutput* set to 0 (or `NULL` in C or `ByVal 0&` in VBA),
then the required number of bytes will be returned. The output is *always* longer than the input.
Only block lengths of 8 or 16 bytes are supported.
For more details of the supported padding schemes, see [Padding schemes for block ciphers](#paddingschemes).

### Example (VBA core function)

```

Dim abInput() As Byte
Dim lpOutput() As Byte
Dim nOutputLen As Long
Dim nInputLen As Long
Dim nBlockLen As Long
Dim i As Long

' Prepare test input 5 bytes long
nInputLen = 5
ReDim abInput(nInputLen - 1)
For i = 0 To nInputLen - 1
    abInput(i) = &HFF
Next
Debug.Print "Input data=0x" & cnvHexStrFromBytes(abInput)

' Find out the required length
nBlockLen = 8
nOutputLen = PAD_BytesBlock(0, 0, abInput(0), nInputLen, nBlockLen, 0)
Debug.Print "Required length is " & nOutputLen & " bytes"
' Check for error
If (nOutputLen <= 0) Then Exit Function

' Pre-dimension output
ReDim lpOutput(nOutputLen - 1)

nOutputLen = PAD_BytesBlock(lpOutput(0), nOutputLen, abInput(0), nInputLen, nBlockLen, 0)
Debug.Print "Padded data=0x" & cnvHexStrFromBytes(lpOutput)

' Now set input as padded output and remove padding
abInput = lpOutput
nInputLen = nOutputLen

' Remove padding...
' No need to query for length because we know the output will be shorter than input
' so make sure output is as long as the input
nOutputLen = nInputLen
ReDim lpOutput(nOutputLen - 1)
nOutputLen = PAD_UnpadBytes(lpOutput(0), nOutputLen, abInput(0), nInputLen, nBlockLen, 0)
Debug.Print "Unpadded length is " & nOutputLen & " bytes"
' Check for error
If (nOutputLen <= 0) Then Exit Function

' Re-dimension the output to the correct length
ReDim Preserve lpOutput(nOutputLen - 1)
Debug.Print "Unpadded data=0x" & cnvHexStrFromBytes(lpOutput)

```

This should result in output as follows:

```

Input data=0xFFFFFFFFFF
Required length is 8 bytes
Padded data=0xFFFFFFFFFF030303
Unpadded length is 5 bytes
Unpadded data=0xFFFFFFFFFF

```

### Example (VBA wrapper function)

```

Dim lpInput() As Byte
Dim lpBlock() As Byte
Dim lpUnpadded() As Byte
lpInput = cnvBytesFromHexStr("FFFFFFFFFF")
Debug.Print "Input data =  0x" & cnvHexStrFromBytes(lpInput)
lpBlock = padBytesBlock(lpInput, 8, 0)
Debug.Print "Padded data = 0x" & cnvHexStrFromBytes(lpBlock)
' Unpad
lpUnpadded = padUnpadBytes(lpBlock, 8, 0)
Debug.Print "Unpadded data = 0x" & cnvHexStrFromBytes(lpUnpadded)

' Special corner case - output is the empty string
lpBlock = cnvBytesFromHexStr("0808080808080808")
Debug.Print "Padded data = 0x" & cnvHexStrFromBytes(lpBlock)
lpUnpadded = padUnpadBytes(lpBlock, 8, 0)
Debug.Print "Unpadded data = 0x" & cnvHexStrFromBytes(lpUnpadded)
```

### See Also

[`PAD_UnpadBytes`](#PAD_UnpadBytes)
[`PAD_HexBlock`](#PAD_HexBlock)
[`PAD_UnpadHex`](#PAD_UnpadHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PAD_HexBlock"></a>PAD_HexBlock
-------------------------------------

Creates a hex-encoded input block suitably padded for encryption by a block cipher in ECB or CBC mode. 

### VBA/VB6 Syntax

`Public Declare Function PAD_HexBlock Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal strInputHex As String, ByVal nBlockLen As Long, ByVal nOptions As Long) As Long`

`nRet = PAD_HexBlock(strOutput, nMaxChars, strInput, nBlockLen, 0)`

### C/C++ Syntax

`long __stdcall  PAD_HexBlock(char *szOutput, long nMaxChars, const char *szInput, long nBlkLen, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive the hexadecimal-encoded padded encryption block.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*szInput*
:   [in] containing the hexadecimal-encoded data to be padded.

*nBlkLen*
:   [in] specifying the cipher block length in bytes (8 or 16).

*nOptions*
:   [in] Option flags. Select one of:  

`API_PAD_DEFAULT` (0) to use the default PKCS5 padding 

`API_PAD_1ZERO` to use OneAndZeroes padding  

`API_PAD_AX923` to use ANSIX923 padding  

`API_PAD_W3C` to use W3C padding

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [padHexBlock](#VB_padHexBlock)(szInput As String, nBlkLen As Long, Optional nOptions As Long = 0) As String`

### .NET Equivalent

[Cipher.Pad Method](#M_Cipher_Pad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding)  

or use the method associated with the relevant encryption algorithm class:

[Aes128.Pad Method](#M_Aes128_Pad_String) (String)  

[Blowfish.Pad Method](#M_Aes128_Pad_String) (String)  

[Des.Pad Method](#M_Aes128_Pad_String) (String)  

[Tdea.Pad Method](#M_Aes128_Pad_String) (String)  

### Python Equivalent

`static [Cipher.pad_hex](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.pad_hex "External link")(datahex, alg, pad=Pad.PKCS5)`

### Remarks

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 
Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

The output is *always* longer than the input.
Only block lengths of 8 or 16 bytes are supported.
For more details of the supported padding schemes, see [Padding schemes for block ciphers](#paddingschemes).

### Examples

An example showing the different padding schemes.

```

Dim strInputHex As String
Dim strOutputHex As String
Dim nOutChars As Long
Dim nBlockLen As Long

' Prepare test input 3 bytes long
strInputHex = "FFFFFF"
Debug.Print "Input data='" & strInputHex & "'"
' Find out the required number of characters in output (the same for all schemes)
nBlockLen = 8   ' NB block length is in bytes
nOutChars = PAD_HexBlock("", 0, strInputHex, nBlockLen, 0)
Debug.Print "Required length is " & nOutChars & " characters"
' Check for error
If (nOutChars <= 0) Then Exit Function
' Pre-dimension output
strOutputHex = String(nOutChars, " ")
' Add default padding (PKCS5Padding)
nOutChars = PAD_HexBlock(strOutputHex, Len(strOutputHex), strInputHex, nBlockLen, 0)
Debug.Print "Padded data='" & strOutputHex & "'"
' Add OneAndZeroesPadding
nOutChars = PAD_HexBlock(strOutputHex, Len(strOutputHex), strInputHex, nBlockLen, API_PAD_1ZERO)
Debug.Print "Padded data='" & strOutputHex & "'"
' Add ANSIX9.23 Padding
nOutChars = PAD_HexBlock(strOutputHex, Len(strOutputHex), strInputHex, nBlockLen, API_PAD_AX923)
Debug.Print "Padded data='" & strOutputHex & "'"	

```

```

Required length is 16 characters
Padded data='FFFFFF0505050505'
Padded data='FFFFFF8000000000'
Padded data='FFFFFF0000000005'

```

### Example (VBA wrapper function)

```

Dim strInputHex As String
Dim strOutputHex As String
strInputHex = "FFFFFF"
Debug.Print "Hex input  =" & strInputHex

strOutputHex = padHexBlock(strInputHex, 8, 0)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, 0)

strOutputHex = padHexBlock(strInputHex, 8, API_PAD_1ZERO)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, API_PAD_1ZERO)

strOutputHex = padHexBlock(strInputHex, 8, API_PAD_AX923)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, API_PAD_AX923)

```

### See Also

[`PAD_UnpadHex`](#PAD_UnpadHex)
[`PAD_BytesBlock`](#PAD_BytesBlock)
[`PAD_UnpadBytes`](#PAD_UnpadBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PAD_UnpadBytes"></a>PAD_UnpadBytes
-----------------------------------------

Removes the padding from an encryption block. 

### VBA/VB6 Syntax

`Public Declare Function PAD_UnpadBytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutputLen As Long, ByRef lpInput As Byte, ByVal nInputLen As Long, ByVal nBlockLen As Long, ByVal nOptions As Long) As Long`

`nRet = PAD_UnpadBytes(lpOutput(0), nOutputLen, abInput(0), nInputLen, nBlockLen, 0)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  PAD_UnpadBytes(unsigned char *lpOutput, long nOutputLen, const unsigned char *lpInput, long nBytes, long nBlkLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] array to be filled with the output.

*nOutputLen*
:   [in] specifying the size of the output array in bytes.

*lpInput*
:   [in] array containing the padded data.

*nBytes*
:   [in] specifying the length of the input in bytes.

*nBlkLen*
:   [in] specifying the cipher block length in bytes (8 or 16).

*nOptions*
:   [in] Option flags. Select one of:  

`API_PAD_DEFAULT` (0) to use the default PKCS5 padding 

`API_PAD_1ZERO` to use OneAndZeroes padding  

`API_PAD_AX923` to use ANSIX923 padding  

`API_PAD_W3C` to use W3C padding

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [padUnpadBytes](#VB_padUnpadBytes)(lpInput() As Byte, nBlkLen As Long, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Cipher.Unpad Method](#M_Cipher_Unpad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding)  

or use the method associated with the relevant encryption algorithm class:

[Aes128.Unpad Method](#M_Aes128_Unpad_Byte) (Byte[])  

[Blowfish.Unpad Method](#M_Blowfish_Unpad_Byte) (Byte[])  

[Des.Unpad Method](#M_Des_Unpad_Byte) (Byte[])  

[Tdea.Unpad Method](#M_Tdea_Unpad_Byte) (Byte[])  

### Python Equivalent

`static [Cipher.unpad](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.unpad "External link")(data, alg, pad=Pad.PKCS5)`

### Remarks

The padding is expected according to the convention in 
[PKCS#5](#PKCS5), [PKCS#7](#PKCS7) and [CMS](#CMS).

If *nOutBytes* is set to zero or *lpOutput* set to 0 (or `NULL` in C or `ByVal 0&` in VBA),
then the required number of bytes will be returned. The output is *always* shorter than the input.
Only block lengths of 8 or 16 bytes are supported.
For more details of the supported padding schemes, see [Padding schemes for block ciphers](#paddingschemes).

Note that it is still possible to have a "valid" padding string at the end of incorrectly deciphered data
- just by coincidence -
so you may get a "valid" result from using the Unpad function, but the decrypted text is garbage.

### Example (VBA core function)

See the example in [`PAD_BytesBlock`](#PAD_BytesBlock).

### Example (VBA wrapper function)

```

Dim lpInput() As Byte
Dim lpBlock() As Byte
Dim lpUnpadded() As Byte
lpInput = cnvBytesFromHexStr("FFFFFFFFFF")
Debug.Print "Input data =  0x" & cnvHexStrFromBytes(lpInput)
lpBlock = padBytesBlock(lpInput, 8, 0)
Debug.Print "Padded data = 0x" & cnvHexStrFromBytes(lpBlock)
' Unpad
lpUnpadded = padUnpadBytes(lpBlock, 8, 0)
Debug.Print "Unpadded data = 0x" & cnvHexStrFromBytes(lpUnpadded)

' Special corner case - output is the empty string
lpBlock = cnvBytesFromHexStr("0808080808080808")
Debug.Print "Padded data = 0x" & cnvHexStrFromBytes(lpBlock)
lpUnpadded = padUnpadBytes(lpBlock, 8, 0)
Debug.Print "Unpadded data = 0x" & cnvHexStrFromBytes(lpUnpadded)
```

### See Also

[`PAD_BytesBlock`](#PAD_BytesBlock)
[`PAD_HexBlock`](#PAD_HexBlock)
[`PAD_UnpadHex`](#PAD_UnpadHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PAD_UnpadHex"></a>PAD_UnpadHex
-------------------------------------

Removes the padding from a hex-encoded encryption block.

### VBA/VB6 Syntax

`Public Declare Function PAD_UnpadHex Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal strInputHex As String, ByVal nBlockLen As Long, ByVal nOptions As Long) As Long`

`nRet = PAD_UnpadHex(strOutput, nMaxChars, strInput, nBlockLen, 0)`

### C/C++ Syntax

`long __stdcall  PAD_UnpadHex(char *szOutput, long nMaxChars, const char *szInput, long nBlkLen, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive the hexadecimal-encoded output.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*szInput*
:   [in] containing the hexadecimal-encoded padded data.

*nBlkLen*
:   [in] specifying the cipher block length in bytes (8 or 16).

*nOptions*
:   [in] Option flags. Select one of:  

`API_PAD_DEFAULT` (0) to use the default PKCS5 padding 

`API_PAD_1ZERO` to use OneAndZeroes padding  

`API_PAD_AX923` to use ANSIX923 padding  

`API_PAD_W3C` to use W3C padding

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [padUnpadHex](#VB_padUnpadHex)(szInput As String, nBlkLen As Long, Optional nOptions As Long = 0) As String`

### .NET Equivalent

[Cipher.Unpad Method](#M_Cipher_Unpad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding)  

or use the method associated with the relevant encryption algorithm class:

[Aes128.Unpad Method](#M_Aes128_Unpad_String) (String)  

[Blowfish.Unpad Method](#M_Blowfish_Unpad_String) (String)  

[Des.Unpad Method](#M_Des_Unpad_String) (String)  

[Tdea.Unpad Method](#M_Tdea_Unpad_String) (String)  

### Python Equivalent

`static [Cipher.unpad_hex](https://cryptosys.net/pydocapi/class-stubs/Cipher.html#crsysapi.Cipher.unpad_hex "External link")(datahex, alg, pad=Pad.PKCS5)`

### Remarks

The padding is expected according to the convention specified in *nOptions*.
The output is *always* shorter than the input.
Only block lengths of 8 or 16 bytes are supported.
Note that it is a valid result for *szOutput* to be an empty string.
For more details of the supported padding schemes, see [Padding schemes for block ciphers](#paddingschemes).

For the "raw" VBA/C function, the user must allocate an output string buffer *szOutput* of the required length. 
Specify a zero *nOutChars* or an empty string for *szOutput* to find the required length of the output string.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.

When using the VBA wrapper function `padUnpadHex` and there is an error, then the input is returned unchanged. The user should check for this and signal an error.
See the VBA wrapper example below. 

### Example (VBA core function)

See the example in [`PAD_HexBlock`](#PAD_HexBlock).

### Example (VBA wrapper function)

```

Dim strInputHex As String
Dim strOutputHex As String
strInputHex = "FFFFFF"
Debug.Print "Hex input  =" & strInputHex

strOutputHex = padHexBlock(strInputHex, 8, 0)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, 0)

strOutputHex = padHexBlock(strInputHex, 8, API_PAD_1ZERO)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, API_PAD_1ZERO)

strOutputHex = padHexBlock(strInputHex, 8, API_PAD_AX923)
Debug.Print "Padded data=" & strOutputHex
Debug.Print "Unpadded   =" & padUnpadHex(strOutputHex, 8, API_PAD_AX923)

```

```

Dim strInputHex As String
Dim strOutputHex As String
strInputHex = "FFFFFFFFFF030303"
Debug.Print "Hex input  =" & strInputHex
strOutputHex = padUnpadHex(strInputHex, API_BLK_TDEA_BYTES, 0)
Debug.Print "Unpadded   =" & strOutputHex
' Output is empty string
strInputHex = "0808080808080808"
Debug.Print "Hex input  =" & strInputHex
strOutputHex = padUnpadHex(strInputHex, API_BLK_TDEA_BYTES, 0)
Debug.Print "Unpadded   =" & strOutputHex
' Bad input data results in the same data being returned
strInputHex = "FFFFFFFFFFFFFFFF"    ' Invalid!
Debug.Print "Hex input  =" & strInputHex
strOutputHex = padUnpadHex(strInputHex, API_BLK_TDEA_BYTES, 0)
Debug.Print "Unpadded   =" & strOutputHex
If Len(strOutputHex) = Len(strInputHex) Then
    Debug.Print "DECRYPTION ERROR (<= expected)"
End If
```

### See Also

[`PAD_HexBlock`](#PAD_HexBlock)
[`PAD_BytesBlock`](#PAD_BytesBlock)
[`PAD_UnpadBytes`](#PAD_UnpadBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PBE_Kdf2"></a>PBE_Kdf2
-----------------------------

Derives a key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1.

### VBA/VB6 Syntax

`Public Declare Function PBE_Kdf2 Lib "diCryptoSys.dll" 
    (ByRef lpDerivedKey As Byte, ByVal nKeyLen As Long, 
    ByRef lpPwd As Byte, ByVal nPwdLen As Long, 
    ByRef lpSalt As Byte, ByVal nSaltLen As Long, 
    ByVal nCount As Long, ByVal nOptions As Long) As Long`

`nRet = PBE_Kdf2(abDerivedKey(0), nKeyLen, abPwd(0), nPwdLen, abSalt(0), nSaltLen, nCount, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  PBE_Kdf2(unsigned char *lpDerivedKey, long nKeyLen, const unsigned char *lpPwd, long nPwdLen, const unsigned char *lpSalt, long nSaltLen, long nCount, long nOptions);`

### Parameters

*lpDerivedKey*
:   [out] Byte array to be filled with derived key.

*nKeyLen*
:   [in] size of the required key in bytes.

*lpPwd*
:   [in] Byte array containing the password.

*nPwdLen*
:   [in] length of the password in bytes.

*lpSalt*
:   [in] Byte array containing the salt.

*nSaltLen*
:   [in] length of the salt in bytes.

*nCount*
:   [in] required iteration count.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HMAC_SHA1` (0) to use the HMAC-SHA-1 algorithm (default)  

`API_HMAC_SHA256` to use the HMAC-SHA-256 algorithm  

`API_HMAC_SHA384` to use the HMAC-SHA-384 algorithm  

`API_HMAC_SHA512` to use the HMAC-SHA-512 algorithm  

`API_HMAC_SHA224` to use the HMAC-SHA-224 algorithm  

`API_HMAC_MD5` to use the HMAC-MD5 algorithm

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [pbeKdf2](#VB_pbeKdf2)(nBytes As Long, lpPwd() As Byte, lpSalt() As Byte, nCount As Long, nOptions As Long) As Byte()`

### .NET Equivalent

[Pbe.Kdf2 Method](#M_Pbe_Kdf2_Int32ByteByteInt32HashAlgorithm) (Int32, Byte[], Byte[], Int32, HashAlgorithm)  

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Pbe::Kdf2](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_pbe.html#a2c385d52c1582a83f5687c23e409f75d "External link") (int dklen, const std::string &password, const bvec_t &salt, int count, PrfAlg prfalg=PrfAlg::Hmac_Sha1)`

### Python Equivalent

`static [Pbe.kdf2](https://cryptosys.net/pydocapi/class-stubs/Pbe.html#crsysapi.Pbe.kdf2 "External link")(dklen, password, salt, count, prfalg=0)`

### Remarks

The output buffer for the derived key *abDerivedKey* must have been dimensioned to at least the
required length *nKeyLen* in bytes.

### Example (VBA core function)

This example uses PBKDF2 as defined in PKCS#5 v2.1
from test vectors provided by Dr. Stephen Henson.
The password is "password" (without quotes).
This derived key is for the 'des-ede3-cbc' example in the test vectors
and therefore needs to be 24 bytes long.

```

    Dim abDerivedKey() As Byte
    Dim nKeyLen As Long
    Dim sPassword As String
    Dim abPwdBytes() As Byte
    Dim abSalt(7) As Byte
    Dim nCount As Long
    Dim nRet As Long
    
' Convert password String to an array of Bytes
    sPassword = "password"
    abPwdBytes = StrConv(sPassword, vbFromUnicode)
    
' Set 8-byte salt = 78 57 8E 5A 5D 63 CB 06
    abSalt(0) = &H78
    abSalt(1) = &H57
    abSalt(2) = &H8E
    abSalt(3) = &H5A
    abSalt(4) = &H5D
    abSalt(5) = &H63
    abSalt(6) = &HCB
    abSalt(7) = &H6
    
' Iteration count is 2048
    nCount = 2048
    
' Pre-dimension output for derived key to required length of 24 bytes
' (Don't forget to do this)
    nKeyLen = 24
    ReDim abDerivedKey(nKeyLen - 1)
    
' Derive PBKDF2 key using function from CryptoSys
    nRet = PBE_Kdf2(abDerivedKey(0), nKeyLen, _
      abPwdBytes(0), Len(sPassword), abSalt(0), 8&, nCount, 0&)
    
' Convert bytes to hex and print
    Debug.Print "Derived key = " & cnvHexStrFromBytes(abDerivedKey)
    Debug.Print "Correct key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643"

```

This should result in output as follows:

```

Derived key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643
Correct key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643

```

Had we specified the required key length to be 64 bytes instead of 24, we would 
have generated this 512-bit key:

```

BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643C4B150DEF7751122
4479994567F2E9B4E3BD0DF7AEDA3022B1F26051D81505C794F8940C04DF1144

```

This second example shows how other SHA-2 hash functions can be used.

```

    Dim abDerivedKey() As Byte
    Dim nKeyLen As Long
    Dim sPassword As String
    Dim abPwdBytes() As Byte
    Dim abSalt(7) As Byte
    Dim nSaltBytes As Long
    Dim nCount As Long
    Dim nRet As Long
    
' Convert password String to an array of Bytes
    sPassword = "password"
    abPwdBytes = StrConv(sPassword, vbFromUnicode)
    
' Set 8-byte salt = 78 57 8E 5A 5D 63 CB 06
    abSalt(0) = &H78
    abSalt(1) = &H57
    abSalt(2) = &H8E
    abSalt(3) = &H5A
    abSalt(4) = &H5D
    abSalt(5) = &H63
    abSalt(6) = &HCB
    abSalt(7) = &H6
    nSaltBytes = 8
    
' Iteration count is 2048
    nCount = 2048
    
' Pre-dimension output for derived key to required length of 24 bytes
' (Don't forget to do this)
    nKeyLen = 24
    ReDim abDerivedKey(nKeyLen - 1)
    
' Derive PBKDF2 key using function from CryptoSys API with default HMAC-SHA-1
    nRet = PBE_Kdf2(abDerivedKey(0), nKeyLen, _
      abPwdBytes(0), Len(sPassword), abSalt(0), nSaltBytes, nCount, API_HASH_SHA1)
' Convert bytes to hex and print
    Debug.Print "Derived key {HMAC-SHA-1}   = " & cnvHexStrFromBytes(abDerivedKey)
    
' Derive PBKDF2 key using function from CryptoSys API with HMAC-SHA-256
    nRet = PBE_Kdf2(abDerivedKey(0), nKeyLen, _
      abPwdBytes(0), Len(sPassword), abSalt(0), nSaltBytes, nCount, API_HASH_SHA256)
    Debug.Print "Derived key {HMAC-SHA-256} = " & cnvHexStrFromBytes(abDerivedKey)

' Derive PBKDF2 key using function from CryptoSys API with HMAC-SHA-224
    nRet = PBE_Kdf2(abDerivedKey(0), nKeyLen, _
      abPwdBytes(0), Len(sPassword), abSalt(0), nSaltBytes, nCount, API_HASH_SHA224)
    Debug.Print "Derived key {HMAC-SHA-224} = " & cnvHexStrFromBytes(abDerivedKey)

```

This should result in output as follows:

```

Derived key {HMAC-SHA-1}   = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643
Derived key {HMAC-SHA-256} = 97B5A91D35AF542324881315C4F849E327C4707D1BC9D322
Derived key {HMAC-SHA-224} = 10CFFEDFB13503519969151E466F587028E0720B387F9AEF

```

### Example (VBA wrapper function)

```

Dim lpPwd() As Byte
Dim lpSalt() As Byte
Dim lpDK() As Byte
lpPwd = StrConv("password", vbFromUnicode)
lpSalt = cnvBytesFromHexStr("78 57 8E 5A 5D 63 CB 06")
lpDK = pbeKdf2(24, lpPwd, lpSalt, 2048, API_HASH_SHA256)
Debug.Print "DK=" & cnvHexStrFromBytes(lpDK)
Debug.Print "OK=97B5A91D35AF542324881315C4F849E327C4707D1BC9D322"

```

```

Dim strDerivedKey As String
strDerivedKey = pbeKdf2Hex(24, "password", "78578E5A5D63CB06", 2048, 0)
Debug.Print "Derived key = " & strDerivedKey
Debug.Print "OK =          " & "BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643"
```

### See Also

[`PBE_Kdf2Hex`](#PBE_Kdf2Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PBE_Kdf2Hex"></a>PBE_Kdf2Hex
-----------------------------------

Derives a key of any length from a password using the PBKDF2 algorithm
from PKCS#5 v2.1 with the salt and derived key encoded in hexadecimal.

### VBA/VB6 Syntax

`Public Declare Function PBE_Kdf2Hex Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal nKeyBytes As Long,
    ByVal strPwd As String, ByVal strSaltHex As String, 
    ByVal nCount As Long, ByVal nOptions As Long) As Long`

`nRet = PBE_Kdf2Hex(strDerivedKey, nMaxChars, nKeyLen, strPassword, strSaltHex, nCount, nOptions)`

### C/C++ Syntax

`long __stdcall  PBE_Kdf2Hex(char *szOutput, long nMaxChars, long dkBytes, const char *szPwd, const char *szSaltHex, long nCount, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive the hexadecimal-encoded derived key.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*dkBytes*
:   [in] specifying the size of the required key in bytes.

*szPwd*
:   [in] containing the password.

*szSaltHex*
:   [in] containing the salt in hex format.

*nCount*
:   [in] specifying the required iteration count.

*nOptions*
:   [in] Option flags. Select one of:  

`API_HMAC_SHA1` (0) to use the HMAC-SHA-1 algorithm (default)  

`API_HMAC_SHA256` to use the HMAC-SHA-256 algorithm  

`API_HMAC_SHA384` to use the HMAC-SHA-384 algorithm  

`API_HMAC_SHA512` to use the HMAC-SHA-512 algorithm  

`API_HMAC_SHA224` to use the HMAC-SHA-224 algorithm  

`API_HMAC_MD5` to use the HMAC-MD5 algorithm

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [pbeKdf2Hex](#VB_pbeKdf2Hex)(dkBytes As Long, strPwd As String, strSaltHex As String, nCount As Long, nOptions As Long) As String`

### .NET Equivalent

[Pbe.Kdf2 Method](#M_Pbe_Kdf2_Int32StringStringInt32HashAlgorithm) (Int32, String, String, Int32)  

### COM/ASP Equivalent

`pbe.DKF2FromString  

Public Function DKF2FromString(ByVal nBytes As Long, ByVal strPassword As String, ByVal strSaltHex As String, nCount As Long) As String`

See [`pbe.DKF2FromString`](#x_pbe_dkf2fromstring).

### Remarks

The output string *szOutput* should be pre-dimensioned to be at least **double** the 
required key length in bytes. (Hint: specify *nMaxChars* as `Len(strOutput)`).
The seed *szSaltHex* is specified in hex format and can be any even number of hex digits in length.
The password *szPassword* is normal text, not hexadecimal.

### Example (VBA core function)

```

Dim strDerivedKey As String
Dim nKeyLen As Long
Dim strPassword As String
Dim strSaltHex As String
Dim nCount As Long
Dim nRet As Long

strPassword = "password"  ' NB normal text, not hex

' Set 8-byte salt = 78 57 8E 5A 5D 63 CB 06
strSaltHex = "78578E5A5D63CB06"

' Iteration count is 2048
nCount = 2048

' Pre-dimension output string for derived key to 
' required length of 24 bytes i.e. 48 hex chars
' (Don't forget to do this)
nKeyLen = 24
strDerivedKey = String(2 * nKeyLen, " ")

' Derive PBKDF2 key using function from CryptoSys API
nRet = PBE_Kdf2Hex(strDerivedKey, Len(strDerivedKey), nKeyLen, _
	strPassword, strSaltHex, nCount, 0)

' Check against test vector
Debug.Print "Derived key = " & strDerivedKey
Debug.Print "Correct key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643"

```

This should result in output as follows:

```

Derived key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643
Correct key = BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643

```

### Example (VBA wrapper function)

```

Dim strDerivedKey As String
strDerivedKey = pbeKdf2Hex(24, "password", "78578E5A5D63CB06", 2048, 0)
Debug.Print "Derived key = " & strDerivedKey
Debug.Print "OK =          " & "BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643"
```

### See Also

[`PBE_Kdf2`](#PBE_Kdf2)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PBE_Scrypt"></a>PBE_Scrypt
---------------------------------

Derives a key of any length from a password using the SCRYPT algorithm.

### VBA/VB6 Syntax

`Public Declare Function PBE_Scrypt Lib "diCryptoSys.dll" (ByRef lpDerivedKey As Byte, ByVal nKeyLen As Long, ByRef lpPwd As Byte, ByVal nPwdLen As Long, ByRef lpSalt As Byte, ByVal nSaltLen As Long, ByVal nParamN As Long, ByVal nParamR As Long, ByVal nParamP As Long, ByVal nOptions As Long) As Long`

`nRet = PBE_Scrypt(abDerivedKey(0), nKeyLen, abPwd(0), nPwdLen, abSalt(0), nSaltLen, nParamN, nParamR, nParamP, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall PBE_Scrypt(unsigned char *lpDerivedKey, long nKeyLen, const unsigned char *lpPwd, long nPwdLen, const unsigned char *lpSalt, long nSaltLen, long nParamN, long nParamR, long nParamP, long nOptions);`

### Parameters

*lpDerivedKey*
:   [out] Byte array to be filled with derived key.

*nKeyLen*
:   [in] size of required key in bytes.

*lpPwd*
:   [in] Byte array containing the password.

*nPwdLen*
:   [in] length of the password in bytes.

*lpSalt*
:   [in] Byte array containing the salt.

*nSaltLen*
:   [in] length of the salt in bytes.

*nParamN*
:   [in] CPU/Memory cost parameter *N* (`"costParameter"`) a number greater than one and a power of 2.

*nParamR*
:   [in] Block size *r* (`"blockSize"`)

*nParamP*
:   [in] Parallelization parameter *p* (`"parallelizationParameter"`)

*nOptions*
:   [in] Option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [pbeScrypt](#VB_pbeScrypt)(nBytes As Long, lpPwd() As Byte, lpSalt() As Byte, nParamN As Long, nParamR As Long, nParamP As Long, Optional nOptions As Long = 0) As Byte()`

### .NET Equivalent

[Pbe.Scrypt Method](#M_Pbe_Scrypt_Int32ByteByteInt32Int32Int32) (Int32, Byte[], Byte[], Int32, Int32, Int32) 

### Python Equivalent

`static [Pbe.scrypt](https://cryptosys.net/pydocapi/class-stubs/Pbe.html#crsysapi.Pbe.scrypt "External link")(dklen, pwdbytes, salt, N, r, p)`

### Remarks

This uses the SCRYPT algorithm from [[RFC7914](#RFC7914)].
There are restrictions on the values of the parameters *N*, *r* and *p*.
In particular, *N* must be larger than 1 and a power of 2.

The output buffer for the derived key *abDerivedKey* must have been dimensioned to at least the
required length *nKeyLen* in bytes.

### Example (VBA core function)

Two examples from [[RFC7914](#RFC7914)].

```

Dim abPwd() As Byte
Dim abSalt() As Byte
Dim abDK() As Byte
Dim nKeyLen As Long
Dim nPwdlen As Long
Dim nSaltLen As Long
Dim nRet As Long

nKeyLen = 64
' Dimension key byte array
ReDim abDK(nKeyLen - 1)
' Convert strings to byte array form
abPwd = StrConv("password", vbFromUnicode)
abSalt = StrConv("NaCl", vbFromUnicode)
' Get lengths in bytes
nPwdlen = UBound(abPwd) + 1
nSaltLen = UBound(abSalt) + 1
' Call the SCRYPT function to derive a 64-byte key with parameters N=1024, r=8, p=16
nRet = PBE_Scrypt(abDK(0), nKeyLen, abPwd(0), nPwdlen, abSalt(0), nSaltLen, 1024, 8, 16, 0)
Debug.Print "PBE_Scrypt() returns " & nRet & " (expecting 0)"
Debug.Print "KEY=" & cnvHexStrFromBytes(abDK)	

```

```

PBE_Scrypt() returns 0 (expecting 0)
KEY=FDBABE1C9D3472007856E7190D01E9FE7C6AD7CBC8237830E77376634B373162
2EAF30D92E22A3886FF109279D9830DAC727AFB94A83EE6D8360CBDFA2CC0640

```

In this second example, we need to pass zero-length byte arrays (representing the empty string) for the password and salt.

```

' INPUT: (N=16, r=1, p=1)
' P="", S="" => empty strings => byte arrays of length zero
' VBA ISSUE: we cannot pass an empty byte array in the usual way `abPwd(0)`
' because it gives a "Subscript out of range" error.
' FIX: pass `0` for the array parameters and zero for the lengths
nRet = PBE_Scrypt(abDK(0), nKeyLen, 0, 0, 0, 0, 16, 1, 1, 0)
Debug.Print "PBE_Scrypt() returns " & nRet & " (expecting 0)"
Debug.Print "KEY=" & cnvHexStrFromBytes(abDK)

```

```

PBE_Scrypt() returns 0 (expecting 0)
KEY=77D6576238657B203B19CA42C18A0497F16B4844E3074AE8DFDFFA3FEDE21442
FCD0069DED0948F8326A753A0FC81F17E8D3E0FB2E0D3628CF35E20C38D18906

```

### Example (VBA wrapper function)

```

Dim lpPwd() As Byte
Dim lpSalt() As Byte
Dim lpDK() As Byte
lpPwd = StrConv("password", vbFromUnicode)
lpSalt = StrConv("NaCl", vbFromUnicode)
lpDK = pbeScrypt(64, lpPwd, lpSalt, 1024, 8, 16, 0)
Debug.Print "DK=" & cnvHexStrFromBytes(lpDK)
Debug.Print "OK=FDBABE1C9D3472007856E7190D01E9FE7C6AD7CBC8237830E77376634B3731622EAF30D92E22A3886FF109279D9830DAC727AFB94A83EE6D8360CBDFA2CC0640"
' INPUT: (N=16, r=1, p=1)
' P="", S="" => empty strings => byte arrays of length zero
' IMPORTANT: dummy variables *must* be independent
Dim lpDummy1() As Byte
Dim lpDummy2() As Byte
lpDK = pbeScrypt(64, lpDummy1, lpDummy2, 16, 1, 1, 0)
Debug.Print "DK=" & cnvHexStrFromBytes(lpDK)
Debug.Print "OK=77D6576238657B203B19CA42C18A0497F16B4844E3074AE8DFDFFA3FEDE21442FCD0069DED0948F8326A753A0FC81F17E8D3E0FB2E0D3628CF35E20C38D18906"

```

```

Dim strDerivedKey As String
strDerivedKey = pbeScryptHex(64, "pleaseletmein", cnvHexStrFromString("SodiumChloride"), 16384, 8, 1, 0)
Debug.Print "Derived key = " & strDerivedKey
Debug.Print "OK =          " & "7023BDCB3AFD7348461C06CD81FD38EBFDA8FBBA904F8E3EA9B543F6545DA1F2D5432955613F0FCF62D49705242A9AF9E61E85DC0D651E40DFCF017B45575887"

```

### See Also

[`PBE_ScryptHex`](#PBE_ScryptHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PBE_ScryptHex"></a>PBE_ScryptHex
---------------------------------------

Derives a key of any length from a password using the SCRYPT algorithm
with the salt and derived key encoded in hexadecimal.

### VBA/VB6 Syntax

`Public Declare Function PBE_ScryptHex Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal dkBytes As Long, ByVal strPwd As String, ByVal strSaltHex As String, ByVal nParamN As Long, ByVal nParamR As Long, ByVal nParamP As Long, ByVal nOptions As Long) As Long`

`nRet = PBE_ScryptHex(strDerivedKey, nMaxChars, dkBytes, strPassword, strSaltHex, nParamN, nParamR, nParamP, nOptions)`

### C/C++ Syntax

`long __stdcall PBE_ScryptHex(char *szOutput, long nMaxChars, long dkBytes, const char *szPwd, const char *szSaltHex, long nParamN, long nParamR, long nParamP, long nOptions);`

### Parameters

*szOutput*
:   [out] to receive the hexadecimal-encoded derived key.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*dkBytes*
:   [in] specifying the size of the required key in bytes.

*szPwd*
:   [in] containing the password (as normal text).

*szSaltHex*
:   [in] containing the salt in hex format.

*nParamN*
:   [in] CPU/Memory cost parameter *N* (`"costParameter"`) a number greater than one and a power of 2.

*nParamR*
:   [in] Block size *r* (`"blockSize"`)

*nParamP*
:   [in] Parallelization parameter *p* (`"parallelizationParameter"`)

*nOptions*
:   [in] Option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [pbeScryptHex](#VB_pbeScryptHex)(dkBytes As Long, strPwd As String, strSaltHex As String, nParamN As Long, nParamR As Long, nParamP As Long, Optional nOptions As Long = 0) As String`

### .NET Equivalent

[Pbe.Scrypt Method](#M_Pbe_Scrypt_Int32StringStringInt32Int32Int32) (Int32, String, String, Int32, Int32, Int32)  

### Remarks

The output string *szOutput* should be pre-dimensioned to be at least **double** the 
required key length in bytes. (Hint: specify *nMaxChars* as `Len(strOutput)`).
The seed *szSaltHex* is specified in hex format and can be any even number of hex digits in length.
The password *szPassword* is normal text, not hexadecimal.

### Example (VBA core function)

```

Dim strDerivedKey As String
Dim nKeyLen As Long
Dim strPassword As String
Dim strSaltHex As String
Dim nRet As Long

strPassword = "pleaseletmein"  ' NB normal text, not hex
strSaltHex = cnvHexStrFromString("SodiumChloride")

' Pre-dimension output string for derived key to
' required length of two times number of bytes
' (Don't forget to do this)
nKeyLen = 64
strDerivedKey = String(2 * nKeyLen, " ")

' Derive key using SCRYPT
nRet = PBE_ScryptHex(strDerivedKey, Len(strDerivedKey), nKeyLen, _
    strPassword, strSaltHex, 16384, 8, 1, 0)

Debug.Print "Derived key = " & strDerivedKey

```

This should result in output as follows:

```

Derived key = 7023BDCB3AFD7348461C06CD81FD38EBFDA8FBBA904F8E3EA9B543F6545DA1F2
D5432955613F0FCF62D49705242A9AF9E61E85DC0D651E40DFCF017B45575887

```

### Example (VBA wrapper function)

```

Dim strDerivedKey As String
strDerivedKey = pbeScryptHex(64, "pleaseletmein", cnvHexStrFromString("SodiumChloride"), 16384, 8, 1, 0)
Debug.Print "Derived key = " & strDerivedKey
Debug.Print "OK =          " & "7023BDCB3AFD7348461C06CD81FD38EBFDA8FBBA904F8E3EA9B543F6545DA1F2D5432955613F0FCF62D49705242A9AF9E61E85DC0D651E40DFCF017B45575887"
```

### See Also

[`PBE_Scrypt`](#PBE_Scrypt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PC1_Bytes"></a>PC1_Bytes
-------------------------------

Enciphers an array of Bytes
in one step using the RC4-compatible 'PC1' algorithm.

### VBA/VB6 Syntax

`Public Declare Function PC1_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long) As Long`

`nRet = PC1_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), nKeyLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  PC1_Bytes(unsigned char *lpOutput, unsigned char *lpInput, long nBytes, unsigned char *lpKey, long nKeyBytes);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*nKeyBytes*
:   [in] equal to length of the key in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Pc1.Encrypt Method](#M_Pc1_Encrypt_ByteByte) (Byte[], Byte[])  

### COM/ASP Equivalent

`pc1.EncryptHex  

Public Function EncryptHex(ByVal sInputHex As String, ByVal strHexKey As String) As String`

See [`pc1.EncryptHex`](#x_pc1_encrypthex).

### Remarks

The input data *lpData* can be of any length provided *lpOutput*
is at least as long.
The key *lpKey* can be any length.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim abKey() As Byte
    Dim abInput() As Byte
    Dim lpOutput() As Byte
    Dim nRet As Long
    Dim nDataLen As Long
    Dim nKeyLen As Long
    Dim sCorrect As String
    
    abKey = cnvBytesFromHexStr("0123456789abcdef")
    abInput = cnvBytesFromHexStr("0123456789abcdef")
    sCorrect = "75b7878099e0c596"
    
    ReDim lpOutput(UBound(abInput))
    nDataLen = UBound(abInput) - LBound(abInput) + 1
    nKeyLen = UBound(abKey) - LBound(abKey) + 1
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abInput)
    ' Encipher using PC1
    nRet = PC1_Bytes(lpOutput(0), abInput(0), nDataLen, abKey(0), nKeyLen)
    Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput)
    Debug.Print "OK=" & sCorrect
    
    ' Now decipher just by calling again. Use same output as input.
    nRet = PC1_Bytes(lpOutput(0), lpOutput(0), nDataLen, abKey(0), nKeyLen)
    Debug.Print "P'=" & cnvHexStrFromBytes(lpOutput)

```

This should result in output as follows:

```

KY=0123456789ABCDEF
PT=0123456789ABCDEF
CT=75B7878099E0C596
OK=75b7878099e0c596
P'=0123456789ABCDEF

```

### See Also

[`PC1_File`](#PC1_File)
[`PC1_Hex`](#PC1_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PC1_File"></a>PC1_File
-----------------------------

Enciphers a file using the RC4-compatible 'PC1' algorithm.
The key is passed as an array of bytes.

### VBA/VB6 Syntax

`Public Declare Function PC1_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal nKeyLen As Long) As Long`

`nRet = PC1_File(strFileOut, strFileIn, abKey(0), nKeyLen)`

### C/C++ Syntax

`long __stdcall  PC1_File(char *szFileOut, char *szFileIn, unsigned char *lpKey, long nKeyBytes);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*nKeyBytes*
:   [in] containing the length of the key in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Pc1.File Method](#M_Pc1_File)  

### Remarks

The key array *lpKey* can be any length.

The output file *szFileOut* will be overwritten without warning.
The input and output filenames must **not** be the same.

### Example

```

    Const MY_PATH As String = "C:\Test\"
    Dim abKey(5) As Byte
    Dim strFileOut As String
    Dim strFileIn As String
    Dim strFileChk As String
    Dim nRet As Long

    Debug.Print "Test_PC1_File..."
    ' Construct full path names to files
    strFileIn = MY_PATH & "hello.txt"
    strFileOut = MY_PATH & "hello.pc1.enc.dat"
    strFileChk = MY_PATH & "hello.pc1.chk.txt"

    ' Setup the 6-byte key "abcxyz"
    abKey(0) = Asc("a")
    abKey(1) = Asc("b")
    abKey(2) = Asc("c")
    abKey(3) = Asc("x")
    abKey(4) = Asc("y")
    abKey(5) = Asc("z")

    ' Encipher plaintext file
    nRet = PC1_File(strFileOut, strFileIn, abKey(0), 6&)
    Debug.Print "PC1_File returns " & nRet

    ' Now decipher just by repeating
    nRet = PC1_File(strFileChk, strFileOut, abKey(0), 6&)
    Debug.Print "PC1_File returns " & nRet

```

This should result in output as follows:

```

Test_PC1_File...
PC1_File returns 0
PC1_File returns 0

```

### See Also

[`PC1_Bytes`](#PC1_Bytes)
[`PC1_Hex`](#PC1_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PC1_Hex"></a>PC1_Hex
---------------------------

Enciphers data encoded in hex format
in one step using the RC4-compatible 'PC1' algorithm.

### VBA/VB6 Syntax

`Public Declare Function PC1_Hex Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, 
    ByVal strInputHex As String, ByVal strKeyHex As String) As Long`

`nRet = PC1_Hex(strOutput, nMaxChars, strInputHex, strKeyHex)`

### C/C++ Syntax

`long __stdcall  PC1_Hex(char *szOutput, long nMaxChars, const char *szInputHex, const char *szKeyHex);`

### Parameters

*szOutput*
:   [out] to receive the hexadecimal-encoded output.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*szInputHex*
:   [in] containing the input data in hex format.

*szKeyHex*
:   [in] containing the key in hex format.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Pc1.Encrypt Method](#M_Pc1_Encrypt_StringString) (String, String)  

### COM/ASP Equivalent

`pc1.EncryptHex  

Public Function EncryptHex(ByVal sInputHex As String, ByVal strHexKey As String) As String`

See [`pc1.EncryptHex`](#x_pc1_encrypthex).

### Remarks

All hex parameters must be an even number of hexadecimal digits.
The input data *szInputHex* can be of any length provided *szOutput*
is at least as long.
The key *szKeyHex* can be any length.
*szOutput* and *szInputHex* should be different variables.

### Example

```

    Dim nRes As Long
    Dim strKey As String
    Dim strInput As String
    Dim strOutput As String
    Dim strCorrect As String
    Dim strCheck As String
    
    ' Test vector 3
    strKey = "ef012345"
    strInput = "00000000000000000000"
    strCorrect = "d6a141a7ec3c38dfbd61"
    
    Debug.Print "KY=" & strKey
    Debug.Print "PT=" & strInput
    ' Encipher using PC1 in hex mode
    strOutput = String(Len(strInput), " ")
    nRes = PC1_Hex(strOutput, Len(strOutput), strInput, strKey)
    Debug.Print "CT=" & strOutput
    Debug.Print "OK=" & strCorrect
    
    ' Now decipher just by calling again.
    strCheck = String(Len(strInput), " ")
    nRes = PC1_Hex(strCheck, Len(strCheck), strOutput, strKey)
    Debug.Print "P'=" & strCheck

```

This should result in output as follows:

```

KY=ef012345
PT=00000000000000000000
CT=D6A141A7EC3C38DFBD61
OK=d6a141a7ec3c38dfbd61
P'=00000000000000000000

```

### See Also

[`PC1_Bytes`](#PC1_Bytes)
[`PC1_File`](#PC1_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="PRF_Bytes"></a>PRF_Bytes
-------------------------------

Generate output bytes using a pseudorandom function (PRF).

### VBA/VB6 Syntax

`Public Declare Function PRF_Bytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpMessage As Byte, ByVal nMsgLen As Long, ByRef lpKey As Byte, ByVal nKeyLen As Long, ByVal strCustom As String, ByVal nOptions As Long) As Long`

`nRet = PRF_Bytes(lpOutput(0), nOutBytes, abMessage(0), nMsgLen, abKey(0), nKeyLen, strCustom, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall PRF_Bytes(unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, const char *szCustom, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive the output.

*nOutBytes*
:   [in] size of output buffer in bytes.

*lpMessage*
:   [in] byte array containing the input data.

*nMsgLen*
:   [in] length of the input data in bytes.

*lpKey*
:   [in] byte array containing the key.

*nKeyLen*
:   [in] length of the key in bytes.

*szCustom*
:   [in] customization string (optional).

*nOptions*
:   [in] Option flags. Select one of:  

`API_KMAC_128` to use KMAC128 (KMAC with SHAKE128)  

`API_KMAC_256` to use KMAC256 (KMAC with SHAKE256).

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function prfBytes(nBytes As Long, lpMessage() As Byte, lpKey() As Byte, nOptions As Long, Optional szCustom As String = "") As Byte()`

#### Parameters

As above. See [Notes on VBA wrapper functions](#notesonvbawrapperfunctions).
Note different order of parameters from core function.

#### Return Value (VBA wrapper)

`Byte():` Output data in byte array.

### .NET Equivalent

[Prf.Bytes Method](#M_Prf_Bytes)  

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Prf::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_prf.html#a8a68d8282f3b6e098ae465db4b89e4a4 "External link") (int numBytes, const bvec_t &message, const bvec_t &key, PrfAlg prfalg, const std::string &customStr="")`

### Python Equivalent

`static [Prf.bytes](https://cryptosys.net/pydocapi/class-stubs/Prf.html#crsysapi.Prf.bytes "External link")(numbytes, msg, key, prfalg, customstring="")`

### Remarks

The output buffer *lpOutput* must exist. It will be filled with exactly *nOutBytes* bytes.
Note there is no zero option for *nOptions*: a valid option flag must be specified.
For KMAC, the default customization string *szCustom* is the empty string `""`.

### Example (VBA core function)

```

Dim strKeyHex As String
Dim strMsgHex As String
Dim nOutBits As Long
Dim nOutBytes As Long
Dim abMAC() As Byte
Dim abMsg() As Byte
Dim abKey() As Byte
Dim nMsgLen As Long
Dim nKeyLen As Long
Dim strCustom As String
Dim strOK As String
Dim nRet As Long

' Ref: `KMAC_samples.pdf` "Secure Hashing - KMAC-Samples" 2017-02-27
' <https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/KMAC_samples.pdf>

' Sample #2
' Input in hex form
strKeyHex = "404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F"
strMsgHex = "00010203"
nOutBits = 256
strCustom = "My Tagged Application"
strOK = "3B1FBA963CD8B0B59E8C1A6D71888B7143651AF8BA0A7070C0979E2811324AA5"
' Convert to byte array form
abKey = cnvBytesFromHexStr(strKeyHex)
abMsg = cnvBytesFromHexStr(strMsgHex)
nKeyLen = UBound(abKey) + 1
nMsgLen = UBound(abMsg) + 1

' Required output size
nOutBytes = (nOutBits / 8)
ReDim abMAC(nOutBytes - 1)
nRet = PRF_Bytes(abMAC(0), nOutBytes, abMsg(0), nMsgLen, abKey(0), nKeyLen, strCustom, API_KMAC_128)
If nRet > 0 Then
    Debug.Print "KMAC=" & cnvHexStrFromBytes(abMAC)
    Debug.Print "OK  =" & strOK
Else
   Debug.Print "Error code " & nRet
End If

```

This should result in output as follows:

```

KMAC=3B1FBA963CD8B0B59E8C1A6D71888B7143651AF8BA0A7070C0979E2811324AA5
OK  =3B1FBA963CD8B0B59E8C1A6D71888B7143651AF8BA0A7070C0979E2811324AA5

```

### Example (VBA wrapper function)

```

Dim lpPrf() As Byte
Dim lpMsg() As Byte
Dim lpKey() As Byte
lpKey = cnvBytesFromHexStr("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F")
lpMsg = cnvBytesFromHexStr("00010203")
' NB order of parameters (szCustom <=> nOptions).
lpPrf = prfBytes(256 \ 8, lpMsg, lpKey, API_KMAC_128, "My Tagged Application")
Debug.Print "KMAC=" & cnvHexStrFromBytes(lpPrf)
Debug.Print "OK  =3B1FBA963CD8B0B59E8C1A6D71888B7143651AF8BA0A7070C0979E2811324AA5"
```

### See Also

[`MAC_Bytes`](#MAC_Bytes)
[`XOF_Bytes`](#XOF_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_BytesWithPrompt"></a>RNG_BytesWithPrompt
---------------------------------------------------

Generates a random set of byte data suitable for cryptographic keys
with a prompt for the user to enter random keystrokes and mouse movements.

### VBA/VB6 Syntax

`Public Declare Function RNG_BytesWithPrompt Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutputLen As Long, ByVal strPrompt As String, ByVal nOptions As Long) As Long`

`nRet = RNG_BytesWithPrompt(lpOutput(0), nOutputLen, strPrompt, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  RNG_BytesWithPrompt(unsigned char *lpOutput, long nOutputLen, const char *szPrompt, long nOptions);`

### Parameters

*lpOutput*
:   [out] array to receive the random data.

*nOutputLen*
:   [in] specifying the required length in bytes.

*szPrompt*
:   [in] specifying an (optional) prompt for the dialog. 
	Specify an empty string ("") or NULL to use the default dialog.

*nOptions*
:   [in] option flags:  

`API_DEFAULT` (0) for default options  

`API_RNG_STRENGTH_112` to make user generate an estimated 112 bits of security (default)  

`API_RNG_STRENGTH_128` to make user generate an estimated 128 bits of security 

`API_RNG_STRENGTH_192` to make user generate an estimated 192 bits of security 

`API_RNG_STRENGTH_256` to make user generate an estimated 256 bits of security

### Returns (VBA/C)

If successful, the return value is 0.
If the parameters are invalid, it returns a negative [error code](#errorcodes).

### .NET Equivalent

[Rng.BytesWithPrompt Method](#M_Rng_BytesWithPrompt_Int32Rng_Strength) (Int32, Rng.Strength)  

[Rng.BytesWithPrompt Method](#M_Rng_BytesWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength)  

### Python Equivalent

`static [Rng.bytes_with_prompt](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.bytes_with_prompt "External link")(n, strength=Strength.BITS_112, prompt='')`

### Remarks

Once started, there is no way to abandon the dialog that prompts the user except by terminating the process.
Some applications may not handle the GUI dialog. Make your own tests to check.
The maximum number of random bytes that can be requested in one call is 65,536 (64 kB).
See [Random Number Generator](#rnginfo) for more information on the RNG 
and its compliance with the relevant standards.

### Example

```

Dim abData() As Byte
Dim nDataLen As Long

' Allocate byte array for 16 bytes
nDataLen = 16
ReDim abData(nDataLen - 1)

' Default prompt with default 112-bit security strength
Call RNG_BytesWithPrompt(abData(0), nDataLen, "", 0)
Debug.Print cnvHexStrFromBytes(abData)

' User-selected prompt with 128-bit security strength
Call RNG_BytesWithPrompt(abData(0), nDataLen, "Our own prompt: type until done...", API_RNG_STRENGTH_128)
Debug.Print cnvHexStrFromBytes(abData)

```

### See Also

[`RNG_KeyBytes`](#RNG_KeyBytes)
[`RNG_HexWithPrompt`](#RNG_HexWithPrompt)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_HexWithPrompt"></a>RNG_HexWithPrompt
-----------------------------------------------

Generates a random set of data in hexadecimal format suitable for cryptographic keys
with a prompt for the user to enter random keystrokes and mouse movements.

### VBA/VB6 Syntax

`Public Declare Function RNG_HexWithPrompt Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal nBytes As Long, ByVal strPrompt As String, ByVal nOptions As Long) As Long`

`nRet = RNG_HexWithPrompt(strOutput, nMaxChars, strPrompt, nOptions)`

### C/C++ Syntax

`long __stdcall  RNG_HexWithPrompt(char *szOutput, long nMaxChars, long nBytes, const char *szPrompt, long nOptions);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*nBytes*
:   [in] value of the required random data length in **bytes**.

*szPrompt*
:   [in] specifying an (optional) prompt for the dialog. 
	Specify an empty string ("") or NULL to use the default dialog.

*nOptions*
:   [in] option flags:  

`API_DEFAULT` (0) for default options  

`API_RNG_STRENGTH_112` to make user generate an estimated 112 bits of security (default)  

`API_RNG_STRENGTH_128` to make user generate an estimated 128 bits of security 

`API_RNG_STRENGTH_192` to make user generate an estimated 192 bits of security 

`API_RNG_STRENGTH_256` to make user generate an estimated 256 bits of security

### Returns (VBA/C)

If successful, the return value is 0.
If the parameters are invalid, it returns a negative [error code](#errorcodes).

### .NET Equivalent

[Rng.HexWithPrompt Method](#M_Rng_HexWithPrompt_Int32) (Int32)  

[Rng.HexWithPrompt Method](#M_Rng_HexWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength)  

### Remarks

See the remarks for [`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt).

### Example

```

Dim strHexData As String
Dim nBytes As Long

' Allocate output string for 16 bytes = 2 x the number of bytes
nBytes = 16
strHexData = String(nBytes * 2, " ")

' Default prompt with default 112-bit security strength
Call RNG_HexWithPrompt(strHexData, Len(strHexData), nBytes, "", 0)
Debug.Print strHexData

' User-selected prompt with 128-bit security strength
Call RNG_HexWithPrompt(strHexData, Len(strHexData), nBytes, "Our own prompt: type until done...", API_RNG_STRENGTH_128)
Debug.Print strHexData

```

### See Also

[`RNG_KeyHex`](#RNG_KeyHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_Initialize"></a>RNG_Initialize
-----------------------------------------

Initializes the RNG generator with a seed file.

### VBA/VB6 Syntax

`Public Declare Function RNG_Initialize Lib "diCryptoSys.dll" (ByVal strSeedFile As String, ByVal nOptions As Long) As Long`

`nRet = RNG_Initialize(strSeedFile, nOptions)`

### C/C++ Syntax

`long __stdcall  RNG_Initialize(const char *szSeedFile, long nOptions);`

### Parameters

*szSeedFile*
:   [in] specifying a seed file. May be the empty string `""`.

*nOptions*
:   [in] option flags:  

`API_DEFAULT` (0) for default options  

`API_RNG_NO_INTEL_DRNG` to turn off support for Intel(R) DRNG for the current session.

### Returns (VBA/C)

If successful, the return value is zero; otherwise it returns a non-zero [error code](#errorcodes).
If `""` is passed for *szSeedFile*, it returns the support status for Intel DRNG (see Remarks). 

### VBA Wrapper Syntax

`Public Function [rngInitialize](#VB_rngInitialize) (szSeedFile As String) As Long  
Public Function [rngInitializeEx](#VB_rngInitializeEx) (Optional nOptions As Long = 0) As Long`

### .NET Equivalent

[Rng.Initialize Method](#M_Rng_Initialize)  

[Rng.InitializeEx Method](#M_Rng_InitializeEx)  

### C++ (STL) Equivalent

`static int [crsysapi::Rng::Initialize](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a11e073fb364369f8dc5dd138c5821b4f "External link") (const std::string &seedFile)  

static int [crsysapi::Rng::InitializeEx](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a38f1ea8802d5eae55561ee60a13ce32d "External link") (Opts opts=Opts::Default)`

### Python Equivalent

`static [Rng.initialize](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.initialize "External link")(seedfilename)`

`static [Rng.initialize_ex](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.initialize_ex "External link")(opts=0)`

### Remarks

A seed file maintains the entropy state between sessions. 
If the seed file does not exist, it will be created, using any existing entropy. The file must be writable by the user. 
File locking is used to prevent interference from simultaneous use by others.
The seed file is automatically updated by this procedure. Any existing file will be overwritten without warning.

**Intel(R) DRNG support:** *[New in v6.22.1]* Pass an empty string `""` for *szSeedFile* to query support for 
Intel(R) Digital Random Number Generator (DRNG) on your system (and add an extra 256 bits of entropy, if available).
If supported, the return value is a positive integer (1,2,3), 
otherwise it returns the error code `PRNG_ERR_NOTAVAIL` (-214).
See [Intel(R) DRNG Support](#inteldrng).

Alternatively, use the option `API_RNG_NO_INTEL_DRNG` to turn off support for Intel(R) DRNG for the current session. 
You might use this if calls to Intel(R) DRNG are causing problems on your system.

### Example

This example shows how to initialize the RNG with a seed file, generate some random data, and then update the seed file.

```

Dim strSeedFile As String
Dim nRet As Long
Dim abData() As Byte
Dim nDataLen As Long
Dim i As Integer

strSeedFile = "C:\Test\seed.dat"
' 1. Initialize
nRet = RNG_Initialize(strSeedFile, 0)
Debug.Print "RNG_Initialize('" & strSeedFile & "') returns " & nRet & " (expecting 0)"

' 2. Generate some random data
nDataLen = 24
ReDim abData(nDataLen - 1)
For i = 1 To 3
    Call RNG_KeyBytes(abData(0), nDataLen, "", 0)
    Debug.Print cnvHexStrFromBytes(abData)
Next

' 3. Update the seed file
nRet = RNG_UpdateSeedFile(strSeedFile, 0)
Debug.Print "RNG_UpdateSeedFile('" & strSeedFile & "') returns " & nRet & " (expecting 0)"

```

```

RNG_Initialize('C:\Test\seed.dat') returns 0 (expecting 0)
79654D8DA3D30468B95B820E3C5615838A765CA666C68A9D
EB2DA20FC86CC797BCB3D26C9E663736E616EF99DEB56C21
5A3DB035BD374E57649AEE367A7E0156A3045AE0111D47EC
RNG_UpdateSeedFile('C:\Test\seed.dat') returns 0 (expecting 0)

```

This example demonstrates support for Intel(R) DRNG

```

Dim n As Long
n = RNG_Initialize("", 0)  ' Query support for Intel(R) DRNG
Debug.Print "RNG_Initialize() returns " & n & " (If > 0 Intel(R) DRNG support available)"
' Explicitly turn off support...
n = RNG_Initialize("", API_RNG_NO_INTEL_DRNG)  ' Turns off Intel(R) DRNG support
Debug.Print "RNG_Initialize(API_RNG_NO_INTEL_DRNG) returns " & n & " (expected -ve)"
n = RNG_Initialize("", 0)  ' Now query again
Debug.Print "RNG_Initialize() returns " & n & " (expected -ve)"

```

```

RNG_Initialize() returns 3 (If > 0 Intel(R) DRNG support available)
RNG_Initialize(API_RNG_NO_INTEL_DRNG) returns -214 (expected -ve)
RNG_Initialize() returns -214 (expected -ve)

```

In practice, you should test for Intel(R) DRNG support before calling any RNG function. If supported, then the generator will have been seeded with sufficient entropy. 
If not, then use a seed file.

```

Dim n As Long
n = rngInitializeEx()
If n <= 0 Then
    ' Intel(R) DRNG not available, so use a seed file
    n = rngInitialize("seed.dat")
End If
' Do work...
Dim abKey() As Byte
abKey = rngKeyBytes(32)
Debug.Print cnvToHex(abKey)
' ...etc
' At end of session, update the seed file
n = RNG_UpdateSeedFile("seed.dat", 0)

```

In the worst case, if Intel(R) DRNG is not supported and a seed file has not yet been created, a new file will be created using whatever entropy is available. 
Make sure to use UpdateSeedFile before finishing - this will save any entropy collected during the current process ready for next time.

### See Also

[`RNG_MakeSeedFile`](#RNG_MakeSeedFile)
[`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_KeyBytes"></a>RNG_KeyBytes
-------------------------------------

Generates a random set of byte data suitable for cryptographic keys.

### VBA/VB6 Syntax

`Public Declare Function RNG_KeyBytes Lib "diCryptoSys.dll" 
    (ByRef lpOutput As Byte, ByVal nBytes As Long, 
    ByVal strSeed As String, ByVal nSeedLen As Long) As Long`

`nRet = RNG_KeyBytes(lpOutput(0), nBytes, strSeed, nSeedLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  RNG_KeyBytes(unsigned char *lpOutput, long nOutputLen, const void *lpSeed, long nSeedLen);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*nOutputLen*
:   [in] value of the required key length in bytes.

*lpSeed*
:   [in] containing an (optional) user-specified seed to be 
used by the random number generator. Specify an empty string (`""`) or NULL to ignore..

*nSeedLen*
:   [in] specifiying the size of the seed in bytes.

### Returns (VBA/C)

Always returns zero. 
If the function fails its continuous random number generator test, a critical error will occur.
See [Self Tests](#selftests) for more details.

### VBA Wrapper Syntax

`Public Function [rngKeyBytes](#VB_rngKeyBytes)(nBytes As Long, Optional szSeed = "") As Byte()`

### .NET Equivalent

[Rng.KeyBytes Method (Int32, Byte[])](#M_Rng_KeyBytes_Int32Byte)  

[Rng.KeyBytes Method (Int32, String)](#M_Rng_KeyBytes_Int32String)  

### Python Equivalent

`static [Rng.bytestring](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.bytestring "External link")(n)`

### Remarks

The seed *szSeed* is optional and is added to the automatic seed values generated internally. 
The seed cannot directly affect the value of the output; it will just ensure that it will be different.

### Example (VBA core function)

```

Dim abKey() As Byte
Dim nRet As Long
Dim nKeyBytes As Long
Dim i As Integer

nKeyBytes = 24
ReDim abKey(nKeyBytes - 1)
' Generate three successive 192-bit random keys with no seeding
For i = 1 To 3
	nRet = RNG_KeyBytes(abKey(0), nKeyBytes, "", 0)
	Debug.Print cnvHexStrFromBytes(abKey)
Next

```

### Example (VBA wrapper function)

```

Dim i As Integer
For i = 1 To 10
    Debug.Print cnvHexStrFromBytes(rngKeyBytes(32))
Next

```

### See Also

[`RNG_KeyHex`](#RNG_KeyHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_KeyHex"></a>RNG_KeyHex
---------------------------------

Generates a random set of data in hexadecimal format suitable for cryptographic keys.

### VBA/VB6 Syntax

`Public Declare Function RNG_KeyHex Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal nBytes As Long, 
    ByVal strSeed As String, ByVal nSeedLen As Long) As Long`

`nRet = RNG_KeyHex(strOutput, nMaxChars, nBytes, strSeed, nSeedLen)`

### C/C++ Syntax

`long __stdcall  RNG_KeyHex(char *szOutput, long nMaxChars, long nBytes, const void *lpSeed, long nSeedLen);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*nMaxChars*
:   [in] specifying the maximum number of characters in *szOutput*.

*nBytes*
:   [in] value of the required key length in **bytes**.

*lpSeed*
:   [in] containing an (optional) user-specified seed to be 
used by the random number generator. Specify an empty string (`""`) or NULL to ignore..

*nSeedLen*
:   [in] specifying the size of the seed in bytes.

### Returns (VBA/C)

Always returns zero. 
If the function fails its continuous random number generator test, a critical error will occur.
See [Self Tests](#selftests) for more details.

### VBA Wrapper Syntax

`Public Function [rngKeyHex](#VB_rngKeyHex)(nBytes As Long, Optional szSeed = "") As String`

### .NET Equivalent

[Rng.KeyHex Method (Int32, Byte[])](#M_Rng_KeyHex_Int32Byte)  

[Rng.KeyHex Method (Int32, String)](#M_Rng_KeyHex_Int32String)  

### COM/ASP Equivalent

`rng.KeyHex  

Public Function KeyHex(ByVal nBytes As Long) As String`

See [`rng.KeyHex`](#x_rng_keyhex).

### Remarks

The output string *szOutput* should be pre-dimensioned to be at least **double** the 
required key length in bytes. *Hint:* specify *nMaxChars* as `Len(strOutput)`.
C/C++ users [must add one to this value](#cusersaddone) when allocating memory.
The seed *szSeed* is optional and is added to the automatic seed values generated internally. 
The seed cannot directly affect the value of the output; it will just ensure that it will be different.

### Example (VBA core function)

```

Dim strHexKey As String
Dim nRet As Long
Dim nKeyBytes As Long
Dim strSeed As String
Dim i As Integer

nKeyBytes = 24
' Pre-dimension hex string to be DOUBLE key length in bytes
strHexKey = String(nKeyBytes * 2, " ")

nRet = RNG_KeyHex(strHexKey, Len(strHexKey), nKeyBytes, "", 0)
Debug.Print strHexKey

' Generate three successive 192-bit random keys with no seeding
For i = 1 To 3
    nRet = RNG_KeyHex(strHexKey, Len(strHexKey), nKeyBytes, "", 0)
    Debug.Print strHexKey
Next

' Generate three more 192-bit random keys using the counter as a seed
For i = 1 To 3
    strSeed = CStr(i)
    nRet = RNG_KeyHex(strHexKey, Len(strHexKey), nKeyBytes, strSeed, Len(strSeed))
    Debug.Print strHexKey
Next

' Generate a DES key and check if it's a weak key
strHexKey = String(8 * 2, " ")
nRet = RNG_KeyHex(strHexKey, Len(strHexKey), 8, "", 0)
Debug.Print strHexKey
nRet = DES_CheckKeyHex(strHexKey)
Debug.Print "DES_CheckKeyHex returns " & nRet & " (" & apiErrorLookup(nRet) & ")"

' Test a known weak key
strHexKey = "fefefefefefefefe"
nRet = DES_CheckKeyHex(strHexKey)
Debug.Print "DES_CheckKeyHex returns " & nRet & " (" & apiErrorLookup(nRet) & ")"

```

This will produce output that of the following form with obviously different values:

```

307152819FE0C2E718A1A6D4FA49AABB36CF274EABA77038
A02FE37FB1BB2F26636B2FAB79D3502617F5FF1761056D0A
E936ED0A805CB5D8190C33B24CE90B9C47CD75627D559E17
5A630F6D97CA0DF22649FABFFF555D91820797C6378C0972
F82B84DD477F065A5D9D2B8B4C625977B5433EA50671A28B
BB54598AA5457F46EAEEB7BD78DA1B1C34F81894FEB216FB
E8CB635CC3D3571DD44D8C982B887E35F00252DF336DAC5A
C7412767A925CA74
DES_CheckKeyHex returns 0 (OK, success, no error)
DES_CheckKeyHex returns 52 (Weak key)

```

### Example (VBA wrapper function)

```

Dim i As Integer
For i = 1 To 10
    Debug.Print rngKeyHex(16)
Next

```

### See Also

[`RNG_KeyBytes`](#RNG_KeyBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_MakeSeedFile"></a>RNG_MakeSeedFile
---------------------------------------------

Creates a new seed file suitable for use with 
	[`RNG_Initialize`](#RNG_Initialize).

### VBA/VB6 Syntax

`Public Declare Function RNG_MakeSeedFile Lib "diCryptoSys.dll" (ByVal strSeedFile As String, ByVal strPrompt As String, ByVal nOptions As Long) As Long`

`nRet = RNG_MakeSeedFile(strSeedFile, strPrompt, nOptions)`

### C/C++ Syntax

`long __stdcall  RNG_MakeSeedFile( const char *szSeedFile, const char *szPrompt, long nOptions);`

### Parameters

*szSeedFile*
:   [in] specifying the seed file to be created.

*szPrompt*
:   [in] specifying an (optional) prompt for the dialog. 
	Specify an empty string ("") or NULL to use the default dialog.

*nOptions*
:   [in] option flags:  

`API_DEFAULT` (0) for default options  

`API_RNG_STRENGTH_112` to make user generate an estimated 112 bits of security (default)  

`API_RNG_STRENGTH_128` to make user generate an estimated 128 bits of security 

`API_RNG_STRENGTH_192` to make user generate an estimated 192 bits of security 

`API_RNG_STRENGTH_256` to make user generate an estimated 256 bits of security

### Returns (VBA/C)

If successful, the return value is zero; otherwise it returns a non-zero [error code](#errorcodes). 

### .NET Equivalent

[Rng.MakeSeedFile Method](#M_Rng_MakeSeedFile_StringRng_Strength) (String, Rng.Strength)  

[Rng.MakeSeedFile Method](#M_Rng_MakeSeedFile_StringStringRng_Strength) (String, String, Rng.Strength)  

### Python Equivalent

`static [Rng.make_seedfile](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.make_seedfile "External link")(seedfilename, strength=Strength.BITS_112, prompt='')`

### Remarks

This uses a dialog window and expects the user to type in random keystrokes. 
Such a GUI interface may not be appropriate in all circumstances.
A new seed file is always created. Any existing file with the same name will be overwritten without warning.
Alternatively, use the command-line program, `ApiMkRngSeed.exe`, provided in the distribution
to make a new seed file [*updated in v6.22*].

### Example

```

Dim strSeedFile As String
Dim nRet As Long

strSeedFile = "seed.dat"
nRet = RNG_MakeSeedFile(strSeedFile, "Making a new seed file: hit random keys until done...", API_RNG_STRENGTH_128)
Debug.Print "RNG_MakeSeedFile('" & strSeedFile & "') returns " & nRet & " (expecting 0)"

```

### See Also

[`RNG_Initialize`](#RNG_Initialize)
[`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_NonceData"></a>RNG_NonceData
---------------------------------------

Returns a random nonce (number used once) as a specified-length
byte array. This replaces the `RNG_Nonce` function from version 2.

### VBA/VB6 Syntax

`Public Declare Function RNG_NonceData Lib "diCryptoSys.dll" 
    (ByRef lpOutput As Byte, ByVal nBytes As Long) As Long`

`nRet = RNG_NonceData(lpOutput(0), nBytes)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  RNG_NonceData(unsigned char *lpOutput, long nBytes);`

### Parameters

*lpOutput*
:   [out] array to be filled with
random values.

*nBytes*
:   [in] specifying the number of
required bytes in the nonce.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Rng.NonceBytes Method](#M_Rng_NonceBytes)  

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Rng::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a6512dc0fdaddf32ebe4072173bb53627 "External link") (int n)`

### Remarks

The array `lpOutput` must be at least `nBytes` bytes long.

### Example

This example generates three nonces each 8 bytes long.

```

    Dim abKey() As Byte
    Dim nRet As Long
    Dim nKeyBytes As Long
    Dim i As Integer
    
    nKeyBytes = 8
    ReDim abKey(nKeyBytes - 1)
    ' Generate three successive 8-byte nonces
    For i = 1 To 3
        nRet = RNG_NonceData(abKey(0), nKeyBytes)
        Debug.Print cnvHexStrFromBytes(abKey)
    Next

```

### See Also

[`RNG_NonceDataHex`](#RNG_NonceDataHex)
[`RNG_Number`](#RNG_Number)
[`RNG_KeyBytes`](#RNG_KeyBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_NonceDataHex"></a>RNG_NonceDataHex
---------------------------------------------

Returns a specified-length random nonce (number used once) as a
hexadecimal string. This is a safer version of the `RNG_NonceHex` function in version 2.

### VBA/VB6 Syntax

`Public Declare Function RNG_NonceDataHex Lib "diCryptoSys.dll" 
    (ByVal strOutput As String, ByVal nMaxChars As Long, 
    ByVal nBytes As Long) As Long`

`nRet = RNG_NonceDataHex(strOutput, nMaxChars, nBytes)`

### C/C++ Syntax

`long __stdcall  RNG_NonceDataHex(char *szOutput, long nMaxChars, long nBytes);`

### Parameters

*szOutput*
:   [out] array to be filled with
random values expressed in hexadecimal.

*nMaxChars*
:   [in] specifying the maximum number 
of characters in *szOutput*.

*nBytes*
:   [in] specifying the number of
required **bytes** in the nonce.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Rng.NonceHex Method](#M_Rng_NonceHex)  

### COM/ASP Equivalent

`rng.NonceHex  

Public Function NonceHex(ByVal nBytes As Long) As String`

See [`rng.NonceHex`](#x_rng_noncehex).

### C++ (STL) Equivalent

`static std::string [crsysapi::Rng::Hex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a94b854ad70cc6c31ab4ffc9597304ae6 "External link") (int n)`

### Remarks

The array *szOutput* must be filled with dummy characters
to two times *nBytes* before calling the function.
The length of the output buffer in characters must be specified.

### Example

This example will create a random number 20 bytes long in hexadecimal.

```

    Dim sHexData As String
    Dim nRet As Long
    Dim nBytes As Long

    nBytes = 20
    ' Set hex string length to 2 x # bytes required.
    sHexData = String(2 * nBytes, " ")
    nRet = RNG_NonceDataHex(sHexData, Len(sHexData), nBytes)
    Debug.Print sHexData

```

This useful wrapper function is in the Visual Basic declarations module.

```

Public Function rngNonceHex(nBytes As Long) As String
' Returns a random nonce nBytes long encoded in hex
    Dim strHex As String
    Dim nRet As Long
    
    strHex = String(nBytes * 2, " ")
    nRet = RNG_NonceDataHex(strHex, Len(strHex), nBytes)
    If nRet = 0 Then
        rngNonceHex = strHex
    End If
End Function

```

### See Also

[`RNG_NonceData`](#RNG_NonceData)
[`RNG_Number`](#RNG_Number)
[`RNG_KeyBytes`](#RNG_KeyBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_Number"></a>RNG_Number
---------------------------------

Returns a random 32-bit number between specified limits.

### VBA/VB6 Syntax

`Public Declare Function RNG_Number Lib "diCryptoSys.dll"
    (ByVal nLower As Long, ByVal nUpper As Long) As Long`

`nRandom = RNG_Number(nLower, nUpper)`

### C/C++ Syntax

`int32_t __stdcall  RNG_Number(int32_t nLower, int32_t nUpper);`

### Parameters

*nLower*
:   [in] specifying a lower limit.

*nUpper*
:   [in] specifying an upper limit.

### Returns (VBA/C)

A random number between *nLower* and *nUpper*.

### .NET Equivalent

[Rng.Number Method](#M_Rng_Number)  

### C++ (STL) Equivalent

`static int32_t [crsysapi::Rng::Number](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a9c11b3035208a82a75edbd94e58f26f0 "External link") (int32_t lower, int32_t upper)  

static int [crsysapi::Rng::Octet](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a99bc1f305c16cb10dad277e0a8df5548 "External link") ()`

### Python Equivalent

`static [Rng.number](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.number "External link")(lower, upper)`

`static [Rng.octet](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.octet "External link")()`

### Remarks

The number returned is an integer selected at random from the set {*nLower*, ..., *nUpper*}.

### Example

This will generate 10 random numbers in the range between -1 million and +1 million:

```

Dim i As Integer
For i = 1 To 10
	Debug.Print RNG_Number(-1000000, 1000000)
Next

```

This will generate 8 random bits from {0, 1}:

```

Dim i As Integer
For i = 1 To 8
	Debug.Print RNG_Number(0, 1);
Next
Debug.Print

```

### See Also

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_Test"></a>RNG_Test
-----------------------------

Carries out a NIST SP800-90 health check 
and FIPS140-2 statistical tests on the random number generator.

### VBA/VB6 Syntax

`Public Declare Function RNG_Test Lib "diCryptoSys.dll"
    (ByVal strFileName As String) As Long`

`nRet = RNG_Test(strFileName)`

### C/C++ Syntax

`long __stdcall  RNG_Test(const char *szFileName);`

### Parameters

*szFileName*

:   [in] containing the full path name of a file
to be created containing the results of the test.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Rng.Test Method](#M_Rng_Test)  

### Remarks

If the file specified in `strFileName` does not exist, it will be created.
If it already exists, it will be overwritten without warning. If no directory path
is specified, the file will be created in the current default directory.
This function carries out, on demand, the health testing procedure from section 11.3 of 
[[SP80090A](#SP80090A)] and the statistical tests for randomness from 
section 4.9.1 of the October 2001 version of FIPS-140-2 [[FIPS140](#FIPS140)].
The statistical test results and the 20,000-bit sample are written to a text file. 
Specify an empty (`""`) or NULL *szFileName* to avoid creating an output file and just
carry out the tests. The statistical tests have since been removed from FIPS-140-2, but we do them anyway.
If any tests fail, a non-zero error code will be returned.

### Example

```

    Dim nRet As Long
    nRet = RNG_Test("Fips140t.txt")

```

Will create the results file "Fips140t.txt" in the default directory.
An example file is

```

FIPS140-2 test for 20000 bits (2500 bytes) at Sat Feb 15 18:28:30 2003

1. Monobits test n1 = 9909 (9725 - 10275)
   Passed Monobits test.
2. Poker test X = 19.69 (2.16 - 46.17)
   Passed Poker test.
3. Runs test:
     Run len:   1    2    3    4    5    6+
     Gaps:   2507, 1236, 679, 319, 147, 147
     Blocks: 2575, 1239, 633, 290, 138, 161
     Min:   (2315, 1114, 527, 240, 103, 103)
     Avg:   (2500, 1250, 625, 312, 156, 156)
     Max:   (2685, 1386, 723, 384, 209, 209)
     Pass:      Y    Y    Y    Y    Y    Y
   Passed Runs test.
4. Long runs test: Gmax = 17 Bmax = 11 (26)
   Passed Long Run test.
Passed FIPS140-2 test.
Test sample was:-
BFB1EF06A74AB69698ED...

```

### See Also

-

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_TestDRBGVS"></a>RNG_TestDRBGVS
-----------------------------------------

Tests the random number generator for conformance to NIST SP 800-90A using the relevant test specified in the
Deterministic Random Bit Generator Validation System (DRBGVS).

### VBA/VB6 Syntax

`Public Declare Function RNG_TestDRBGVS Lib "diCryptoSys.dll" (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal nReturnedBitsLen As Long, ByVal strEntropyInput As String, ByVal strNonce As String, ByVal strPersonalizationString As String, ByVal strAdditionalInput1 As String, ByVal strEntropyReseed As String, ByVal strAdditionalInputReseed As String, ByVal strAdditionalInput2 As String, ByVal nOptions As Long) As Long`

`nRet = RNG_TestDRBGVS(strOutput, nMaxChars, nReturnedBitsLen, strEntropyInput, strNonce, strPersonalizationString,  strAdditionalInput1, strEntropyReseed, strAdditionalInputReseed, strAdditionalInput2, nOptions)`

### C/C++ Syntax

`long __stdcall  RNG_TestDRBGVS(char *szOutput, long nMaxChars, long nReturnedBitsLen, const char *szEntropyInput, 
	const char *szNonce, const char *szPersonalizationString, const char *szAdditionalInput1, 
	const char *szEntropyReseed, const char *szAdditionalInputReseed, const char *szAdditionalInput2, long nOptions);`

### Parameters

*szOutput*

:   [out] to receive the ReturnedBits in hexadecimal format.

*nMaxChars*

:   [in] specifying the maximum number of hexadecimal characters to be received.

*nReturnedBitsLen*

:   [in] specifying the number of bits to be returned from each call to the generate function in the test.

*szEntropyInput*

:   [in] containing the EntropyInput value in hex format.

*szNonce*

:   [in] containing the Nonce value in hex format.

*szPersonalizationString*

:   [in] containing the PersonalizationString value in hex format.

*szAdditionalInput1*

:   [in] containing the first AdditionalInput value in hex format.

*szEntropyReseed*

:   [in] containing the EntropyReseed value in hex format.

*szAdditionalInputReseed*

:   [in] containing the AdditionalInputReseed value in hex format.

*szAdditionalInput2*

:   [in] containing the second AdditionalInput value in hex format.

*nOptions*

:   [in] Option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string; 
otherwise it returns a negative [error code](#errorcodes).

### .NET Equivalent

[Rng.TestDrbgvs Method](#M_Rng_TestDrbgvs)  

### Python Equivalent

`static [Rng.test_drbgvs](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.test_drbgvs "External link")(returnedBitsLen, entropyInput, nonce, personalizationString, additionalInput1, entropyReseed, additionalInputReseed, additionalInput2)`

### Remarks

The test procedure, the input values and the expected output are described in the [[DRBGVS](#DRBGVS)] document and associated test vectors. 
**[Changed in v6.22]** The relevant DRBG mechanism is `HMAC_DRBG SHA-512` without prediction resistance.
Use the empty string `""` to pass a zero-length input. All hex strings must have an even number of characters.

### Example

```

' drbgtestvectors/drbgvectors_pr_false/HMAC_DRBG.txt (line 22654)
' # CAVS 14.3
' # DRBG800-90A information for "drbg_pr"
' # Generated on Tue Apr 02 15:32:12 2013
Dim nRet As Long
Dim strOutput As String
Dim nMaxChars As Long
' Set input values in hex
Const nReturnedBitsLen As Long = 2048
Const strEntropyInput As String = "da740cbc36057a8e282ae717fe7dfbb245e9e5d49908a0119c5dbcf0a1f2d5ab"
Const strNonce As String = "46561ff612217ba3ff91baa06d4b5440"
Const strPersonalizationString As String = "fc227293523ecb5b1e28c87863626627d958acc558a672b148ce19e2abd2dde4"
Const strAdditionalInput1 As String = "b7998998eaf9e5d34e64ff7f03de765b31f407899d20535573e670c1b402c26a"
Const strEntropyReseed As String = "1d61d4d8a41c3254b92104fd555adae0569d1835bb52657ec7fbba0fe03579c5"
Const strAdditionalInputReseed As String = "b9ed8e35ad018a375b61189c8d365b00507cb1b4510d21cac212356b5bbaa8b2"
Const strAdditionalInput2 As String = "2089d49d63e0c4df58879d0cb1ba998e5b3d1a7786b785e7cf13ca5ea5e33cfd"
Const strExpectedBits = "5b70f3e4da95264233efbab155b828d4e231b67cc92757feca407cc9615a6608" & _
	"71cb07ad1a2e9a99412feda8ee34dc9c57fa08d3f8225b30d29887d20907d123" & _
	"30fffd14d1697ba0756d37491b0a8814106e46c8677d49d9157109c402ad0c24" & _
	"7a2f50cd5d99e538c850b906937a05dbb8888d984bc77f6ca00b0e3bc97b16d6" & _
	"d25814a54aa12143afddd8b2263690565d545f4137e593bb3ca88a37b0aadf79" & _
	"726b95c61906257e6dc47acd5b6b7e4b534243b13c16ad5a0a1163c0099fce43" & _
	"f428cd27c3e6463cf5e9a9621f4b3d0b3d4654316f4707675df39278d5783823" & _
	"049477dcce8c57fdbd576711c91301e9bd6bb0d3e72dc46d480ed8f61fd63811"

' Print output details
Debug.Print "# HMAC_DRBG options: SHA-512"
Debug.Print "[SHA-512]"
Debug.Print "[PredictionResistance = False]"
Debug.Print "[EntropyInputLen = " & Len(strEntropyInput) * 8 / 2 & "]"
Debug.Print "[NonceLen = " & Len(strNonce) * 8 / 2 & "]"
Debug.Print "[PersonalizationStringLen = " & Len(strPersonalizationString) * 8 / 2 & "]"
Debug.Print "[AdditionalInputLen = " & Len(strAdditionalInput1) * 8 / 2 & "]"
Debug.Print
Debug.Print "COUNT = 0"
Debug.Print "EntropyInput = " & strEntropyInput
Debug.Print "Nonce = " & strNonce
Debug.Print "PersonalizationString = " & strPersonalizationString
Debug.Print "AdditionalInput = " & strAdditionalInput1
Debug.Print "EntropyInputReseed = " & strEntropyReseed
Debug.Print "AdditionalInputReseed = " & strAdditionalInputReseed
Debug.Print "AdditionalInput = " & strAdditionalInput2

' Perform the DRBGVS test, dimensioning output string first
strOutput = String(nReturnedBitsLen * 2 / 8, " ")
nRet = RNG_TestDRBGVS(strOutput, Len(strOutput), nReturnedBitsLen, strEntropyInput, strNonce, _
	strPersonalizationString, strAdditionalInput1, _
	strEntropyReseed, strAdditionalInputReseed, strAdditionalInput2, 0)
Debug.Print "ReturnedBits = " & strOutput
Debug.Print "ExpectedBits = " & strExpectedBits
Debug.Assert strOutput = strExpectedBits

```

```

# HMAC_DRBG options: SHA-512
[SHA-512]
[PredictionResistance = False]
[EntropyInputLen = 256]
[NonceLen = 128]
[PersonalizationStringLen = 256]
[AdditionalInputLen = 256]

COUNT = 0
EntropyInput = da740cbc36057a8e282ae717fe7dfbb245e9e5d49908a0119c5dbcf0a1f2d5ab
Nonce = 46561ff612217ba3ff91baa06d4b5440
PersonalizationString = fc227293523ecb5b1e28c87863626627d958acc558a672b148ce19e2abd2dde4
AdditionalInput = b7998998eaf9e5d34e64ff7f03de765b31f407899d20535573e670c1b402c26a
EntropyInputReseed = 1d61d4d8a41c3254b92104fd555adae0569d1835bb52657ec7fbba0fe03579c5
AdditionalInputReseed = b9ed8e35ad018a375b61189c8d365b00507cb1b4510d21cac212356b5bbaa8b2
AdditionalInput = 2089d49d63e0c4df58879d0cb1ba998e5b3d1a7786b785e7cf13ca5ea5e33cfd
ReturnedBits = 5b70f3e4da95264233efbab155b828d4e231b67cc92757feca407cc9615a6608...
ExpectedBits = 5b70f3e4da95264233efbab155b828d4e231b67cc92757feca407cc9615a6608...

```

### See Also

[`RNG_Test`](#RNG_Test)

[[Contents](#topofpage)] [[Index](#index)]

<a id="RNG_UpdateSeedFile"></a>RNG_UpdateSeedFile
-------------------------------------------------

Updates an RNG seed file.

### VBA/VB6 Syntax

`Public Declare Function RNG_UpdateSeedFile Lib "diCryptoSys.dll" (ByVal strSeedFile As String, ByVal nOptions As Long) As Long`

`nRet = RNG_UpdateSeedFile(strSeedFile, nOptions)`

### C/C++ Syntax

`long __stdcall  RNG_UpdateSeedFile(const char *szSeedFile, long nOptions);`

### Parameters

*szSeedFile*
:   [in] specifying the seed file to be updated.

*nOptions*
:   [in] option flags: not used in this release. Specify zero.

### Returns (VBA/C)

If successful, the return value is zero; otherwise it returns a non-zero [error code](#errorcodes). 

### .NET Equivalent

[Rng.UpdateSeedFile Method](#M_Rng_UpdateSeedFile)  

### C++ (STL) Equivalent

`static int [crsysapi::Rng::UpdateSeedFile](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a6ea18a6064720dd4270d18c08ca51776 "External link") (const std::string &seedFile)`

### Python Equivalent

`static [Rng.update_seedfile](https://cryptosys.net/pydocapi/class-stubs/Rng.html#crsysapi.Rng.update_seedfile "External link")(seedfilename)`

### Remarks

The seed file must be writable by the user. Use this function at periodic intervals or when exiting your application.
If the file does not exist it will be created. Any existing file of the same name will be overwritten without warning. 

### Example

See the example in [`RNG_Initialize`](#RNG_Initialize).

### See Also

[`RNG_Initialize`](#RNG_Initialize)
[`RNG_MakeSeedFile`](#RNG_MakeSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_AddBytes"></a>SHA1_AddBytes
---------------------------------------

Adds an array of bytes to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA1_AddBytes Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA1_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  SHA1_AddBytes(long hContext, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the SHA-1 context.

*lpData*
:   [in] array containing the next part of the message
to be hashed.

*nDataLen*
:   [in] containing the number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.AddData Method](#M_Sha1_AddData_Byte) (Byte[])  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA1_Init`. This function may be called many times before creating
the final message digest with `SHA1_HexDigest`.
`SHA1_AddString` may also be called.

### Example

This example creates the hash of the three-character string "abc" using a mixture of calls
to `SHA1_AddBytes` and `SHA1_AddString`.

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long
    Dim abData(2) As Byte

    ' Set context handle
    hContext = SHA1_Init()
    ' Remember to check for an invalid handle
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Set up a test array of bytes
    abData(0) = Asc("a")
    abData(1) = &H62    ' same as Asc("b")
    ' Add mixture of bytes and strings
    nRet = SHA1_AddBytes(hContext, abData(0), 2)
    nRet = SHA1_AddString(hContext, "c")

    ' Set strDigest to be 40 chars
    strDigest = String(40, " ")
    nRet = SHA1_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

a9993e364706816aba3e25717850c26c9cd0d89d

```

### See Also

[`SHA1_Init`](#SHA1_Init)
[`SHA1_AddString`](#SHA1_AddString)
[`SHA1_HexDigest`](#SHA1_HexDigest)
[`SHA1_Reset`](#SHA1_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_AddString"></a>SHA1_AddString
-----------------------------------------

Adds a string of ascii characters to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA1_AddString Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strMessage As String) As Long`

`nRet = SHA1_AddString(hContext, strMessage)`

### C/C++ Syntax

`long __stdcall  SHA1_AddString(long hContext, const char *szMessage);`

### Parameters

*hContext*
:   [in] handle to the SHA-1 context.

*szMessage*
:   [in] containing the next part of the message
to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.AddData Method](#M_Sha1_AddData_String) (String)  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA1_Init`. This function may be called many times before creating
the final message digest with `SHA1_HexDigest`
This function should only be used to hash strings of "printable" ANSI characters.
To hash a string that contains binary characters, such as ascii zero, use `SHA1_AddBytes`.

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long

    ' Set context handle
    hContext = SHA1_Init()

    Debug.Print "SHA1_Init() returns handle = " & Hex(hContext)
    ' Remember to check for an invalid handle
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Add strings one by one
    nRet = SHA1_AddString(hContext, "a")
    nRet = SHA1_AddString(hContext, "bc")

    ' Set strDigest to be 40 chars
    strDigest = String(40, " ")
    nRet = SHA1_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

SHA1_Init() returns handle = 10029CB0
a9993e364706816aba3e25717850c26c9cd0d89d

```

Note that the actual value of the handle is not important, just that it should not be zero.

### See Also

[`SHA1_Init`](#SHA1_Init)
[`SHA1_AddBytes`](#SHA1_AddBytes)
[`SHA1_HexDigest`](#SHA1_HexDigest)
[`SHA1_Reset`](#SHA1_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_BytesHash"></a>SHA1_BytesHash
-----------------------------------------

Creates a SHA-1 message digest in `Byte` array format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function SHA1_BytesHash Lib "diCryptoSys.dll"
    (ByRef lpDigest As Byte, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA1_BytesHash(abDigest(0), abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA1_BytesHash(unsigned char *digest, const unsigned char *lpData, long nDataLen);`

### Parameters

*digest*
:   [out] array to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.BytesHash Method](#M_Sha1_BytesHash)  

### Remarks

This function differs from other SHA1 functions in that it creates a digest in `Byte` array
format. This is particularly useful when you need to carry out repeated hash operations.
*lpDigest* must be at least 20 (`API_MAX_SHA1_BYTES`)bytes long. 

### Examples

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(19) As Byte ' Create 20-byte array to receive digest
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute SHA-1 hash digest
    nRet = SHA1_BytesHash(abDigest(0), abData(0), 3)
    
    ' Print resulting bytes in hex format
    Debug.Print nRet; cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

 0 A9993E364706816ABA3E25717850C26C9CD0D89D

```

This second example shows how to carry out repeated hashes of the digest.

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(19) As Byte ' Create 20-byte array to receive digest
    Dim i As Integer
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute SHA-1 hash digest of input
    nRet = SHA1_BytesHash(abDigest(0), abData(0), 3)
    
    ' Now carry out repeated hashes of the digest
    For i = 2 To 1000
        nRet = SHA1_BytesHash(abDigest(0), abDigest(0), 20)
    Next
   
    ' Print H(1000) in hex format
    Debug.Print cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

 58EEDCE24AD638F2ABF39E4B13D5726802DEF2C1

```

### See Also

[`SHA1_BytesHexHash`](#SHA1_BytesHexHash)
[`PBE_Kdf2`](#PBE_Kdf2)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_BytesHexHash"></a>SHA1_BytesHexHash
-----------------------------------------------

Creates a SHA-1 message digest in hexadecimal format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function SHA1_BytesHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA1_BytesHexHash(strDigest, abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA1_BytesHexHash(char *szDigest, const unsigned char *lpData, long nDataLen);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.HexHash Method](#M_Sha1_HexHash_Byte) (Byte[])  

### COM/ASP Equivalent

`sha1.HexHexHash  

Public Function HexHexHash(ByVal strHexData As String) As String`

See [`sha1.HexHexHash`](#x_hexhexhash).

### Remarks

*szDigest* must be at least 40 (`API_MAX_SHA1_CHARS`) characters long (41 in a C program). 

### Example

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    ' Alternative way of making sure string is 40 chars long
    Dim strDigest As String * 40

    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")

    nRet = SHA1_BytesHexHash(strDigest, abData(0), 3)
    Debug.Print nRet; strDigest

```

This should result in output as follows:

```

 0 a9993e364706816aba3e25717850c26c9cd0d89d

```

### See Also

[`SHA1_StringHexHash`](#SHA1_StringHexHash)
[`SHA1_FileHexHash`](#SHA1_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_FileHexHash"></a>SHA1_FileHexHash
---------------------------------------------

Creates a SHA-1 message digest in hexadecimal format
from a file.

### VBA/VB6 Syntax

`Public Declare Function SHA1_FileHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strFileName As String, ByVal strMode As String) As Long`

`nRet = SHA1_FileHexHash(strDigest, strFileName, strMode)`

### C/C++ Syntax

`long __stdcall  SHA1_FileHexHash(char *szDigest, const char *szFileName, const char *szMode);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szFileName*
:   [in] with full path name of file.

*szMode*
:   [in] to set mode: "t" or "b"

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.FileHexHash Method](#M_Sha1_FileHexHash)  

[Sha1.FileTextHexHash Method](#M_Sha1_FileTextHexHash)  

### COM/ASP Equivalent

`sha1.FileHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String  

sha1.FileTextHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String`

See [sha1.FileHexHash](#x_filehexhash), [`sha1.FileTextHexHash`](#x_filetexthexhash).

### Remarks

*szDigest* must be at least 40 (`API_MAX_SHA1_CHARS`) characters long (41 in a C program). 
Setting *szMode* equal
to "t" or "T" will hash file in "text" mode treating a CR-LF pair as a single newline character.
Setting *szMode* equal to "b" or "B" will hash file in "binary" mode treating
CR-LF as two binary characters (default).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim strFileName As String

    strFileName = "hello.txt"
    ' Set strDigest to be 40 chars
    strDigest = String(40, " ")
    ' Make sha1sum in text mode (treating CR-LF as single NL)
    nRet = SHA1_FileHexHash(strDigest, strFileName, "t")
    Debug.Print "t " & nRet; strDigest
    ' Do in binary mode (treating CR-LF as two binary bytes)
    nRet = SHA1_FileHexHash(strDigest, strFileName, "b")
    Debug.Print "b " & nRet; strDigest

```

For a 13-byte text file "hello.txt" in the default directory containing the 11 characters
"hello world" followed by CR-LF this
should result in output as follows:

```

t  0 22596363b3de40b06f981fb85d82312e8c0ed511
b  0 88a5b867c3d110207786e66523cd1e4a484da697

```

### See Also

[`SHA1_StringHexHash`](#SHA1_StringHexHash)
[`SHA1_BytesHexHash`](#SHA1_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_HexDigest"></a>SHA1_HexDigest
-----------------------------------------

Returns the final message digest value as a hex string.

### VBA/VB6 Syntax

`Public Declare Function SHA1_HexDigest Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal hContext As Long) As Long`

`nRet = SHA1_HexDigest(strDigest, hContext)`

### C/C++ Syntax

`long __stdcall  SHA1_HexDigest(char *szDigest, long hContext);`

### Parameters

*szDigest*
:   [out] variable long enough to receive the final message digest.

*hContext*
:   [in] handle to the SHA-1 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.HexDigest Method](#M_Sha1_HexDigest)  

### Remarks

This operation delivers the result of Add operations since the last Init or Reset operation.
The handle to the context *hContext* must have been set up with a
prior call to `SHA1_Init`. The string variable *szDigest* must
have been set up with at least 40 (`API_MAX_SHA1_CHARS`) characters (41 in a C program)
to receive the digest value in hex format.
Note that this digest operation is a destructive, read-once operation.
Once it has been performed,
the context must be reset before being used to calculate another digest value.

### Example

See [`SHA1_AddString`](#SHA1_AddString) and
[`SHA1_AddBytes`](#SHA1_AddBytes)

### See Also

[`SHA1_Init`](#SHA1_Init)
[`SHA1_AddString`](#SHA1_AddString)
[`SHA1_AddBytes`](#SHA1_AddBytes)
[`SHA1_Reset`](#SHA1_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_Hmac"></a>SHA1_Hmac
-------------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the SHA-1 hash function.

### VBA/VB6 Syntax

`Public Declare Function SHA1_Hmac Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long) As Long`

`nRet = SHA1_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA1_Hmac(char *szDigest, const unsigned char *textBytes, long textLen, const unsigned char *lpKeyBytes, long keyLen);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*textBytes*
:   [in] array containing the text of the message.

*textLen*
:   [in] containing the number of bytes in the array

*lpKeyBytes*
:   [in] array containing the key.

*keyLen*
:   [in] containing the number of bytes in the key

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.Hmac Method](#M_Sha1_Hmac_ByteByte) (Byte[], Byte[])  

### Remarks

*szDigest* must be at least 40 (`API_MAX_SHA1_CHARS`) characters long (41 in a C program).

### Example

This example reproduces the three test vectors from RFC 2014 using SHA-1 instead of MD5.
Note that the results will be different from those given in RFC 2104 because a different
hash function is used (RFC 2104 uses MD5).

```

    Dim nRet As Long
    Dim abData() As Byte
    Dim abKey() As Byte
    Dim i As Integer
    Dim nDataLen As Long, nKeyLen As Long
    Dim strDigest As String * 40

    ' Test No 1.
    ' Set key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HB
    Next
    ' Convert string to byte array
    abData() = StrConv("Hi There", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    ' Create HMAC digest
    nRet = SHA1_Hmac(strDigest, abData(0), nDataLen, abKey(0), 16)
    Debug.Print 1; nRet; strDigest

    ' Test No 2.
    abKey() = StrConv("Jefe", vbFromUnicode)
    nKeyLen = UBound(abKey) + 1
    abData() = StrConv("what do ya want for nothing?", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    nRet = SHA1_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
    Debug.Print 2; nRet; strDigest

    ' Test No 3.
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HAA
    Next
    ReDim abData(49)
    For i = 0 To 49
        abData(i) = &HDD
    Next
    nRet = SHA1_Hmac(strDigest, abData(0), 50, abKey(0), 16)
    Debug.Print 3; nRet; strDigest

```

This should result in output as follows:

```

 1  0 675b0b3a1b4ddf4e124872da6c2f632bfed957e9
 2  0 effcdf6ae5eb2fa2d27416d5f184df9c259a7c79
 3  0 d730594d167e35d5956fd8003d0db3d3f46dc7bb

```

### See Also

[`SHA1_HmacHex`](#SHA1_HmacHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_HmacHex"></a>SHA1_HmacHex
-------------------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the SHA-1 hash function, passing its arguments in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function SHA1_HmacHex Lib "diCryptoSys.dll" 
    (ByVal strDigest As String, ByVal strHexData As String, 
    ByVal strHexKey As String) As Long`

`nRet = SHA1_Hmac(strDigest, strHexData, strHexKey)`

### C/C++ Syntax

`long __stdcall  SHA1_HmacHex(char *szDigest, const char *sHexText, const char *sHexKey);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*sHexText*
:   [in] containing the text of the message in hexadecimal format.

*sHexKey*
:   [in] containing the key in hexadecimal format.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.Hmac Method](#M_Sha1_Hmac_StringString) (String, String)  

### COM/ASP Equivalent

`sha1.HmacHex  

Public Function HmacHex(ByVal strHexText As String, ByVal strHexKey As String) As String`

See [`sha1.HmacHex`](#x_hmachex).

### Remarks

The string variable *szDigest* must be at least 40 (`API_MAX_SHA1_CHARS`) characters long (41 in a C program). 
*szData* and *szKey* are expected to be an even number of characters long, 
i.e. representing complete byte values. Any trailing odd character will be ignored.

### Example

```

'Example from Wei Dai's Crypto++ test vectors
'fipstest.cpp - written and placed in the public domain by Wei Dai
'From http://trolocsis.com/crypto++/fipstest_8cpp-source.html
'MAC_KnownAnswerTest<HMAC<SHA> >(
'"303132333435363738393a3b3c3d3e3f40414243",
'"Sample #2",
'"0922d3405faa3d194f82a45830737d5cc6c75d24");

    Dim nRet As Long
    Dim strDigest As String * 40
    Dim strMessage As String
    Dim sHexMsg As String
    Dim sCorrect As String
    
    sCorrect = "0922d3405faa3d194f82a45830737d5cc6c75d24"
    
    ' Convert data to hex format
    sHexMsg = cnvHexStrFromString("Sample #2")
    nRet = SHA1_HmacHex(strDigest, sHexMsg, "303132333435363738393a3b3c3d3e3f40414243")
    Debug.Print "Digest =" & strDigest
    Debug.Print "Correct=" & sCorrect
    Debug.Assert (strDigest = sCorrect)

```

This should result in output as follows:

```

Digest =0922d3405faa3d194f82a45830737d5cc6c75d24
Correct=0922d3405faa3d194f82a45830737d5cc6c75d24

```

### See Also

[`SHA1_Hmac`](#SHA1_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_Init"></a>SHA1_Init
-------------------------------

Initialises the SHA-1 context ready for subsequent calls with
`SHA1_AddString`, `SHA1_AddBytes`, and `SHA1_HexDigest`.

### VBA/VB6 Syntax

`Public Declare Function SHA1_Init Lib "diCryptoSys.dll"
    () As Long`

`Dim hContext As Long  

    hContext = SHA1_Init()`

### C/C++ Syntax

`long __stdcall  SHA1_Init(void);`

### Parameters

None.

### Returns (VBA/C)

non-zero handle of the SHA-1 context *hContext*.
Returns zero if an error occurs.

### .NET Equivalent

[Sha1.Init Method](#M_Sha1_Init)  

### Remarks

It is important to check for a zero context handle and stop if one occurs.

### Example

See [`SHA1_HexDigest`](#SHA1_HexDigest)

### See Also

[`SHA1_AddString`](#SHA1_AddString)
[`SHA1_AddBytes`](#SHA1_AddBytes)
[`SHA1_HexDigest`](#SHA1_HexDigest)
[`SHA1_Reset`](#SHA1_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_Reset"></a>SHA1_Reset
---------------------------------

Resets the context.

### VBA/VB6 Syntax

`Public Declare Function SHA1_Reset Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = SHA1_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  SHA1_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the SHA-1 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.Reset Method](#M_Sha1_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

This trivial example creates a context handle and then destroys it.

```

    Dim nRet As Long
    Dim hContext As Long

    hContext = SHA1_Init()
    nRet = SHA1_Reset(hContext)

```

### See Also

[`SHA1_Init`](#SHA1_Init)
[`SHA1_AddString`](#SHA1_AddString)
[`SHA1_AddBytes`](#SHA1_AddBytes)
[`SHA1_HexDigest`](#SHA1_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA1_StringHexHash"></a>SHA1_StringHexHash
-------------------------------------------------

Creates a SHA-1 message digest in hexadecimal format
from a message of `String` type.

### VBA/VB6 Syntax

`Public Declare Function SHA1_StringHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strMessage As String) As Long`

`nRet = SHA1_StringHexHash(strDigest, strMessage)`

### C/C++ Syntax

`long __stdcall  SHA1_StringHexHash(char *szDigest, const char *szMessage);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szMessage*
:   [in] containing the message to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha1.HexHash Method](#M_Sha1_HexHash_String) (String)  

### COM/ASP Equivalent

`sha1.StringHexHash  

Public Function StringHexHash(ByVal strData As String) As String`

See [`sha1.StringHexHash`](#x_stringhexhash).

### Remarks

*szDigest* must be at least 40 (`API_MAX_SHA1_CHARS`) characters long (41 in a C program).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    ' Set strDigest to be 40 chars
    strDigest = String(40, " ")
    nRet = SHA1_StringHexHash(strDigest, "abc")
    Debug.Print strDigest

    nRet = SHA1_StringHexHash(strDigest, _
        "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
    Debug.Print strDigest

```

This should result in output as follows:

```

a9993e364706816aba3e25717850c26c9cd0d89d
84983e441c3bd26ebaae4aa1f95129e5e54670f1

```

### See Also

[`SHA1_FileHexHash`](#SHA1_FileHexHash)
[`SHA1_BytesHexHash`](#SHA1_BytesHexHash)
[`SHA1_BytesHash`](#SHA1_BytesHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_AddBytes"></a>SHA2_AddBytes
---------------------------------------

Adds an array of bytes to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA2_AddBytes Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA2_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  SHA2_AddBytes(long hContext, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the SHA-2 context.

*lpData*
:   [in] array containing the next part of the message
to be hashed.

*nDataLen*
:   [in] containing the number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.AddData Method](#M_Sha256_AddData_Byte) (Byte[])  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA2_Init`. This function may be called many times before creating
the final message digest with `SHA2_HexDigest`.
`SHA2_AddString` may also be called.

### Example

This example creates the hash of the three-character string "abc" using a mixture of calls
to `SHA2_AddBytes` and `SHA2_AddString`.

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long
    Dim abData(2) As Byte

    ' Set context handle
    hContext = SHA2_Init()
    ' Remember to check for an invalid handle
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Set up a test array of bytes
    abData(0) = Asc("a")
    abData(1) = &H62    ' same as Asc("b")
    ' Add mixture of bytes and strings
    nRet = SHA2_AddBytes(hContext, abData(0), 2)
    nRet = SHA2_AddString(hContext, "c")

    ' Set strDigest to be 64 chars
    strDigest = String(64, " ")
    nRet = SHA2_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

```

### See Also

[`SHA2_Init`](#SHA2_Init)
[`SHA2_AddString`](#SHA2_AddString)
[`SHA2_HexDigest`](#SHA2_HexDigest)
[`SHA2_Reset`](#SHA2_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_AddString"></a>SHA2_AddString
-----------------------------------------

Adds a string of ascii characters to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA2_AddString Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strMessage As String) As Long`

`nRet = SHA2_AddString(hContext, strMessage)`

### C/C++ Syntax

`long __stdcall  SHA2_AddString(long hContext, const char *szMessage);`

### Parameters

*hContext*
:   [in] handle to the SHA-2 context.

*szMessage*
:   [in] containing the next part of the message
to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.AddData Method](#M_Sha256_AddData_String) (String)  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA2_Init`. This function may be called many times before creating
the final message digest with `SHA2_HexDigest`
This function should only be used to hash strings of "printable" ANSI characters.
To hash a string that contains binary characters, such as ascii zero, use `SHA1_AddBytes`.

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim hContext As Long
    Dim i As Long
    Dim sA1000 As String

    ' Set context handle
    hContext = SHA2_Init()
    If hContext = 0 Then
        MsgBox "Failed to set context"
        Exit Function
    End If

    ' Create a string of 1000 'a's
    sA1000 = String(1000, "a")

    ' Add 1000 times => one million repetitions of "a"
    For i = 1 To 1000
        nRet = SHA2_AddString(hContext, sA1000)
    Next

    ' Set strDigest to be 64 chars - don't forget!!
    strDigest = String(64, " ")
    nRet = SHA2_HexDigest(strDigest, hContext)
    Debug.Print strDigest

```

This should result in output as follows:

```

cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0

```

Note that the actual value of the handle is not important, just that it should not be zero.

### See Also

[`SHA2_Init`](#SHA2_Init)
[`SHA2_AddBytes`](#SHA2_AddBytes)
[`SHA2_HexDigest`](#SHA2_HexDigest)
[`SHA2_Reset`](#SHA2_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_BytesHash"></a>SHA2_BytesHash
-----------------------------------------

Creates a SHA-256 message digest in `Byte` array format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function SHA2_BytesHash Lib "diCryptoSys.dll"
    (ByRef lpDigest As Byte, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA2_BytesHash(abDigest(0), abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA2_BytesHash(unsigned char *lpDigest, const unsigned char *lpData, long nDataLen);`

### Parameters

*lpDigest*
:   [out] array to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.BytesHash Method](#M_Sha256_BytesHash)  

### Remarks

This function differs from other SHA2 functions in that it creates a digest in `Byte` array
format. This is particularly useful when you need to carry out repeated hash operations.
*lpDigest* must be at least 32 (`API_MAX_SHA2_BYTES`) bytes long. 

### Examples

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(31) As Byte ' Create 32-byte array to receive digest
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute SHA-256 hash digest
    nRet = SHA2_BytesHash(abDigest(0), abData(0), 3)
    
    ' Print resulting bytes in hex format
    Debug.Print nRet; cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

 0 BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

```

This second example shows how to carry out repeated hashes of the digest.

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    Dim abDigest(31) As Byte ' Create 32-byte array to receive digest
    Dim i As Integer
    
    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")
    
    ' Compute SHA-256 hash digest of input
    nRet = SHA2_BytesHash(abDigest(0), abData(0), 3)
    
    ' Now carry out repeated hashes of the digest
    For i = 2 To 1000
        nRet = SHA2_BytesHash(abDigest(0), abDigest(0), 32)
    Next
   
    ' Print H(1000) in hex format
    Debug.Print cnvHexStrFromBytes(abDigest)

```

This should result in output as follows:

```

FC8A6B86A13F71CD9A67F558AB6FD82A3DD89186163A017ED8051ACF6D3F8F99

```

### See Also

[`SHA1_BytesHash`](#SHA1_BytesHash)
[`PBE_Kdf2`](#PBE_Kdf2)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_BytesHexHash"></a>SHA2_BytesHexHash
-----------------------------------------------

Creates a SHA-256 message digest in hexadecimal format
from a message in `Byte` array format.

### VBA/VB6 Syntax

`Public Declare Function SHA2_BytesHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA2_BytesHexHash(strDigest, abData(0), nDataLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA2_BytesHexHash(char *szDigest, const unsigned char *lpData, long nDataLen);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*lpData*
:   [in] array containing the message to be hashed.

*nDataLen*
:   [in] containing number of bytes in the array.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.HexHash Method](#M_Sha256_HexHash_Byte) (Byte[])  

### COM/ASP Equivalent

`sha256.HexHexHash  

Public Function HexHexHash(ByVal strHexData As String) As String`

See [`sha256.HexHexHash`](#x_hexhexhash).

### Remarks

*szDigest* must be at least 64 (`API_MAX_SHA2_CHARS`) characters long (65 in a C program).

### Example

```

    Dim nRet As Long
    Dim abData(2) As Byte   ' Create 3-byte array (NB zero-based)
    ' Alternative way of making sure string is 64 chars long
    Dim strDigest As String * 64

    ' Setup byte array with "abc"
    abData(0) = Asc("a")
    abData(1) = Asc("b")
    abData(2) = Asc("c")

    nRet = SHA2_BytesHexHash(strDigest, abData(0), 3)
    Debug.Print nRet; strDigest

```

This should result in output as follows:

```

 0 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

```

### See Also

[`SHA2_StringHexHash`](#SHA2_StringHexHash)
[`SHA2_FileHexHash`](#SHA2_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_FileHexHash"></a>SHA2_FileHexHash
---------------------------------------------

Creates a SHA-256 message digest in hexadecimal format
from a file.

### VBA/VB6 Syntax

`Public Declare Function SHA2_FileHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strFileName As String, ByVal strMode As String) As Long`

`nRet = SHA2_FileHexHash(strDigest, strFileName, strMode)`

### C/C++ Syntax

`long __stdcall  SHA2_FileHexHash(char *szDigest, const char *szFileName, const char *szMode);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szFileName*
:   [in] with full path name of file.

*szMode*
:   [in] to set mode: "t" or "b"

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.FileHexHash Method](#M_Sha256_FileHexHash)  

[Sha256.FileTextHexHash Method](#M_Sha256_FileTextHexHash)  

### COM/ASP Equivalent

`sha256.FileHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String  

sha256.FileTextHexHash  

Public Function FileHexHash(ByVal strFileName As String) As String`

See [sha256.FileHexHash](#x_filehexhash), [`sha256.FileTextHexHash`](#x_filetexthexhash).

### Remarks

*szDigest* must be at least 64 (`API_MAX_SHA2_CHARS`) characters long (65 in a C program).
Setting *szMode* equal
to "t" or "T" will hash file in "text" mode treating a CR-LF pair as a single newline character.
Setting *szMode* equal to "b" or "B" will hash file in "binary" mode treating
CR-LF as two binary characters (default).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    Dim strFileName As String

    strFileName = "hello.txt"
    ' Set strDigest to be 64 chars
    strDigest = String(64, " ")
    ' Make sha1sum in text mode (treating CR-LF as single NL)
    nRet = SHA2_FileHexHash(strDigest, strFileName, "t")
    Debug.Print "t " & nRet; strDigest
    ' Do in binary mode (treating CR-LF as two binary bytes)
    nRet = SHA2_FileHexHash(strDigest, strFileName, "b")
    Debug.Print "b " & nRet; strDigest

```

For a 13-byte text file "hello.txt" in the default directory containing the 11 characters
"hello world" followed by CR-LF this
should result in output as follows:

```

t  0 a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
b  0 572a95fee9c0f320030789e4883707affe12482fbb1ea04b3ea8267c87a890fb

```

### See Also

[`SHA2_StringHexHash`](#SHA2_StringHexHash)
[`SHA2_BytesHexHash`](#SHA2_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_HexDigest"></a>SHA2_HexDigest
-----------------------------------------

Returns the final message digest value as a hex string.

### VBA/VB6 Syntax

`Public Declare Function SHA2_HexDigest Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal hContext As Long) As Long`

`nRet = SHA2_HexDigest(strDigest, hContext)`

### C/C++ Syntax

`long __stdcall  SHA2_HexDigest(char *szDigest, long hContext);`

### Parameters

*szDigest*
:   [out] variable long enough to receive the final message digest.

*hContext*
:   [in] handle to the SHA-1 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.HexDigest Method](#M_Sha256_HexDigest)  

### Remarks

This operation delivers the result of Add operations since the last Init or Reset operation.
The handle to the context *hContext* must have been set up with a
prior call to `SHA1_Init`. The string variable *szDigest* must
have been set up with at least 64 (`API_MAX_SHA2_CHARS`) characters (65 in a C program)
to receive the digest value in hex format.
Note that this digest operation is a destructive, read-once operation.
Once it has been performed,
the context must be reset before being used to calculate another digest value.

### Example

See [`SHA2_AddString`](#SHA2_AddString) and
[`SHA2_AddBytes`](#SHA2_AddBytes)

### See Also

[`SHA2_Init`](#SHA2_Init)
[`SHA2_AddString`](#SHA2_AddString)
[`SHA2_AddBytes`](#SHA2_AddBytes)
[`SHA2_Reset`](#SHA2_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_Hmac"></a>SHA2_Hmac
-------------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the SHA-256 hash function.

### VBA/VB6 Syntax

`Public Declare Function SHA2_Hmac Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal nKeyLen As Long) As Long`

`nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  SHA2_Hmac(char *szDigest, const unsigned char *textBytes, long textLen, const unsigned char *lpKeyBytes, long keyLen);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*textBytes*
:   [in] array containing the text of the message.

*textLen*
:   [in] containing the number of bytes in the array

*lpKeyBytes*
:   [in] array containing the key.

*keyLen*
:   [in] containing the number of bytes in the key

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.Hmac Method](#M_Sha256_Hmac_ByteByte) (Byte[], Byte[])  

### Remarks

*szDigest* must be at least 64 (`API_MAX_SHA2_CHARS`) characters long (65 in a C program).

### Example

This example reproduces the three test vectors from RFC 2014 using SHA-256 instead of MD5.
Note that the results will be different from those given in RFC 2104 because a different
hash function is used (RFC 2104 uses MD5).

```

    Dim nRet As Long
    Dim abData() As Byte
    Dim abKey() As Byte
    Dim i As Integer
    Dim nDataLen As Long, nKeyLen As Long
    Dim strDigest As String * 64

    ' Test No 1.
    ' Set key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HB
    Next
    ' Convert string to byte array
    abData() = StrConv("Hi There", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    ' Create HMAC digest
    nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), 16)
    Debug.Print 1; nRet; strDigest

    ' Test No 2.
    abKey() = StrConv("Jefe", vbFromUnicode)
    nKeyLen = UBound(abKey) + 1
    abData() = StrConv("what do ya want for nothing?", vbFromUnicode)
    nDataLen = UBound(abData) + 1
    nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
    Debug.Print 2; nRet; strDigest

    ' Test No 3.
    ReDim abKey(15)
    For i = 0 To 15
        abKey(i) = &HAA
    Next
    ReDim abData(49)
    For i = 0 To 49
        abData(i) = &HDD
    Next
    nRet = SHA2_Hmac(strDigest, abData(0), 50, abKey(0), 16)
    Debug.Print 3; nRet; strDigest

```

This should result in output as follows:

```

 1  0 492ce020fe2534a5789dc3848806c78f4f6711397f08e7e7a12ca5a4483c8aa6
 2  0 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
 3  0 7dda3cc169743a6484649f94f0eda0f9f2ff496a9733fb796ed5adb40a44c3c1

```

### See Also

[`SHA1_Hmac`](#SHA1_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_HmacHex"></a>SHA2_HmacHex
-------------------------------------

Is a keyed-hash function that provides message
authentication using the HMAC algorithm and the SHA-256 hash function, passing its arguments in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function SHA2_HmacHex Lib "diCryptoSys.dll" 
    (ByVal strDigest As String, ByVal strHexData As String, 
    ByVal strHexKey As String) As Long`

`nRet = SHA2_HmacHex(strDigest, strHexData, strHexKey)`

### C/C++ Syntax

`long __stdcall  SHA2_HmacHex(char *szDigest, const char *sHexText, const char *sHexKey);`

### Parameters

*szDigest*
:   [out] variable of sufficient length to
receive the message digest in hex format.

*sHexText*
:   [in] containing the text of the message in hexadecimal format.

*sHexKey*
:   [in] containing the key in hexadecimal format.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.Hmac Method](#M_Sha256_Hmac_StringString) (String, String)  

### COM/ASP Equivalent

`sha256.HmacHex  

Public Function HmacHex(ByVal strHexText As String, ByVal strHexKey As String) As String`

See [`sha256.HmacHex`](#x_hmachex).

### Remarks

*szDigest* must be at least 64 (`API_MAX_SHA2_CHARS`) characters long (65 in a C program).
*szData* and *szKey* are expected to be an even number of characters long, 
i.e. representing complete byte values. Any trailing odd character will be ignored.

### Example

```

'Example from Wei Dai's Crypto++ test vectors
'fipstest.cpp - written and placed in the public domain by Wei Dai
'From http://trolocsis.com/crypto++/fipstest_8cpp-source.html
'MAC_KnownAnswerTest<HMAC<SHA256> >(
'"303132333435363738393a3b3c3d3e3f40414243",
'"abc",
'"D28363F335B2DAE468793A38680DEA9F7FB8BE1DCEDA197CDB3B1CB59A9F6422");

    Dim nRet As Long
    Dim strDigest As String * 64
    Dim strMessage As String
    Dim sHexMsg As String
    Dim sCorrect As String
    
    sCorrect = "d28363f335b2dae468793a38680dea9f7fb8be1dceda197cdb3b1cb59a9f6422"
    
    ' Convert data to hex format
    sHexMsg = cnvHexStrFromString("abc")
    nRet = SHA2_HmacHex(strDigest, sHexMsg, "303132333435363738393a3b3c3d3e3f40414243")
    Debug.Print "Digest =" & strDigest
    Debug.Print "Correct=" & sCorrect
    Debug.Assert (strDigest = sCorrect)

```

This should result in output as follows:

```

Digest =d28363f335b2dae468793a38680dea9f7fb8be1dceda197cdb3b1cb59a9f6422
Correct=d28363f335b2dae468793a38680dea9f7fb8be1dceda197cdb3b1cb59a9f6422

```

### See Also

[`SHA2_Hmac`](#SHA2_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_Init"></a>SHA2_Init
-------------------------------

Initialises the SHA-256 context ready for subsequent calls with
`SHA2_AddString`, `SHA2_AddBytes`, and `SHA2_HexDigest`.

### VBA/VB6 Syntax

`Public Declare Function SHA2_Init Lib "diCryptoSys.dll"
    () As Long`

`Dim hContext As Long  

    hContext = SHA2_Init()`

### C/C++ Syntax

`long __stdcall  SHA2_Init(void);`

### Parameters

None.

### Returns (VBA/C)

non-zero handle of the SHA-256 context *hContext*.
Returns zero if an error occurs.

### .NET Equivalent

[Sha256.Init Method](#M_Sha256_Init)  

### Remarks

It is important to check for a zero context handle and stop if one occurs.

### Example

See [`SHA2_HexDigest`](#SHA2_HexDigest)

### See Also

[`SHA2_AddString`](#SHA2_AddString)
[`SHA2_AddBytes`](#SHA2_AddBytes)
[`SHA2_HexDigest`](#SHA2_HexDigest)
[`SHA2_Reset`](#SHA2_Reset)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_Reset"></a>SHA2_Reset
---------------------------------

Resets the context.

### VBA/VB6 Syntax

`Public Declare Function SHA2_Reset Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = SHA2_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  SHA2_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the SHA-1 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.Reset Method](#M_Sha256_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

This trivial example creates a context handle and then destroys it.

```

    Dim nRet As Long
    Dim hContext As Long

    hContext = SHA2_Init()
    nRet = SHA2_Reset(hContext)

```

### See Also

[`SHA2_Init`](#SHA2_Init)
[`SHA2_AddString`](#SHA2_AddString)
[`SHA2_AddBytes`](#SHA2_AddBytes)
[`SHA2_HexDigest`](#SHA2_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA2_StringHexHash"></a>SHA2_StringHexHash
-------------------------------------------------

Creates a SHA-256 message digest in hexadecimal format
from a message of `String` type.

### VBA/VB6 Syntax

`Public Declare Function SHA2_StringHexHash Lib "diCryptoSys.dll"
    (ByVal strDigest As String, ByVal strMessage As String) As Long`

`nRet = SHA2_StringHexHash(strDigest, strMessage)`

### C/C++ Syntax

`long __stdcall  SHA2_StringHexHash(char *szDigest, const char *szMessage);`

### Parameters

*szDigest*
:   [out] to receive message digest.

*szMessage*
:   [in] containing the message to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha256.HexHash Method](#M_Sha256_HexHash_String) (String)  

### COM/ASP Equivalent

`sha256.StringHexHash  

Public Function StringHexHash(ByVal strData As String) As String`

See [`sha256.StringHexHash`](#x_stringhexhash).

### Remarks

*szDigest* must be at least 64 (`API_MAX_SHA2_CHARS`) characters long (65 in a C program).

### Example

```

    Dim nRet As Long
    Dim strDigest As String
    ' Set strDigest to be 64 chars
    strDigest = String(64, " ")
    nRet = SHA2_StringHexHash(strDigest, "abc")
    Debug.Print strDigest

    nRet = SHA2_StringHexHash(strDigest, _
        "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
    Debug.Print strDigest

```

This should result in output as follows:

```

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1

```

### See Also

[`SHA2_FileHexHash`](#SHA2_FileHexHash)
[`SHA2_BytesHexHash`](#SHA2_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_AddBytes"></a>SHA3_AddBytes
---------------------------------------

Adds an array of bytes to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA3_AddBytes Lib "diCryptoSys.dll" (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = SHA3_AddBytes(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long _stdcall SHA3_AddBytes(long hContext, const unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the SHA-3 context.

*lpData*
:   [in] byte array containing the next part of the message to be hashed.

*nDataLen*
:   [in] number of bytes in the array

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha3.AddData Method](#M_Sha3_AddData_Byte) (Byte[])  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA3_Init`. This function may be called many times before creating
the final message digest with `SHA3_HexDigest`.
`SHA3_AddString` may also be called.

### Example

This example creates the SHA-3-256 hash of the three-character string "abc" using a mixture of calls
to `SHA3_AddBytes` and `SHA3_AddString`.

```

Dim nRet As Long
Dim nBytes As Long
Dim strDigest As String
Dim hContext As Long
Dim abData(1) As Byte

' Set context handle
hContext = SHA3_Init(256)
' Check for an invalid handle
If hContext = 0 Then
  MsgBox "Failed to set context"
  Exit Function
End If

' Set up a test array of bytes
abData(0) = Asc("a")
abData(1) = &H62    ' same as Asc("b")
' Add mixture of bytes and strings to pass "abc"
nRet = SHA3_AddBytes(hContext, abData(0), 2)
nRet = SHA3_AddString(hContext, "c")

' Get required length of output string (NB 2 times number of bytes)
nBytes = SHA3_LengthInBytes(hContext)
strDigest = String(nBytes * 2, " ")
nRet = SHA3_HexDigest(strDigest, Len(strDigest), hContext)
Debug.Print strDigest	

```

This should result in output as follows:

```

3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532

```

### See Also

[`SHA3_Init`](#SHA3_Init)
[`SHA3_AddString`](#SHA3_AddString)
[`SHA3_HexDigest`](#SHA3_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_AddString"></a>SHA3_AddString
-----------------------------------------

Adds a string of ascii characters to the digest.

### VBA/VB6 Syntax

`Public Declare Function SHA3_AddString Lib "diCryptoSys.dll" (ByVal hContext As Long, ByVal strMessage As String) As Long`

`nRet = SHA3_AddString(hContext, strMessage)`

### C/C++ Syntax

`long _stdcall SHA3_AddString(long hContext, const char *szMessage);`

### Parameters

*hContext*
:   [in] handle to the SHA-3 context.

*szMessage*
:   [in] string containing the next part of the message to be hashed.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha3.AddData Method](#M_Sha3_AddData_String) (String)  

### Remarks

The handle to the context *hContext* must have been set up with a
prior call to `SHA3_Init`. This function may be called many times before creating
the final message digest with `SHA3_HexDigest`
This function should only be used to hash strings of "printable" ANSI characters.
To hash a string that contains binary characters, such as ascii zero, use `SHA3_AddBytes`.

### Example

This example computes the SHA-3-224 digest of one million repetitions of the character "a".

```

Dim nRet As Long
Dim nBytes As Long
Dim strDigest As String
Dim hContext As Long
Dim i As Long
Dim sA1000 As String

' Set context handle
hContext = SHA3_Init(224)
If hContext = 0 Then
  MsgBox "Failed to set context"
  Exit Function
End If

' Create a string of 1000 'a's
sA1000 = String(1000, "a")

' Add 1000 times => one million repetitions of "a"
For i = 1 To 1000
  nRet = SHA3_AddString(hContext, sA1000)
Next

' Get required length of output string (NB 2 times number of bytes)
nBytes = SHA3_LengthInBytes(hContext)
strDigest = String(nBytes * 2, " ")
nRet = SHA3_HexDigest(strDigest, Len(strDigest), hContext)
Debug.Print strDigest

```

This should result in output as follows:

```

d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c

```

### See Also

[`SHA3_Init`](#SHA3_Init)
[`SHA3_AddBytes`](#SHA3_AddBytes)
[`SHA3_HexDigest`](#SHA3_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_HexDigest"></a>SHA3_HexDigest
-----------------------------------------

Returns the final message digest value as a hex string.

### VBA/VB6 Syntax

`Public Declare Function SHA3_HexDigest Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal nMaxChars As Long, ByVal hContext As Long) As Long`

`nRet = SHA3_HexDigest(strDigest, nMaxChars, hContext)`

### C/C++ Syntax

`long _stdcall SHA3_HexDigest(char *szOutput, long nMaxChars, long hContext);`

### Parameters

*szOutput*
:   [out] buffer to receive the final message digest in hexadecimal format.

*nMaxChars*
:   [in] maximum number of hex characters to be received.

*hContext*
:   [in] handle to the SHA-3 context.

### Returns (VBA/C)

If successful, the return value is the number of characters in the output string;
otherwise it returns a negative [error code](#errorcodes).

### .NET Equivalent

[Sha3.HexDigest Method](#M_Sha3_HexDigest)  

### Remarks

This operation delivers the result of Add operations since the Init operation.
The handle to the context *hContext* must have been set up with a
prior call to `SHA3_Init`. 

The final digest value will be truncated to the specified length if *nMaxChars* is less than the required digest size.

Note that this digest operation is a destructive, read-once operation.
Once it has been performed, the context must be initialized before being used to calculate another digest value.

### Example

See [`SHA3_AddString`](#SHA3_AddString) and
[`SHA3_AddBytes`](#SHA3_AddBytes)

### See Also

[`SHA3_Init`](#SHA3_Init)
[`SHA3_AddString`](#SHA3_AddString)
[`SHA3_AddBytes`](#SHA3_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_Init"></a>SHA3_Init
-------------------------------

Initialises the SHA-3 context ready for subsequent calls with
`SHA3_AddString`, `SHA3_AddBytes`, and `SHA3_HexDigest`.

### VBA/VB6 Syntax

`Public Declare Function SHA3_Init Lib "diCryptoSys.dll"
    (ByVal nHashBitLen As Long) As Long`

`Dim hContext As Long  

    hContext = SHA3_Init(nHashBitLen)`

### C/C++ Syntax

`long _stdcall SHA3_Init(long nHashBitLen);`

### Parameters

*nHashBitLen*
:   [in] specifying the number of bits in the hash output. 
	This *must* be one of 224, 256, 384 or 512.

### Returns (VBA/C)

Non-zero handle of the SHA-3 context *hContext*.
Returns zero if an error occurs.

### .NET Equivalent

[Sha3.Init Method](#M_Sha3_Init)  

### Remarks

It is important to check for a zero context handle and stop if one occurs. 
An error can occur, for example, if an invalid value for *nHashBitLen* is passed.

### Example

See [`SHA3_HexDigest`](#SHA3_HexDigest)

### See Also

[`SHA3_AddString`](#SHA3_AddString)
[`SHA3_AddBytes`](#SHA3_AddBytes)
[`SHA3_HexDigest`](#SHA3_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_LengthInBytes"></a>SHA3_LengthInBytes
-------------------------------------------------

Returns the number of bytes in the hash output for the algorithm defined in the current SHA-3 context.

### VBA/VB6 Syntax

`Public Declare Function SHA3_LengthInBytes Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nLen = SHA3_LengthInBytes(hContext)`

### C/C++ Syntax

`long _stdcall SHA3_LengthInBytes(long hContext);`

### Parameters

*hContext*

:   [in] handle to the current SHA-3 context.

### Returns (VBA/C)

the number of bytes in the hash output for the algorithm defined in the current SHA-3 context, 
or a negative [error code](#errorcodes).

### .NET Equivalent

[Sha3.LengthInBytes Property](#M_Sha3_LengthInBytesProperty)  

### Remarks

### Example

```

Dim h As Long
Dim nLen As Long
h = SHA3_Init(256)
nLen = SHA3_LengthInBytes(h)
Debug.Print "SHA3_LengthInBytes = " & nLen

```

```

SHA3_LengthInBytes = 32

```

[[Contents](#topofpage)] [[Index](#index)]

<a id="SHA3_Reset"></a>SHA3_Reset
---------------------------------

Resets the context.

### VBA/VB6 Syntax

`Public Declare Function SHA3_Reset Lib "diCryptoSys.dll" (ByVal hContext As Long) As Long`

`nRet = SHA3_Reset(hContext)`

### C/C++ Syntax

`long __stdcall  SHA3_Reset(long hContext);`

### Parameters

*hContext*
:   [in] handle to the SHA-3 context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Sha3.Reset Method](#M_Sha3_Reset)  

### Remarks

Destroys the existing context.
The results of any part-messages added to the context will be lost.

### Example

This trivial example creates a context handle for SHA-3-384, gets the output length in bytes (expecting 48), and then destroys it.

```

Dim nRet As Long
Dim nLen As Long
Dim hContext As Long

hContext = SHA3_Init(384)
Debug.Print "SHA3_Init returns 0x" & Hex(hContext)
Debug.Assert hContext <> 0
nLen = SHA3_LengthInBytes(hContext)
Debug.Print "SHA3_LengthInBytes=" & nLen

' Destroy the context
nRet = SHA3_Reset(hContext)
Debug.Print "SHA3_Reset returns " & nRet

' Now we have an invalid context handle
nLen = SHA3_LengthInBytes(hContext)
Debug.Print "SHA3_LengthInBytes returns " & nLen
Debug.Print apiErrorLookup(nLen)

```

```

SHA3_Init returns 0x3485BE53
SHA3_LengthInBytes=48
SHA3_Reset returns 0
SHA3_LengthInBytes returns -64
Invalid context handle (INVALID_HANDLE_ERROR)

```

### See Also

[`SHA3_Init`](#SHA3_Init)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_B64Mode"></a>TDEA_B64Mode
-------------------------------------

Encrypts or decrypts data
represented as a base64 string
using a specified mode. The key and initialization vector
are represented as base64 strings.

### VBA/VB6 Syntax

`Public Declare Function TDEA_B64Mode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String,
    ByVal strKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strIV As String) As Long`

`nRet = TDEA_B64Mode(strOutput, strInput, strKey, bEncrypt, strMode, strIV)`

### C/C++ Syntax

`long __stdcall  TDEA_B64Mode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in base64.

*szKey*
:   [in] containing the key in base64.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV), if required,
in base64.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

[Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)  

### Remarks

The length of the input string *szInput* must represent a multiple of the block size (8 bytes) when decoded. 
If not, an error will be returned.
The initialization vector
string *szIV* must represent exactly 8 bytes
unless *szMode* is `ECB`, in which case *szIV* is ignored (use `""`).
The key *szKey* must represent exactly 24 bytes, the required key length.
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strIV As String
Dim bEncrypt As Boolean
Dim sCorrect As String

' Key is 0x737C791F25EAD0E04629254352F7DC6291E5CB26917ADA32
strKey = "c3x5HyXq0OBGKSVDUvfcYpHlyyaRetoy"
' IV is 0xB36B6BFB6231084E
strIV = "s2tr+2IxCE4="
' 0x5468697320736F6D652073616D706520636F6E74656E742E0808080808080808
'  "T h i s _ s o m e _ s a m p e _ c o n t e n t ." (padding 8 x 08)
strInput = "VGhpcyBzb21lIHNhbXBlIGNvbnRlbnQuCAgICAgICAg="
sCorrect = "12/RF4+9AvhCMfXB0qL3SkFZSClk9nUkglQiPa+a+OQ="

' Set strOutput to be same length as strInput
strOutput = String(Len(strInput), " ")

Debug.Print "KY=" & strKey
Debug.Print "IV=" & strIV
Debug.Print "PT=" & strInput
nRet = TDEA_B64Mode(strOutput, strInput, strKey, ENCRYPT, "CBC", strIV)
Debug.Print "CT=" & strOutput; nRet
Debug.Print "OK=" & sCorrect

strInput = strOutput
nRet = TDEA_B64Mode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=c3x5HyXq0OBGKSVDUvfcYpHlyyaRetoy
IV=s2tr+2IxCE4=
PT=VGhpcyBzb21lIHNhbXBlIGNvbnRlbnQuCAgICAgICAg=
CT=12/RF4+9AvhCMfXB0qL3SkFZSClk9nUkglQiPa+a+OQ= 0 
OK=12/RF4+9AvhCMfXB0qL3SkFZSClk9nUkglQiPa+a+OQ=
P'=VGhpcyBzb21lIHNhbXBlIGNvbnRlbnQuCAgICAgICAg= 0 

```

### See Also

[`TDEA_HexMode`](#TDEA_HexMode)
[`TDEA_BytesMode`](#TDEA_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_Bytes"></a>TDEA_Bytes
---------------------------------

Encrypts or decrypts an array of Bytes
in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`TDEA_BytesMode`](#TDEA_BytesMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function TDEA_Bytes Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean) As Long`

`nRet = TDEA_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  TDEA_Bytes(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Encrypt Method](#M_Tdea_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Tdea.Decrypt Method](#M_Tdea_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

with *mode*=`Mode.ECB`.

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* must be exactly 24 bytes long.
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

```

    Dim nRet As Long
    Dim strInput As String
    Dim strKey As String
    Dim sCorrect As String
    Dim abKey() As Byte
    Dim lpOutput() As Byte
    Dim abData() As Byte
    Dim nDataLen As Long
    
    ' Define test vectors in hex
    strKey = "0123456789abcdeffedcba987654321089abcdef01234567"
    strInput = "0123456789abcde70123456789abcde7"
    sCorrect = "de0b7c06ae5e0ed5de0b7c06ae5e0ed5"
    
    ' Convert to byte arrays and compute lengths
    abKey = cnvBytesFromHexStr(strKey)
    abData = cnvBytesFromHexStr(strInput)
    nDataLen = Len(strInput) \ 2
    
    ' Dimension array for output
    ReDim lpOutput(nDataLen - 1)
    
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "PT=" & cnvHexStrFromBytes(abData)
    ' Encrypt in one-off process
    nRet = TDEA_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), ENCRYPT)
    Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput), nRet
    Debug.Print "OK=" & sCorrect
    Debug.Assert (sCorrect = cnvHexStrFromBytes(lpOutput))
    
    ' Now decrypt back
    nRet = TDEA_Bytes(abData(0), lpOutput(0), nDataLen, abKey(0), DECRYPT)
    Debug.Print "P'=" & cnvHexStrFromBytes(abData), nRet
    Debug.Assert (strInput = cnvHexStrFromBytes(abData))

```

This should result in output as follows:

```

KY=0123456789ABCDEFFEDCBA987654321089ABCDEF01234567
PT=0123456789ABCDE70123456789ABCDE7
CT=DE0B7C06AE5E0ED5DE0B7C06AE5E0ED5        0 
OK=de0b7c06ae5e0ed5de0b7c06ae5e0ed5
P'=0123456789ABCDE70123456789ABCDE7        0 

```

### See Also

[`TDEA_BytesMode`](#TDEA_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_BytesMode"></a>TDEA_BytesMode
-----------------------------------------

Encrypts or decrypts an array of Bytes
in one step
using a specified mode.

### VBA/VB6 Syntax

`Public Declare Function TDEA_BytesMode Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = TDEA_BytesMode(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  TDEA_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpOutput*
:   [out] array of sufficient length to receive the output.

*lpInput*
:   [in] array containing the input data.

*nBytes*
:   [in] equal to length of the input data in bytes.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the
initialization vector (IV), or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Encrypt Method](#M_Tdea_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

[Tdea.Decrypt Method](#M_Tdea_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])  

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
The key *lpKey* must be exactly 24 bytes long and the IV, if required, exactly 8 bytes long.
The output array *lpOutput* must be at least *nDataLen* bytes long.
*lpOutput* and *lpData* may be the same.

### Example

```

Dim nRet As Long
Dim strOutput As String
Dim strInput As String
Dim strKey As String
Dim strHexIV As String
Dim sCorrect As String
Dim nDataLen As Long
Dim abKey() As Byte
Dim lpOutput() As Byte
Dim abData() As Byte
Dim abInitV() As Byte

strKey = "0123456789abcdeffedcba987654321089abcdef01234567"
strHexIV = "1234567890abcdef"
strInput = "Now is the time for all "
sCorrect = "204011f986e35647199e47af391620c5bb9a5bcfc86db0bb"

' Convert to byte arrays and compute lengths
abKey = cnvBytesFromHexStr(strKey)
abInitV = cnvBytesFromHexStr(strHexIV)
abData = StrConv(strInput, vbFromUnicode)
nDataLen = Len(strInput)

' Dimension array for output
ReDim lpOutput(nDataLen - 1)

Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
Debug.Print "PT=" & cnvHexStrFromBytes(abData)

' Encrypt in one-off process
nRet = TDEA_BytesMode(lpOutput(0), abData(0), nDataLen, _
    abKey(0), True, "CBC", abInitV(0))
Debug.Print "CT=" & cnvHexStrFromBytes(lpOutput)
Debug.Print "OK=" & sCorrect
Debug.Assert (sCorrect = cnvHexStrFromBytes(lpOutput))

' Now decrypt back
nRet = TDEA_BytesMode(abData(0), lpOutput(0), nDataLen, _
    abKey(0), DECRYPT, "CBC", abInitV(0))
strOutput = StrConv(abData(), vbUnicode)
Debug.Print "P'=" & "[" & strOutput & "]"
Debug.Assert (strOutput = strInput)

```

This should result in output as follows:

```

KY=0123456789ABCDEFFEDCBA987654321089ABCDEF01234567
IV=1234567890ABCDEF
PT=4E6F77206973207468652074696D6520666F7220616C6C20
CT=204011F986E35647199E47AF391620C5BB9A5BCFC86DB0BB 
OK=204011f986e35647199e47af391620c5bb9a5bcfc86db0bb
P'=[Now is the time for all ]

```

### See Also

[`TDEA_Bytes`](#TDEA_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_File"></a>TDEA_File
-------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as arrays of bytes.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function TDEA_File Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte) As Long`

`nRet = TDEA_File(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0))`

### C/C++ Syntax

`long __stdcall  TDEA_File(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

[Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])  

### Remarks

The key *lpKey* must be exactly 24 bytes long.
The initialization vector
byte array *lpInitV* must be exactly the block size of 8 bytes long,
except for ECB mode, where it is ignored (use `0`).

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

### Example

```

    Const MY_PATH As String = "C:\Test\"
    Dim abKey() As Byte
    Dim strFileOut As String
    Dim strFileIn As String
    Dim strFileChk As String
    Dim nRet As Long

    ' Construct full path names to files
    strFileIn = MY_PATH & "hello.txt"
    strFileOut = MY_PATH & "hello.tdea.enc.dat"
    strFileChk = MY_PATH & "hello.tdea.chk.txt"

    ' Create the key as an array of bytes
    ' This creates an array of 24 bytes {&HFE, &HDC, ... &H10}
    abKey = cnvBytesFromHexStr("fedcba9876543210fedcba9876543210fedcba9876543210")

    ' Encrypt plaintext file to ciphertext
    ' Output file = 16-byte ciphertext file hello.enc
    nRet = TDEA_File(strFileOut, strFileIn, abKey(0), ENCRYPT, "ECB", 0)
    Debug.Print nRet

    ' Now decrypt it
    nRet = TDEA_File(strFileChk, strFileOut, abKey(0), DECRYPT, "ECB", 0)
    Debug.Print nRet

```

### See Also

[`TDEA_FileExt`](#TDEA_FileExt)
[`TDEA_FileHex`](#TDEA_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_FileExt"></a>TDEA_FileExt
-------------------------------------

Encrypts or decrypts a file
using a specified mode with extended options.

@deprecated use
[CIPHER_FileEncrypt()](#CIPHER_FileEncrypt) and
[CIPHER_FileDecrypt()](#CIPHER_FileDecrypt)
instead. 

### VBA/VB6 Syntax

`Public Declare Function TDEA_FileExt Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByRef lpKey As Byte, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByRef lpInitV As Byte, ByVal nOptions As Long) As Long`

`nRet = TDEA_FileExt(strFileOut, strFileIn, abKey(0), bEncrypt, strMode, abInitV(0), nOptions)`

### C/C++ Syntax

`long __stdcall  TDEA_FileExt(const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV, long nOptions);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*lpKey*
:   [in] array containing the key.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] array containing the initialization vector (IV),
or zero (0) for ECB mode.

*nOptions*
:   [in] option flags:  

Zero (0) for default behaviour as per [`TDEA_File`](#TDEA_File).  

`API_IV_PREFIX` to prepend the IV before the ciphertext in the output file (ignored for ECB mode)  

`API_PAD_LEAVE` to leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting)

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

[Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)  

### Remarks

For the default behaviour, see [`TDEA_File`](#TDEA_File). 
The options are ignored if not applicable.
For more information on the behaviour of the options, see
[Extensions to block cipher functions for files](#extensionsforfiles).

### Example

```

Dim abKey() As Byte
Dim abIV() As Byte
Dim strFilePlain As String
Dim strFileCipher As String
Dim strFileCheck As String
Dim strFileChk1 As String
Dim nRet As Long

' Input file is exactly 19 bytes long
strFilePlain = "nowis19.txt"
strFileCipher = "nowis19.tdea.enc.dat"
strFileCheck = "nowis19.tdea.chk.txt"
strFileChk1 = "nowis19.tdea.chk1.txt"

' Create the key and IV as arrays of bytes
' This creates an array of 24 bytes {&H01, &H23, ... &H67}
abKey = cnvBytesFromHexStr("0123456789ABCDEFFEDCBA987654321089ABCDEF01234567")
' This creates an array of 8 bytes {&H12, &H34, ... &HEF}
abIV = cnvBytesFromHexStr("1234567890ABCDEF ")

' Encrypt plaintext file to ciphertext with embedded IV at beginning
' Output file = 32-byte ciphertext file .enc.dat
nRet = TDEA_FileExt(strFileCipher, strFilePlain, abKey(0), ENCRYPT, "CBC", abIV(0), API_IV_PREFIX)
Debug.Print "TDEA_FileExt(ENCRYPT) returns " & nRet
Debug.Print "Output file '" & strFileCipher & "' is " & FileLen(strFileCipher) & " bytes"

' Now decrypt it back to original plaintext - this file should be 19 bytes long
nRet = TDEA_FileExt(strFileCheck, strFileCipher, abKey(0), DECRYPT, "CBC", abIV(0), API_IV_PREFIX)
Debug.Print "TDEA_FileExt(DECRYPT) returns " & nRet
Debug.Print "Output file '" & strFileCheck & "' is " & FileLen(strFileCheck) & " bytes"

' Alternatively, decrypt and leave padding bytes in place - this file should be 24 bytes long
nRet = TDEA_FileExt(strFileChk1, strFileCipher, abKey(0), DECRYPT, "CBC", abIV(0), API_IV_PREFIX + API_PAD_LEAVE)
Debug.Print "TDEA_FileExt(DECRYPT, API_PAD_LEAVE) returns " & nRet
Debug.Print "Output file '" & strFileChk1 & "' is " & FileLen(strFileChk1) & " bytes"

```

This should give the following output 

```

TDEA_FileExt(ENCRYPT) returns 0
Output file 'nowis19.tdea.enc.dat' is 32 bytes
TDEA_FileExt(DECRYPT) returns 0
Output file 'nowis19.tdea.chk.txt' is 19 bytes
TDEA_FileExt(DECRYPT, API_PAD_LEAVE) returns 0
Output file 'nowis19.tdea.chk1.txt' is 24 bytes

```

### See Also

[`TDEA_File`](#TDEA_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_FileHex"></a>TDEA_FileHex
-------------------------------------

Encrypts or decrypts a file
using a specified mode. The key and initialization vector
are passed as hexadecimal strings.

### VBA/VB6 Syntax

`Public Declare Function TDEA_FileHex Lib "diCryptoSys.dll"
    (ByVal strFileOut As String, ByVal strFileIn As String,
    ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = TDEA_FileHex(strFileOut, strFileIn, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  TDEA_FileHex(const char *szFileOut, const char *szFileIn, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szFileOut*
:   [in] with the full path name of the output
file to be created.

*szFileIn*
:   [in] with the full path name of the input file
to be processed.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)  

[Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)  

### Remarks

The key string *szHexKey* must be exactly 48 hex characters long (i.e. representing exactly 24 bytes/192 bits).
The initialization vector *szHexIV*
must be exactly 16 hex characters long
(i.e. representing exactly the block size of 8 bytes), except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].

The output file *szFileOut* will be overwritten without warning.
If there is an error [*new in version 3.3*], the output file will **not exist**.
The input and output filepaths must **not** be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of
[[CMS](#CMS)], 
which is the same as the padding method in [[PKCS7](#PKCS7)] and [[PKCS5](#PKCS5)].

Note that even though the parameters are in hexadecimal-encoded form, the encrypted file is still binary.

### Example

This example will encrypt the file "bigfile.dat" in CBC mode using the key
`0xfedcba9876543210fedcba9876543210fedcba9876543210` and initialization vector
`0x0123456789abcdef`. The output file "bigfile.cbc" will be created or
overwritten. It then decrypts the ciphertext file as a check, creating or
overwriting the file "bigfile.chk".

```

    Dim nRet As Long

    nRet = TDEA_FileHex("bigfile.cbc", "bigfile.dat", _
        "fedcba9876543210fedcba9876543210fedcba9876543210", _
        ENCRYPT, "CBC", "0123456789abcdef")
    Debug.Print nRet

    ' and decrypt it as a check
    nRet = TDEA_FileHex("bigfile.chk", "bigfile.cbc", _
        "fedcba9876543210fedcba9876543210fedcba9876543210", _
        DECRYPT, "CBC", "0123456789abcdef")
    Debug.Print nRet

```

### See Also

[`TDEA_File`](#TDEA_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_Final"></a>TDEA_Final
---------------------------------

Closes and clears the TDEA context.

### VBA/VB6 Syntax

`Public Declare Function TDEA_Final Lib "diCryptoSys.dll"
    (ByVal hContext As Long) As Long`

`nRet = TDEA_Final(hContext)`

### C/C++ Syntax

`long __stdcall  TDEA_Final(long hContext);`

### Parameters

*hContext*
:   [in] containing the handle to the TDEA context.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Dispose Method](#M_Tdea_Dispose)  

### Remarks

### Example

See [`TDEA_UpdateHex`](#TDEA_UpdateHex).

### See Also

[`TDEA_Init`](#TDEA_Init)
[`TDEA_InitHex`](#TDEA_InitHex)
[`TDEA_UpdateHex`](#TDEA_UpdateHex)
[`TDEA_Update`](#TDEA_Update)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_Hex"></a>TDEA_Hex
-----------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a key represented in hexadecimal notation.
The process is carried out in one step in Electronic Codebook (EBC) mode.

@deprecated use
[`TDEA_HexMode`](#TDEA_HexMode) 
with *strMode*=`"ECB"`.

### VBA/VB6 Syntax

`Public Declare Function TDEA_Hex Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, ByVal strKey As String,
    ByVal bEncrypt As Boolean) As Long`

`nRet = TDEA_Hex(strOutput, strInput, strKey, bEncrypt)`

### C/C++ Syntax

`long __stdcall  TDEA_Hex(char *szOutput, const char *szInput, const char *szKey, int fEncrypt);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeString) (String, String, Mode, String)  

with *mode*=`Mode.ECB`.

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
The key string *szKey* must be exactly 48 hex characters long
(i.e. representing exactly 24 bytes). The parity bit is ignored.
The output string *szOutput* must be set up with at least the same number of characters as the input
string before calling.
The variables *szOutput* and *szInput* should be different.
Valid hexadecimal characters are [0-9A-Fa-f].

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim bEncrypt As Boolean
    Dim sCorrect As String

    strInput = "8000000000000000"
    strKey = "010101010101010101010101010101010101010101010101"
    sCorrect = "95F8A5E5DD31D900"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "PT=" & strInput
    ' Encrypt
    nRet = TDEA_Hex(strOutput, strInput, strKey, ENCRYPT)
    Debug.Print "CT=" & strOutput, "Return value=" & nRet
    Debug.Print "OK=" & sCorrect

    ' Decrypt back
    strInput = strOutput
    nRet = TDEA_Hex(strOutput, strInput, strKey, DECRYPT)
    Debug.Print "P'=" & strOutput & "Return value=" & nRet

```

This should result in output as follows:

```

KY=010101010101010101010101010101010101010101010101
PT=8000000000000000
CT=95F8A5E5DD31D900         Return value= 0
OK=95F8A5E5DD31D900
P'=8000000000000000         Return value= 0

```

### See Also

[`TDEA_HexMode`](#TDEA_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_HexMode"></a>TDEA_HexMode
-------------------------------------

Encrypts or decrypts data
represented as a hexadecimal string
using a specified mode. The key and initialization vector
are represented as a hexadecimal string.

### VBA/VB6 Syntax

`Public Declare Function TDEA_HexMode Lib "diCryptoSys.dll"
    (ByVal strOutput As String, ByVal strInput As String, 
    ByVal strHexKey As String, ByVal bEncrypt As Boolean, 
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`nRet = TDEA_HexMode(strOutput, strInput, strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  TDEA_HexMode(char *szOutput, const char *szInput, const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szOutput*
:   [out] of sufficient length to receive the output.

*szInput*
:   [in] containing the input data in hexadecimal.

*szKey*
:   [in] containing the key in hexadecimal.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector (IV)
in hexadecimal.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeString) (String, String, Mode, String)  

[Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeString) (String, String, Mode, String)  

### COM/ASP Equivalent

`tdea.HexMode  

Public Function HexMode(ByVal strInput As String, ByVal strHexKey As String, ByVal bEncrypt As Boolean, ByVal strMode As String, ByVal strHexIV As String) As String`

See [`tdea.HexMode`](#x_hexmode).

### Remarks

The length of the input string *szInput* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
The key string *szHexKey*
must be exactly 48 hex characters long (i.e. representing exactly 24 bytes).
The initialization vector
string *szIV* must be exactly 16 hex characters long
(i.e. representing exactly 8 bytes) unless *szMode* is `ECB`, 
in which case *szIV* is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
The output string *szOutput* must be set up with at least the same
number of characters as the input string before calling.
The variables *szOutput* and *szInput* should be different.

### Example

```

    Dim nRet As Long
    Dim strOutput As String
    Dim strInput As String
    Dim strKey As String
    Dim strIV As String
    Dim bEncrypt As Boolean
    Dim sCorrect As String

    strInput = "5468697320736F6D652073616D706520636F6E74656E742E0808080808080808"
    strKey = "737C791F25EAD0E04629254352F7DC6291E5CB26917ADA32"
    strIV = "B36B6BFB6231084E"
    sCorrect = "d76fd1178fbd02f84231f5c1d2a2f74a4159482964f675248254223daf9af8e4"
    ' Set strOutput to be same length as strInput
    strOutput = String(Len(strInput), " ")

    Debug.Print "KY=" & strKey
    Debug.Print "PT=" & strInput
    nRet = TDEA_HexMode(strOutput, strInput, strKey, True, "CBC", strIV)
    Debug.Print "CT=" & strOutput; nRet
    Debug.Print "OK=" & sCorrect

    strInput = strOutput
    nRet = TDEA_HexMode(strOutput, strInput, strKey, DECRYPT, "CBC", strIV)
    Debug.Print "P'=" & strOutput; nRet

```

This should result in output as follows:

```

KY=737C791F25EAD0E04629254352F7DC6291E5CB26917ADA32
PT=5468697320736F6D652073616D706520636F6E74656E742E0808080808080808
CT=D76FD1178FBD02F84231F5C1D2A2F74A4159482964F675248254223DAF9AF8E4 0
OK=d76fd1178fbd02f84231f5c1d2a2f74a4159482964f675248254223daf9af8e4
P'=5468697320736F6D652073616D706520636F6E74656E742E0808080808080808 0

```

### See Also

[`TDEA_Hex`](#TDEA_Hex)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_Init"></a>TDEA_Init
-------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the TDEA function.
The key and IV data are provided in byte arrays.

### VBA/VB6 Syntax

`Public Declare Function TDEA_Init Lib "diCryptoSys.dll" (ByRef lpKey As Byte, ByVal fEncrypt As Integer, ByVal strMode As String, ByRef lpIV As Byte) As Long`

`hContext = TDEA_Init(lpKey(0), bEncrypt, strMode, lpIV(0))`

### C/C++ Syntax

`long __stdcall  TDEA_Init(const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);`

### Parameters

*lpKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*lpIV*
:   [in] containing the initialization vector
 in hexadecimal. Set as zero (0) for ECB mode.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`TDEA_Update`, `TDEA_UpdateHex` or `TDEA_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Tdea.InitEncrypt Method](#M_Tdea_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])  

[Tdea.InitDecrypt Method](#M_Tdea_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])  

### Remarks

The key *lpKey* must be exactly 24 bytes long and the IV, if required, exactly 8 bytes long.
Unlike most other functions in this API, `TDEA_Init` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling a TDEA function.

### Example

See [`TDEA_Update`](#TDEA_Update).

### See Also

[`TDEA_InitHex`](#TDEA_InitHex)
[`TDEA_UpdateHex`](#TDEA_UpdateHex)
[`TDEA_Update`](#TDEA_Update)
[`TDEA_Final`](#TDEA_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_InitError"></a>TDEA_InitError
-----------------------------------------

Returns the error code after an unsuccessful call to
`TDEA_Init` or `TDEA_InitHex`.

### VBA/VB6 Syntax

`Public Declare Function TDEA_InitError Lib "diCryptoSys.dll"
    () As Long`

`nRet = TDEA_InitError()`

### C/C++ Syntax

`long __stdcall  TDEA_InitError(void);`

### Parameters

None

### Returns (VBA/C)

Returns the [error code](#errorcodes) from the last call to
`TDEA_Init` or `TDEA_InitHex`.

### .NET Equivalent

[Tdea.ErrCode Property](#M_Tdea_ErrCodeProperty)  

### Remarks

### Example

[`API_ErrorLookup`](#API_ErrorLookup)

### See Also

<a id="TDEA_InitHex"></a>TDEA_InitHex
-------------------------------------

Initialises the context with the key, direction and mode
ready for repeated
operations of the TDEA function.
The key and IV data are provided in hexadecimal format.

### VBA/VB6 Syntax

`Public Declare Function TDEA_InitHex Lib "diCryptoSys.dll"
    (ByVal strHexKey As String, ByVal bEncrypt As Boolean,
    ByVal strMode As String, ByVal strHexIV As String) As Long`

`hContext = TDEA_InitHex(strHexKey, bEncrypt, strMode, strHexIV)`

### C/C++ Syntax

`long __stdcall  TDEA_InitHex(const char *szKey, int fEncrypt, const char *szMode, const char *szIV);`

### Parameters

*szKey*
:   [in] containing the key in hexadecimal
representation.

*fEncrypt*
:   [in] direction flag:
set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

*szMode*
:   [in] specifying the confidentiality mode:  

`"ECB"` for Electronic Codebook mode,  

`"CBC"` for Cipher Block Chaining mode,  

`"CFB"` for 64-bit Cipher Feedback mode,  

`"OFB"` for Output Feedback mode, or  

`"CTR"` for Counter mode.

*szIV*
:   [in] containing the initialization vector
 in hexadecimal.

### Returns (VBA/C)

Non-zero handle of the context *hContext*
to be used in subsequent calls to the functions 
`TDEA_Update`, `TDEA_UpdateHex` or `TDEA_Final`. 
Returns zero if an error occurs.

### .NET Equivalent

[Tdea.InitEncrypt Method](#M_Tdea_InitEncrypt_StringModeString) (String, Mode, String)  

[Tdea.InitDecrypt Method](#M_Tdea_InitDecrypt_StringModeString) (String, Mode, String)  

### Remarks

The key string *szHexKey*
must be exactly 48 hex characters long (i.e. representing exactly 24 bytes/192 bits).
The initialization vector *szHexIV*
must be exactly 16 hex characters long (i.e. representing exactly the block size of 8 bytes), 
except for ECB mode, where it is ignored (use `""`).
Valid hexadecimal characters are [0-9A-Fa-f].
Unlike most other functions in this API, `TDEA_InitHex` returns zero if an error occurs.
It is important to check that the value of *hContext* returned is
**not** equal to zero before calling a TDEA function.

### Example

See [`TDEA_UpdateHex`](#TDEA_UpdateHex).

### See Also

[`TDEA_Init`](#TDEA_Init)
[`TDEA_UpdateHex`](#TDEA_UpdateHex)
[`TDEA_Update`](#TDEA_Update)
[`TDEA_Final`](#TDEA_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_Update"></a>TDEA_Update
-----------------------------------

Carries out the TDEA transformation function on a byte array
according to the direction
and mode set up by an earlier call to `TDEA_Init()` or `TDEA_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function TDEA_Update Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByRef lpData As Byte, ByVal nDataLen As Long) As Long`

`nRet = TDEA_Update(hContext, abData(0), nDataLen)`

### C/C++ Syntax

`long __stdcall  TDEA_Update(long hContext, unsigned char *lpData, long nDataLen);`

### Parameters

*hContext*
:   [in] handle to the TDEA context set up by an earlier call to
	`TDEA_Init()` or `TDEA_InitHex()`.

*lpData*
:   [in,out] array containing the input data.

*nDataLen*
:   [in] equal to length of the input data in bytes.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Update Method](#M_Tdea_Update_Byte) (Byte[])  

### Remarks

The input data *lpData* must be an exact multiple of 8 bytes long.
If not, an error code will be returned.
Note that the output overwrites the input.

### Example

This example carries out one of the Monte Carlo tests from NIST 800-20
[[SP80020](#SP80020)].

```

    Dim nRet As Long
    Dim hContext As Long
    Dim sCorrect As String
    Dim j As Integer
    Dim abKey() As Byte
    Dim abInitV() As Byte
    Dim aBlock() As Byte
    Dim aNext() As Byte
    Dim aLast() As Byte

    aBlock() = StrConv("Now is t", vbFromUnicode)
    abKey = cnvBytesFromHexStr( _
        "0123456789abcdef23456789abcdef01456789abcdef0123")
    abInitV = cnvBytesFromHexStr("1234567890abcdef")
    sCorrect = "cb191f85d1ed8439"

    Debug.Print "TDEA Monte Carlo TCBC Mode Encrypt:"
    Debug.Print "KY=" & cnvHexStrFromBytes(abKey)
    Debug.Print "IV=" & cnvHexStrFromBytes(abInitV)
    Debug.Print "PT=" & cnvHexStrFromBytes(aBlock)

    hContext = TDEA_Init(abKey(0), True, "CBC", abInitV(0))
    If hContext = 0 Then
        nRet = TDEA_InitError()
        Debug.Print "TDEA_Init Failed: " & apiErrorLookup(nRet)
        Exit Function
    End If
    ' Do 10,000 times
    aNext() = aBlock()
    For j = 0 To 9999
        aBlock() = aNext()
        nRet = TDEA_Update(hContext, aBlock(0), 8)
        If j = 0 Then
            aNext() = abInitV()
        Else
            aNext() = aLast()
        End If
        aLast() = aBlock()
    Next
    Debug.Print "CT=" & cnvHexStrFromBytes(aBlock)
    Debug.Print "OK=" & sCorrect
    nRet = TDEA_Final(hContext)
    
    Debug.Assert (sCorrect = cnvHexStrFromBytes(aBlock))

```

This should result in output as follows:

```

TDEA Monte Carlo TCBC Mode Encrypt:
KY=0123456789ABCDEF23456789ABCDEF01456789ABCDEF0123
IV=1234567890ABCDEF
PT=4E6F772069732074
CT=CB191F85D1ED8439
OK=cb191f85d1ed8439

```

### See Also

[`TDEA_Init`](#TDEA_Init)
[`TDEA_InitHex`](#TDEA_InitHex)
[`TDEA_UpdateHex`](#TDEA_UpdateHex)
[`TDEA_Final`](#TDEA_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="TDEA_UpdateHex"></a>TDEA_UpdateHex
-----------------------------------------

Carries out the TDEA transformation function on a hexadecimal string
according to the direction
and mode set up by an earlier call to `TDEA_Init()` or `TDEA_InitHex()`.

### VBA/VB6 Syntax

`Public Declare Function TDEA_UpdateHex Lib "diCryptoSys.dll"
    (ByVal hContext As Long, ByVal strHexString As String) As Long`

`nRet = TDEA_UpdateHex(hContext, strHexString)`

### C/C++ Syntax

`long __stdcall  TDEA_UpdateHex(long hContext, char *szHexData);`

### Parameters

*hContext*
:   [in] handle to the TDEA context set up by an earlier call to
	`TDEA_Init()` or `TDEA_InitHex()`.

*szHexData*
:   [in,out] containing input in hexadecimal format
to be processed by the TDEA function and to receive the output.

### Returns (VBA/C)

If successful, the return value is 0;
otherwise it returns a non-zero [error code](#errorcodes).

### .NET Equivalent

[Tdea.Update Method](#M_Tdea_Update_String) (String)  

### Remarks

*szHexString* must be a multiple of 16 hex characters long
(i.e. representing a multiple of 8 bytes). If not, an error code will be returned.
Valid hexadecimal characters are [0-9A-Fa-f]. Note that the output overwrites the input.
*szHexString* must be a variable that can receive the output, not a constant.

### Example

```

    Dim nRet As Long
    Dim hContext As Long
    Dim sBlock As String
    Dim strKey As String
    Dim strIV As String
    Dim sNext As String
    Dim sLast As String
    Dim sCorrect As String
    Dim j As Integer

    sBlock = "4e6f772069732074"
    strKey = "0123456789abcdef" & _
            "23456789abcdef01" & _
            "456789abcdef0123"
    strIV = "1234567890abcdef"
    sCorrect = "cb191f85d1ed8439"

    Debug.Print "TDEA Monte Carlo TCBC Mode Encrypt:"
    Debug.Print "KY=" & strKey
    Debug.Print "IV=" & strIV
    Debug.Print "PT=" & sBlock

    hContext = TDEA_InitHex(strKey, True, "CBC", strIV)
    If hContext = 0 Then
        Exit Function
    End If
    ' Do 10,000 times
    sNext = sBlock
    For j = 0 To 9999
        sBlock = sNext
        nRet = TDEA_UpdateHex(hContext, sBlock)
        If j = 0 Then
            sNext = strIV
        Else
            sNext = sLast
        End If
        sLast = sBlock
    Next
    Debug.Print "CT=" & sBlock
    Debug.Print "OK=" & sCorrect
    nRet = TDEA_Final(hContext)

```

This should result in output as follows:

```

TDEA Monte Carlo TCBC Mode Encrypt:
KY=0123456789abcdef23456789abcdef01456789abcdef0123
IV=1234567890abcdef
PT=4e6f772069732074
CT=CB191F85D1ED8439
OK=cb191f85d1ed8439
```

### See Also

[`TDEA_Init`](#TDEA_Init)
[`TDEA_InitHex`](#TDEA_InitHex)
[`TDEA_Update`](#TDEA_Update)
[`TDEA_Final`](#TDEA_Final)

[[Contents](#topofpage)] [[Index](#index)]

<a id="WIPE_Data"></a>WIPE_Data
-------------------------------

Zeroises data in memory.

### VBA/VB6 Syntax

`Public Declare Function WIPE_Data Lib "diCryptoSys.dll" 
    (ByRef lpData As Byte, ByVal nBytes As Long) As Long`

Alternative aliases for Visual Basic users to deal with Byte and String types explicitly:  

`Public Declare Function WIPE_Bytes Lib "diCryptoSys.dll" Alias "WIPE_Data" 
    (ByRef lpData As Byte, ByVal nBytes As Long) As Long  

Public Declare Function WIPE_String Lib "diCryptoSys.dll" Alias "WIPE_Data" 
    (ByVal strData As String, ByVal nStrLen As Long) As Long`

`nRet = WIPE_Data(abData(0), nBytes)
' Note the "(0)" after the byte array parameter`

Visual Basic only:-  

`nRet = WIPE_Bytes(abData(0), nBytes)  

nRet = WIPE_String(strData, nStrLen)`

### C/C++ Syntax

`long __stdcall  WIPE_Data(void *lpData, long nDataLen);`

### Parameters

*lpData*
:   [in,out] `Byte` array to be cleared.

*nDataLen*
:   [in] specifying the number of bytes to be cleared.

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns an  [error code](#errorcodes).

### .NET Equivalent

[Wipe.Data Method](#M_Wipe_Data)  

[Wipe.String Method](#M_Wipe_String)  

### C++ (STL) Equivalent

`static bool [crsysapi::Wipe::Data](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#aa081cd1e059d775c1d5a67e956f766e6 "External link") (bvec_t &data)  

static bool [crsysapi::Wipe::String](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#abbc9b94c430c6039c3186cb4af472030 "External link") (std::string &s)`

### Python Equivalent

`static [Wipe.data](https://cryptosys.net/pydocapi/class-stubs/Wipe.html#crsysapi.Wipe.data "External link")(data)`

### Remarks

This function does not free any memory; it just zeroises it.

### Examples

```

Dim abData(3) As Byte
Dim nLen As Long
Dim nRet As Long
' Set up data in byte array
abData(0) = &HDE
abData(1) = &HAD
abData(2) = &HBE
abData(3) = &HEF
Debug.Print "Before WIPE_Data: " & "[" & cnvHexStrFromBytes(abData) & "]"
nLen = UBound(abData) - LBound(abData) + 1
nRet = WIPE_Data(abData(0), nLen)
Debug.Print "After WIPE_Data:  " & "[" & cnvHexStrFromBytes(abData) & "]"

```

or use alias in VB

```

nRet = WIPE_Bytes(abData(0), n)

```

```

Dim strData As String
Dim nRet As Long
strData = "my deepest secrets"
Debug.Print "Before WIPE_String: " & "[" & strData & "]"
nRet = WIPE_String(strData, Len(strData))
' Set to empty as well...
strData = ""
Debug.Print "After WIPE_String:  " & "[" & strData & "]"

```

In C:

```

char passwd[256];

printf("Enter password: ");
/* Accept password from user
 * ... 
 * ... then do something with it 
 * ... 
 * Wipe it */
WIPE_Data(passwd, strlen(passwd));

```

### See Also

[`WIPE_File`](#WIPE_File)

[[Contents](#topofpage)] [[Index](#index)]

<a id="WIPE_File"></a>WIPE_File
-------------------------------

Securely wipes and deletes a file using 7-pass DOD standards.

### VBA/VB6 Syntax

`Public Declare Function WIPE_File Lib "diCryptoSys.dll" 
    (ByVal strFileName As String, ByVal nOptions As Long) As Long`

`nRet = WIPE_File(strFileName, nOptions)`

### C/C++ Syntax

`long __stdcall  WIPE_File(const char *szFileName, long nOptions);`

### Parameters

*szFileName*
:   [in] specifying the file to be deleted.

*nOptions*
:   [in] Option flags. Select one of:  

`API_WIPEFILE_DOD7` (0) to use DOD 7-pass (default)  

`API_WIPEFILE_SIMPLE` to overwrite with single pass of zero bytes (quicker but less secure)  [*New in v5.3*].

### Returns (VBA/C)

If successful, the return value is zero;
otherwise it returns a nonzero [error code](#errorcodes).

### .NET Equivalent

[Wipe.File Method](#M_Wipe_File)  

### C++ (STL) Equivalent

`static bool [crsysapi::Wipe::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#a60c4d6caf053d66866704b0989d20eb5 "External link") (const std::string &fileName, Opts opts=Opts::Default)`

### Python Equivalent

`static [Wipe.file](https://cryptosys.net/pydocapi/class-stubs/Wipe.html#crsysapi.Wipe.file "External link")(filename, opts=Options.DEFAULT)`

### Remarks

Wipes a file using the 7-pass DOD Standard according to [[`NISPOM`](#NISPOM)] before deleting.

### Example

```

nRet = WIPE_File("ToDelete.txt", 0)

```

### See Also

[`WIPE_Data`](#WIPE_Data)

[[Contents](#topofpage)] [[Index](#index)]

<a id="XOF_Bytes"></a>XOF_Bytes
-------------------------------

Generate bytes using an eXtendable Output Function (XOF).

### VBA/VB6 Syntax

`Public Declare Function XOF_Bytes Lib "diCryptoSys.dll" (ByRef lpOutput As Byte, ByVal nOutBytes As Long, ByRef lpMessage As Byte, ByVal nMsgLen As Long, ByVal nOptions As Long) As Long`

`nRet = XOF_Bytes(lpOutput(0), nOutBytes, abMessage(0), nMsgLen, nOptions)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall XOF_Bytes(unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, long nOptions);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive the output.

*nOutBytes*
:   [in] size of output buffer in bytes.

*lpMessage*
:   [in] byte array containing the input data.

*nMsgLen*
:   [in] length of the input data in bytes.

*nOptions*
:   [in] Option flags. Select one of:  

`API_XOF_SHAKE128` to use SHAKE128  

`API_XOF_SHAKE256` to use SHAKE256  

`API_XOF_MGF1_SHA1` to use MGF1-SHA-1  

`API_XOF_MGF1_SHA256` to use MGF1-SHA-256  

`API_XOF_MGF1_SHA512` to use MGF1-SHA-512  

`API_XOF_ASCON_XOF` to use ASCON-XOF  

`API_XOF_ASCON_XOFA` to use ASCON-XOFA

### Returns (VBA/C)

If successful, the return value is the number of bytes in the output;
otherwise it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [xofBytes](#VB_xofBytes)(nBytes As Long, lpMessage() As Byte, nOptions As Long) As Byte()`

### .NET Equivalent

[Xof.Bytes Method](#M_Xof_Bytes)  

### C++ (STL) Equivalent

`static bvec_t [crsysapi::Xof::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_xof.html#a885aa3379908793503497c119b04107c "External link") (int numBytes, const bvec_t &message, XofAlg xofalg)`

### Python Equivalent

`static [Xof.bytes](https://cryptosys.net/pydocapi/class-stubs/Xof.html#crsysapi.Xof.bytes "External link")(numbytes, msg, xofalg)`

### Remarks

The output buffer *lpOutput* must exist. It will be filled with exactly *nOutBytes* bytes.
Note there is no zero option for *nOptions*: a valid option flag must be specified.

SHAKE128 and SHAKE256 are described in the SHA-3 Standard [[FIPS202](#FIPS202)]. 
MGF1, despite its name as a *Mask Generation Function* (MGF), is also an eXtendable Output Function (XOF) using the SHA1/SHA-2 hash functions, 
and is described in [[PKCS1](#PKCS1)]. 
The extendable output functions
Ascon-Xof and Ascon-Xofa
are from the cipher suite [ASCON](#ciphersuiteascon) and are provisional subject to final approval by NIST.

### Example (VBA core function)

```

Dim strMsgHex As String
Dim nOutBits As Long
Dim nOutBytes As Long
Dim abOut() As Byte
Dim abMsg() As Byte
Dim nMsgLen As Long
Dim strOK As String
Dim nRet As Long
 
' Ref: "SHA-3 XOF Test Vectors for Byte-Oriented Output"
' File `SHAKE256VariableOut.rsp` COUNT = 1244
' <https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/shakebytetestvectors.zip>

' Input in hex form
strMsgHex = "6ae23f058f0f2264a18cd609acc26dd4dbc00f5c3ee9e13ecaea2bb5a2f0bb6b"
nOutBits = 2000
strOK = "b9b92544fb25cfe4ec6fe437d8da2bbe00f7bdaface3de97b8775a44d753c3adca3f7c6f183cc8647e229070439aa9539ae1f8f13470c9d3527fffdeef6c94f9f0520ff0c1ba8b16e16014e1af43ac6d94cb7929188cce9d7b02f81a2746f52ba16988e5f6d93298d778dfe05ea0ef256ae3728643ce3e29c794a0370e9ca6a8bf3e7a41e86770676ac106f7ae79e67027ce7b7b38efe27d253a52b5cb54d6eb4367a87736ed48cb45ef27f42683da140ed3295dfc575d3ea38cfc2a3697cc92864305407369b4abac054e497378dd9fd0c4b352ea3185ce1178b3dc1599df69db29259d4735320c8e7d33e8226620c9a1d22761f1d35bdff79a"
' Convert to byte array form
abMsg = cnvBytesFromHexStr(strMsgHex)
nMsgLen = UBound(abMsg) + 1

nOutBytes = (nOutBits / 8)
ReDim abOut(nOutBytes - 1)
nRet = XOF_Bytes(abOut(0), nOutBytes, abMsg(0), nMsgLen, API_XOF_SHAKE256)
If nRet > 0 Then
    Debug.Print "OUT=" & cnvHexStrFromBytes(abOut)
    Debug.Print "OK =" & strOK
Else
   Debug.Print "Error code " & nRet
End If

```

This should result in output as follows:

```

OUT=B9B92544FB25CFE4EC6FE437D8DA2BBE00F7BDAFACE3DE97B8775A44D753C3ADCA3F7C6F183CC8647E229070439AA9539AE1F8F13470C9D3527FFFDEEF6C94F9F0520FF0C1BA8B16E16014E1AF43AC6D94CB7929188CCE9D7B02F81A2746F52BA16988E5F6D93298D778DFE05EA0EF256AE3728643CE3E29C794A0370E9CA6A8BF3E7A41E86770676AC106F7AE79E67027CE7B7B38EFE27D253A52B5CB54D6EB4367A87736ED48CB45EF27F42683DA140ED3295DFC575D3EA38CFC2A3697CC92864305407369B4ABAC054E497378DD9FD0C4B352EA3185CE1178B3DC1599DF69DB29259D4735320C8E7D33E8226620C9A1D22761F1D35BDFF79A
OK =b9b92544fb25cfe4ec6fe437d8da2bbe00f7bdaface3de97b8775a44d753c3adca3f7c6f183cc8647e229070439aa9539ae1f8f13470c9d3527fffdeef6c94f9f0520ff0c1ba8b16e16014e1af43ac6d94cb7929188cce9d7b02f81a2746f52ba16988e5f6d93298d778dfe05ea0ef256ae3728643ce3e29c794a0370e9ca6a8bf3e7a41e86770676ac106f7ae79e67027ce7b7b38efe27d253a52b5cb54d6eb4367a87736ed48cb45ef27f42683da140ed3295dfc575d3ea38cfc2a3697cc92864305407369b4abac054e497378dd9fd0c4b352ea3185ce1178b3dc1599df69db29259d4735320c8e7d33e8226620c9a1d22761f1d35bdff79a

```

### Example (VBA wrapper function)

```

Dim lpMessage() As Byte
Dim lpOut() As Byte
lpMessage = cnvBytesFromHexStr("6ae23f058f0f2264a18cd609acc26dd4dbc00f5c3ee9e13ecaea2bb5a2f0bb6b")
' Output 2000 bits
lpOut = xofBytes(2000 \ 8, lpMessage, API_XOF_SHAKE256)
Debug.Print "OUT=" & cnvHexStrFromBytes(lpOut)
Debug.Print "OK =" & "b9b92544fb25cf...f1d35bdff79a"

```

### See Also

[`MAC_Bytes`](#MAC_Bytes)
[`PRF_Bytes`](#PRF_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

<a id="ZLIB_Deflate"></a>ZLIB_Deflate
-------------------------------------

Compresses data using the ZLIB deflate algorithm.

### VBA/VB6 Syntax

`Public Declare Function ZLIB_Deflate Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByVal nOutBytes As Long, 
    ByRef lpInput As Byte, ByVal nInputLen As Long) As Long`

`nRet = ZLIB_Deflate(lpOutput(0), nOutBytes, abInput(0), nInputLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  ZLIB_Deflate(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nBytes);`

### Parameters

*lpOutput*
:   [out] abyte buffer to receive output data.

*nOutBytes*
:   [in] size of the output buffer in bytes.

*lpInput*
:   [in] input data to be compressed.

*nBytes*
:   [in] length of input array in bytes.

### Returns (VBA/C)

The number of bytes successfully copied into the output buffer or the required size in bytes. 
If an error occurs, it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [zlibDeflate](#VB_zlibDeflate)(lpInput() As Byte) As Byte()`

### .NET Equivalent

[Zlib.Deflate Method](#M_Zlib_Deflate)  

### Remarks

To determine the required size of the output buffer, call the function with *nOutBytes* set to zero (or *lpOutput* set to NULL).

### Example (VBA core function)

```

Dim strPlain As String
Dim strBack As String
Dim abPlain() As Byte
Dim abCompressed() As Byte
Dim nCompLen As Long
Dim nUncompLen As Long
Dim nRet As Long

' COMPRESSSION (deflation)

' Set the plaintext message
strPlain = "hello, hello, hello. This is a 'hello world' message " & _
    "for the world, repeat, for the world."
' Convert to an array of bytes
abPlain = StrConv(strPlain, vbFromUnicode)
nUncompLen = UBound(abPlain) + 1
' Find required compressed length by calling with zero length value
nCompLen = ZLIB_Deflate(0, 0, abPlain(0), nUncompLen)
Debug.Print "COMPR-LEN=" & nCompLen
ReDim abCompressed(nCompLen - 1)
' Now compress plaintext
Call ZLIB_Deflate(abCompressed(0), nCompLen, abPlain(0), nUncompLen)
' Display compressed data in hex
Debug.Print "COMPR-DATA=" & cnvHexStrFromBytes(abCompressed)

' DECOMPRESSSION (inflation)

' Uncompress the compressed data
' New in [v5.3]: we can find the uncompressed length from compressed data
nUncompLen = ZLIB_Inflate(0, 0, abCompressed(0), nCompLen)
Debug.Print "Uncompressed length = " & nUncompLen
Debug.Assert (nUncompLen > 0)
ReDim abPlain(nUncompLen - 1)
nRet = ZLIB_Inflate(abPlain(0), nUncompLen, abCompressed(0), nCompLen)

' Convert back to a string
strBack = StrConv(abPlain, vbUnicode)
Debug.Print strBack

```

```

COMPR-LEN=68
COMPR-DATA=789CCB48CDC9C9D751C840A2F4144232328B15802851411D2CA2509E5F9493A2AE909B5A5C9C989EAA90965FA45092910A11D651284A2D484D2CD14115D6030086D11F4E
Uncompressed length = 90
hello, hello, hello. This is a 'hello world' message for the world, repeat, for the world.	

```

### Example (VBA wrapper function)

```

Dim strPlain As String
Dim lpToCompress() As Byte
Dim lpCompressed() As Byte
Dim lpUncompressed() As Byte
strPlain = "hello, hello, hello. This is a 'hello world' message " & _
    "for the world, repeat, for the world."
lpToCompress = StrConv(strPlain, vbFromUnicode)
lpCompressed = zlibDeflate(lpToCompress)
Debug.Print "OK=        " & "789CCB48CDC9C9D751C840A2F4144232328B15802851411D2CA2509E5F9493A2AE909B5A5C9C989EAA90965FA45092910A11D651284A2D484D2CD14115D6030086D11F4E"
Debug.Print "COMPRESSED=" & cnvHexStrFromBytes(lpCompressed)
lpUncompressed = zlibInflate(lpCompressed)
Debug.Print "'" & StrConv(lpUncompressed, vbUnicode); "'"

```

### See Also

[`ZLIB_Inflate`](#ZLIB_Inflate)

[[Contents](#topofpage)] [[Index](#index)]

<a id="ZLIB_Inflate"></a>ZLIB_Inflate
-------------------------------------

Inflates compressed data using the ZLIB uncompress algorithm.

### VBA/VB6 Syntax

`Public Declare Function ZLIB_Inflate Lib "diCryptoSys.dll"
    (ByRef lpOutput As Byte, ByVal nOutBytes As Long, 
    ByRef lpInput As Byte, ByVal nInputLen As Long) As Long`

`nRet = ZLIB_Inflate(lpOutput(0), nOutBytes, abInput(0), nInputLen)
' Note the "(0)" after the byte array parameters`

### C/C++ Syntax

`long __stdcall  ZLIB_Inflate(unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nBytes);`

### Parameters

*lpOutput*
:   [out] byte buffer to receive output data.

*nOutBytes*
:   [in] size of the output buffer in bytes.

*lpInput*
:   [in] input data to be uncompressed.

*nBytes*
:   [in] length of input array in bytes.

### Returns (VBA/C)

The number of bytes successfully copied into the output buffer or the required size in bytes. 
If an error occurs, it returns a negative [error code](#errorcodes).

### VBA Wrapper Syntax

`Public Function [zlibInflate](#VB_zlibInflate)(lpInput() As Byte) As Byte()`

### .NET Equivalent

[Zlib.Inflate Method](#M_Zlib_Inflate_Byte) (Byte[])  

[Zlib.Inflate Method](#M_Zlib_Inflate_ByteInt32) (Byte[], Int32)  

### Remarks

[*New in v5.3*] This function will now compute the required output length for the output buffer. In earlier versions you needed to know the size by other means.

To determine the required size of the output buffer, call the function with *nOutBytes* set to zero (or *lpOutput* set to NULL).

### Example (VBA core function)

See [`ZLIB_Deflate`](#ZLIB_Deflate).

### Example (VBA wrapper function)

```

Dim strPlain As String
Dim lpToCompress() As Byte
Dim lpCompressed() As Byte
Dim lpUncompressed() As Byte
strPlain = "hello, hello, hello. This is a 'hello world' message " & _
    "for the world, repeat, for the world."
lpToCompress = StrConv(strPlain, vbFromUnicode)
lpCompressed = zlibDeflate(lpToCompress)
Debug.Print "OK=        " & "789CCB48CDC9C9D751C840A2F4144232328B15802851411D2CA2509E5F9493A2AE909B5A5C9C989EAA90965FA45092910A11D651284A2D484D2CD14115D6030086D11F4E"
Debug.Print "COMPRESSED=" & cnvHexStrFromBytes(lpCompressed)
lpUncompressed = zlibInflate(lpCompressed)
Debug.Print "'" & StrConv(lpUncompressed, vbUnicode); "'"

```

### See Also

[`ZLIB_Deflate`](#ZLIB_Deflate)

[[Contents](#topofpage)] [[Index](#index)]

<a id="vbawrapperfunctions"></a>VBA Wrapper Functions
-----------------------------------------------------

*New in [v6.20]:* All VBA wrapper functions and definitions are now in the one file `basCryptoSys.bas`.
The file `basCryptoSysWrappers.bas` is withdrawn and must not be used with v6.20 and above.
See [Notes on VBA wrapper functions](#notesonvbawrapperfunctions).

### <a id="vbawrapperfunctionlist"></a>VBA Wrapper Function List

* [aeadAddAAD](#VB_aeadAddAAD) - Add a chunk of additional authenticated data (in incremental mode).
* [aeadDecryptWithTag](#VB_aeadDecryptWithTag) - Decrypt data using specified AEAD algorithm in one-off operation.
* [aeadDestroy](#VB_aeadDestroy) - Close the AEAD context and destroy the key (in incremental mode).
* [aeadEncryptWithTag](#VB_aeadEncryptWithTag) - Encrypt data using specified AEAD algorithm in one-off operation.
* [aeadFinishDecrypt](#VB_aeadFinishDecrypt) - Finish the authenticated decryption (in incremental mode).
* [aeadFinishEncrypt](#VB_aeadFinishEncrypt) - Finish the authenticated encryption (in incremental mode).
* [aeadInitKey](#VB_aeadInitKey) - Initialize the AEAD context with the key and algorithm ready for repeated incremental operations.
* [aeadSetNonce](#VB_aeadSetNonce) - Set the nonce for the AEAD context (in incremental mode).
* [aeadStartDecrypt](#VB_aeadStartDecrypt) - Start authenticated decryption (in incremental mode).
* [aeadStartEncrypt](#VB_aeadStartEncrypt) - Start authenticated encryption (in incremental mode).
* [aeadUpdate](#VB_aeadUpdate) - Encrypts or decrypts a chunk of input (in incremental mode).
* [apiCompileTime](#VB_apiCompileTime) - Gets date and time the CryptoSys DLL module was last compiled.
* [apiErrorCode](#VB_apiErrorCode) - Returns the error code of the error that occurred when calling the last function.
* [apiErrorLookup](#VB_apiErrorLookup) - Retrieves the error message associated with a given error code.
* [apiLicenceType](#VB_apiLicenceType) - Returns the ASCII value of the licence type.
* [apiModuleInfo](#VB_apiModuleInfo) - Get additional information about the core DLL module.
* [apiModuleName](#VB_apiModuleName) - Retrieves the name of the current process's module.
* [apiPlatform](#VB_apiPlatform) - Get platform the core DLL was compiled for.
* [apiVersion](#VB_apiVersion) - Get version number of native core DLL.
* [blfBytesBlock](#VB_blfBytesBlock) - Encrypt or decrypt a block of data using Blowfish algorithm.
* [cipherDecryptBytes](#VB_cipherDecryptBytes) - Decrypts data in a byte array using the specified block cipher algorithm, mode and padding.
* [cipherDecryptHex](#VB_cipherDecryptHex) - Decrypt hex-encoded data using the specified block cipher algorithm, mode and padding.
* [cipherEncryptBytes](#VB_cipherEncryptBytes) - Encrypts data in a byte array using the specified block cipher algorithm, mode and padding.
* [cipherEncryptHex](#VB_cipherEncryptHex) - Encrypt hex-encoded data using the specified block cipher algorithm, mode and padding.
* [cipherFileDecrypt](#VB_cipherFileDecrypt) - Decrypt a file with block cipher.
* [cipherFileEncrypt](#VB_cipherFileEncrypt) - Encrypt a file with block cipher.
* [cipherFinal](#VB_cipherFinal) - Closes and clears the CIPHER context.
* [cipherInit](#VB_cipherInit) - Initializes the CIPHER context with the key, algorithm and mode ready for repeated incremental operations.
* [cipherInitHex](#VB_cipherInitHex) - Initializes the CIPHER context with hex-encoded key, algorithm and mode ready for repeated incremental operations.
* [cipherKeyUnwrap](#VB_cipherKeyUnwrap) - Unwraps (decrypts) key material with a key-encryption key.
* [cipherKeyWrap](#VB_cipherKeyWrap) - Wraps (encrypts) key material with a key-encryption key.
* [cipherStreamBytes](#VB_cipherStreamBytes) - Encipher data in array of bytes using specified stream cipher.
* [cipherStreamFile](#VB_cipherStreamFile) - Encipher data in a file using specified stream cipher.
* [cipherStreamFinal](#VB_cipherStreamFinal) - Close the CIPHERSTREAM context and destroy the key.
* [cipherStreamHex](#VB_cipherStreamHex) - Encipher data in a hex-encoded string using specified stream cipher.
* [cipherStreamInit](#VB_cipherStreamInit) - Initialize the CIPHERSTREAM context ready for repeated operations of
* [cipherStreamUpdate](#VB_cipherStreamUpdate) - Encrypt input using current CIPHERSTREAM context (in incremental mode).
* [cipherUpdate](#VB_cipherUpdate) - Encrypts or decrypts a chunk of input (in incremental mode).
* [cipherUpdateHex](#VB_cipherUpdateHex) - Encrypts or decrypts a chunk of hex-encoded input (in incremental mode).
* [cnvB64Filter](#VB_cnvB64Filter) - Strips any invalid base64 characters from a string.
* [cnvB64StrFromBytes](#VB_cnvB64StrFromBytes) - Encodes an array of bytes as a base64-encoded string.
* [cnvB64StrFromHexStr](#VB_cnvB64StrFromHexStr) - Re-encodes a hexadecimal-encoded binary value as base64.
* [cnvB64StrFromString](#VB_cnvB64StrFromString) - Encodes an ANSI string as a base64-encoded string.
* [cnvBytesFromB64Str](#VB_cnvBytesFromB64Str) - Decodes a base64-encoded string as an array of Bytes.
* [cnvBytesFromHexStr](#VB_cnvBytesFromHexStr) - Decodes a hexadecimal-encoded string as an array of Bytes.
* [cnvBytesLen](#VB_cnvBytesLen) - Find length of byte array.
* [cnvBytesMid](#VB_cnvBytesMid) - Return a substring of bytes of specified length from within a given byte array
* [cnvFromBase64](#VB_cnvFromBase64) - Decodes a base64-encoded string as an array of bytes.
* [cnvFromHex](#VB_cnvFromHex) - Decodes a hexadecimal-encoded string as an array of bytes.
* [cnvHexFilter](#VB_cnvHexFilter) - Strips any invalid hex characters from a hex string.
* [cnvHexFromBytesMid](#VB_cnvHexFromBytesMid) - Encodes a substring of an array of bytes as a hexadecimal-encoded string.
* [cnvHexStrFromB64Str](#VB_cnvHexStrFromB64Str) - Re-encodes a base64-encoded binary value as hexadecimal.
* [cnvHexStrFromBytes](#VB_cnvHexStrFromBytes) - Encodes an array of bytes as a hexadecimal-encoded string.
* [cnvHexStrFromString](#VB_cnvHexStrFromString) - Encodes an ANSI string as a hexadecimal-encoded string.
* [cnvStringFromHexStr](#VB_cnvStringFromHexStr) - Decodes a hexadecimal-encoded string as an ANSI string.
* [cnvToBase64](#VB_cnvToBase64) - Encodes an array of bytes as a base64-encoded string.
* [cnvToHex](#VB_cnvToHex) - Encodes an array of bytes as a hexadecimal-encoded string.
* [comprCompress](#VB_comprCompress) - Compress data using compression algorithm.
* [comprUncompress](#VB_comprUncompress) - Uncompress data using compression algorithm.
* [crcBytes](#VB_crcBytes) - Compute the CRC-32 checksum of an array of bytes.
* [crcFile](#VB_crcFile) - Compute the CRC-32 checksum of a file.
* [crcString](#VB_crcString) - Compute the CRC-32 checksum of an ANSI string.
* [errFormatErrorMessage](#VB_errFormatErrorMessage) - Return an error message string for the last error.
* [hashAddBytes](#VB_hashAddBytes) - Add an array of bytes to be digested.
* [hashAddString](#VB_hashAddString) - Add a string to be digested.
* [hashBytes](#VB_hashBytes) - Compute hash digest in byte format of byte input.
* [hashFile](#VB_hashFile) - Compute hash digest in byte format of a file.
* [hashFinal](#VB_hashFinal) - Return the final message digest value.
* [hashHexFromBits](#VB_hashHexFromBits) - Compute hash digest in hex format from bit-oriented input.
* [hashHexFromBytes](#VB_hashHexFromBytes) - Compute hash digest in hex format of byte input.
* [hashHexFromFile](#VB_hashHexFromFile) - Compute hash digest in hex format of a file.
* [hashHexFromHex](#VB_hashHexFromHex) - Compute hash digest in hex-encoded format from hex-encoded input.
* [hashHexFromString](#VB_hashHexFromString) - Compute hash digest in hex-encoded format from hex-encoded input.
* [hashInit](#VB_hashInit) - Initialise the HASH context ready for incremental operations.
* [hashLength](#VB_hashLength) - Return length of message digest output in bytes.
* [macAddBytes](#VB_macAddBytes) - Adds an array of bytes to be authenticated.
* [macAddString](#VB_macAddString) - Adds a string to be authenticated.
* [macBytes](#VB_macBytes) - Computes a keyed MAC in byte format from byte input.
* [macFinal](#VB_macFinal) - Returns the final MAC value.
* [macHexFromBytes](#VB_macHexFromBytes) - Computes a keyed MAC in hex-encoded format from byte input.
* [macHexFromHex](#VB_macHexFromHex) - Computes a keyed MAC in hex-encoded format from hex-encoded input.
* [macInit](#VB_macInit) - Initialises the MAC context ready to receive data to authenticate.
* [padBytesBlock](#VB_padBytesBlock) - Creates an input block suitably padded for encryption by a block cipher in ECB or CBC mode.
* [padHexBlock](#VB_padHexBlock) - Creates a hex-encoded input block suitably padded for encryption by a block cipher in ECB or CBC mode.
* [padHexString](#VB_padHexString) - Add PKCS5 padding to a hex string up to next multiple of block length [DEPRECATED].
* [padUnpadBytes](#VB_padUnpadBytes) - Removes the padding from an encryption block.
* [padUnpadHex](#VB_padUnpadHex) - Removes the padding from a hex-encoded encryption block.
* [pbeKdf2](#VB_pbeKdf2) - Derives a key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1.
* [pbeKdf2Hex](#VB_pbeKdf2Hex) - Derives a hex-encoded key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1.
* [pbeScrypt](#VB_pbeScrypt) - Derives a key of any length from a password using the SCRYPT algorithm from RFC7914.
* [pbeScryptHex](#VB_pbeScryptHex) - Derives a hex-encoded key of any length from a password using the SCRYPT algorithm from RFC7914.
* [prfBytes](#VB_prfBytes) - Generate output bytes using a pseudorandom function (PRF).
* [rngInitialize](#VB_rngInitialize) - Initialize the RNG generator using a seed file.
* [rngInitializeEx](#VB_rngInitializeEx) - Query and initialize the RNG generator using Intel(R) DRNG, if available.
* [rngKeyBytes](#VB_rngKeyBytes) - Generate a random key value.
* [rngKeyHex](#VB_rngKeyHex) - Generate a random key in hex format.
* [rngNonce](#VB_rngNonce) - Generate a random nonce.
* [rngNonceHex](#VB_rngNonceHex) - Generate a hex-encoded sequence of bytes.
* [unpadHexString](#VB_unpadHexString) - Strips PKCS5 padding from a hex string [DEPRECATED].
* [wipeBytes](#VB_wipeBytes) - Zeroise data in memory.
* [wipeFile](#VB_wipeFile) - Securely wipes and deletes a file using 7-pass DOD standards.
* [wipeString](#VB_wipeString) - Zeroise a string.
* [xofBytes](#VB_xofBytes) - Generate bytes using an extendable-output function (XOF).
* [zlibDeflate](#VB_zlibDeflate) - Compress data using the ZLIB deflate algorithm.
* [zlibInflate](#VB_zlibInflate) - Inflate compressed data using the ZLIB algorithm.

### <a id="VB_aeadAddAAD"></a>aeadAddAAD

Add a chunk of additional authenticated data (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadAddAAD ( _
    hContext As Long, _
    lpAAD() As Byte _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

lpAAD

:   Chunk of Additional Authenticated Data (AAD) to add.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

May be repeated to add additional data in chunks.
Must eventually be followed by either [aeadStartEncrypt](#VB_aeadStartEncrypt) or [aeadStartDecrypt](#VB_aeadStartDecrypt).
Returns `MISUSE_ERROR` if called out of sequence.

---

### <a id="VB_aeadDecryptWithTag"></a>aeadDecryptWithTag

Decrypt data using specified AEAD algorithm in one-off operation. The authentication tag is expected to be appended to the input ciphertext.

#### Syntax

[VBA]

```

Public Function aeadDecryptWithTag ( _
    lpData() As Byte, _
    lpKey() As Byte, _
    lpNonce() As Byte, _
    lpAAD() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpData

:   Input data to be decrypted.

lpKey

:   Key of exact length for algorithm (16 or 32 bytes).

lpNonce

:   Initialization Vector (IV) (aka nonce) exactly 16 bytes for ASCON else exactly 12 bytes long.

lpAAD

:   Additional authenticated data (optional) - set variable as `vbNullString` to ignore.

nOptions

:   Algorithm to be used. Select one from

```

API_AEAD_AES_128_GCM
API_AEAD_AES_256_GCM
API_AEAD_CHACHA20_POLY1305
API_AEAD_ASCON_128
API_AEAD_ASCON_128A
```

Add `API_IV_PREFIX` to expect the IV to be prepended at the start of the input (use the `Or` operator).

#### Return Value

`Byte():` Plaintext in a byte array, or empty array on error (an empty array may also be the correct result).

#### Remarks

The input must include the 16-byte tag appended to the ciphertext.

---

### <a id="VB_aeadDestroy"></a>aeadDestroy

Close the AEAD context and destroy the key (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadDestroy ( _
    hContext As Long _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

---

### <a id="VB_aeadEncryptWithTag"></a>aeadEncryptWithTag

Encrypt data using specified AEAD algorithm in one-off operation. The authentication tag is appended to the output.

#### Syntax

[VBA]

```

Public Function aeadEncryptWithTag ( _
    lpData() As Byte, _
    lpKey() As Byte, _
    lpNonce() As Byte, _
    lpAAD() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpData

:   Input data to be encrypted.

lpKey

:   Key of exact length for algorithm (16 or 32 bytes).

lpNonce

:   Initialization Vector (IV) (aka nonce) exactly 16 bytes for ASCON else exactly 12 bytes long.

lpAAD

:   Additional authenticated data (optional) - set variable as `vbNullString` to ignore.

nOptions

:   Algorithm to be used. Select one from

```

API_AEAD_AES_128_GCM
API_AEAD_AES_256_GCM
API_AEAD_CHACHA20_POLY1305
API_AEAD_ASCON_128
API_AEAD_ASCON_128A
```

Add `API_IV_PREFIX` to prepend the IV (nonce) before the ciphertext in the output (use the `Or` operator).

#### Return Value

`Byte():` Ciphertext with tag appended in a byte array, or empty array on error.

#### Remarks

The output will either be exactly `taglen` (16) bytes longer than the input,
or exactly `taglen + ivlen` (28/32) bytes longer if `API_IV_PREFIX` is used.

---

### <a id="VB_aeadFinishDecrypt"></a>aeadFinishDecrypt

Finish the authenticated decryption (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadFinishDecrypt ( _
    hContext As Long _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

Returns the nonzero error code `AUTH_FAILED_ERROR` (-40) if the inputs are not authentic.
Must be preceded by [aeadStartDecrypt](#VB_aeadStartDecrypt) and zero or more calls to [aeadUpdate](#VB_aeadUpdate).
May be followed by [aeadSetNonce](#VB_aeadSetNonce) to begin processing another packet with the same key and algorithm;
otherwise should be followed by [aeadDestroy](#VB_aeadDestroy).
Returns `MISUSE_ERROR` if called out of sequence.

---

### <a id="VB_aeadFinishEncrypt"></a>aeadFinishEncrypt

Finish the authenticated encryption (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadFinishEncrypt ( _
    hContext As Long _
) As Byte()

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

#### Return Value

`Byte():` Authentication tag value.

#### Remarks

Must be preceded by [aeadStartEncrypt](#VB_aeadStartEncrypt) and zero or more calls to [aeadUpdate](#VB_aeadUpdate).
May be followed by [aeadSetNonce](#VB_aeadSetNonce) to begin processing another packet with the same key and algorithm;
otherwise should be followed by [aeadDestroy](#VB_aeadDestroy).

---

### <a id="VB_aeadInitKey"></a>aeadInitKey

Initialize the AEAD context with the key and algorithm ready for repeated incremental operations.

#### Syntax

[VBA]

```

Public Function aeadInitKey ( _
    lpKey() As Byte, _
    nOptions As Long _
) As Long

```

#### Parameters

lpKey

:   Key of exact length for algorithm (16 or 32 bytes).

nOptions

:   Algorithm to be used. Select one from

```

API_AEAD_AES_128_GCM
API_AEAD_AES_256_GCM
API_AEAD_CHACHA20_POLY1305
```

#### Return Value

`Long:` Nonzero handle of the AEAD context, or *zero* if an error occurs.

---

### <a id="VB_aeadSetNonce"></a>aeadSetNonce

Set the nonce for the AEAD context (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadSetNonce ( _
    hContext As Long, _
    lpNonce() As Byte _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

lpNonce

:   Nonce of exact length required for given algorithm (currently always 12 bytes).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

---

### <a id="VB_aeadStartDecrypt"></a>aeadStartDecrypt

Start authenticated decryption (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadStartDecrypt ( _
    hContext As Long, _
    lpTagToCheck() As Byte _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

lpTagToCheck

:   Byte array containing the tag to be checked.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

May be followed by zero or more calls to [aeadUpdate](#VB_aeadUpdate) to decrypt data in chunks.
Must eventually be followed by [aeadFinishDecrypt](#VB_aeadFinishDecrypt).
Returns `MISUSE_ERROR` if called out of sequence.
**Caution**: do not trust decrypted data until final authentication.

---

### <a id="VB_aeadStartEncrypt"></a>aeadStartEncrypt

Start authenticated encryption (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadStartEncrypt ( _
    hContext As Long _
) As Long

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

May be followed by zero or more calls to [aeadUpdate](#VB_aeadUpdate) to encrypt data in chunks.
Must eventually be followed by [aeadFinishEncrypt](#VB_aeadFinishEncrypt).
Returns `MISUSE_ERROR` if called out of sequence.

---

### <a id="VB_aeadUpdate"></a>aeadUpdate

Encrypts or decrypts a chunk of input (in incremental mode).

#### Syntax

[VBA]

```

Public Function aeadUpdate ( _
    hContext As Long, _
    lpData() As Byte _
) As Byte()

```

#### Parameters

hContext

:   Handle to the AEAD context set up by an earlier call to [aeadInitKey](#VB_aeadInitKey).

lpData

:   Data to be encrypted or decrypted.

#### Return Value

`Byte():` Encrypted or decrypted data in array of exactly the same length as input; or an empty array on error

#### Remarks

This function may be repeated to add data in chunks.
The input data is encrypted or decrypted depending on the start mode set by a preceding call to
[aeadStartEncrypt](#VB_aeadStartEncrypt) or [aeadStartDecrypt](#VB_aeadStartDecrypt), respectively.
It must eventually be followed by either [aeadFinishEncrypt](#VB_aeadFinishEncrypt) or [aeadFinishDecrypt](#VB_aeadFinishDecrypt), which must match the start mode.

---

### <a id="VB_apiCompileTime"></a>apiCompileTime

Gets date and time the CryptoSys DLL module was last compiled.

#### Syntax

[VBA]

```

Public Function apiCompileTime() As String

```

#### Return Value

`String:` Date and time string.

---

### <a id="VB_apiErrorCode"></a>apiErrorCode

Returns the error code of the error that occurred when calling the last function.

#### Syntax

[VBA]

```

Public Function apiErrorCode() As Long

```

#### Return Value

`Long:` Error code (see [apiErrorLookup](#VB_apiErrorLookup)).

#### Remarks

Not all functions set this value.

---

### <a id="VB_apiErrorLookup"></a>apiErrorLookup

Retrieves the error message associated with a given error code.

#### Syntax

[VBA]

```

Public Function apiErrorLookup ( _
    nCode As Long _
) As String

```

#### Parameters

nCode

:   Error code for which the message is required.

#### Return Value

`String:` Error message, or empty string if no corresponding error code.

---

### <a id="VB_apiLicenceType"></a>apiLicenceType

Returns the ASCII value of the licence type.

#### Syntax

[VBA]

```

Public Function apiLicenceType ( _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

nOptions

:   For future use.

#### Return Value

`String:` `D`=Developer `T`=Trial.

---

### <a id="VB_apiModuleInfo"></a>apiModuleInfo

Get additional information about the core DLL module.

#### Syntax

[VBA]

```

Public Function apiModuleInfo ( _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

nOptions

:   For future use.

#### Return Value

`String:` Additional information, e.g. "Licensed Developer Edition".

---

### <a id="VB_apiModuleName"></a>apiModuleName

Retrieves the name of the current process's module.

#### Syntax

[VBA]

```

Public Function apiModuleName ( _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

nOptions

:   For future use.

#### Return Value

`String:` File path to current DLL module.

---

### <a id="VB_apiPlatform"></a>apiPlatform

Get platform the core DLL was compiled for.

#### Syntax

[VBA]

```

Public Function apiPlatform() As String

```

#### Return Value

`String:` `"Win32"` or `"X64"`.

---

### <a id="VB_apiVersion"></a>apiVersion

Get version number of native core DLL.

#### Syntax

[VBA]

```

Public Function apiVersion() As Long

```

#### Return Value

`Long:` Version number as an integer in form `Major*100*100 + Minor*100 + Revision`. For example, version 6.1.2 would return `60102`.

---

### <a id="VB_blfBytesBlock"></a>blfBytesBlock

Encrypt or decrypt a block of data using Blowfish algorithm.

#### Syntax

[VBA]

```

Public Function blfBytesBlock ( _
    fEncrypt As Integer, _
    lpInput() As Byte, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    Optional szMode As String = "ECB" _
) As Byte()

```

#### Parameters

fEncrypt

:   ENCRYPT (True) to encrypt, DECRYPT (False) to decrypt

lpInput

:   Input data, length must be an exact multiple of 8.

lpKey

:   Key of length between 1 and 56 bytes (448 bits)

lpIV

:   Initialization vector of exactly 8 bytes

szMode

:   Encryption mode. Select one from:

```

"ECB" "CBC" "CTR" "OFB" "CFB"
```

#### Return Value

`Byte():` Output data, the same length as the input, or an empty array on error.

---

### <a id="VB_cipherDecryptBytes"></a>cipherDecryptBytes

Decrypts data in a byte array using the specified block cipher algorithm, mode and padding.
The key and initialization vector are passed as byte arrays.

#### Syntax

[VBA]

```

Public Function cipherDecryptBytes ( _
    lpInput() As Byte, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As Byte()

```

#### Parameters

lpInput

:   Input data to be decrypted.

lpKey

:   Key of exact length for block cipher algorithm.

lpIV

:   Initialization Vector (IV) of exactly the block size (if not provided in input) or empty array for ECB mode.

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to expect the IV to be prepended at the start of the input
(ignored for ECB mode).

#### Return Value

`Byte():` Decrypted plaintext in byte array or empty array on error.

#### Remarks

Default padding is `Pkcs5` for ECB and CBC mode and `NoPad` for all other modes.

---

### <a id="VB_cipherDecryptHex"></a>cipherDecryptHex

Decrypt hex-encoded data using the specified block cipher algorithm, mode and padding.
The input data, key and initialization vector are all represented as hexadecimal strings.

#### Syntax

[VBA]

```

Public Function cipherDecryptHex ( _
    szInputHex As String, _
    szKeyHex As String, _
    szIvHex As String, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

szInputHex

:   Hex-encoded input data.

szKeyHex

:   Hex-encoded key of exact key length.

szIvHex

:   Hex-encoded IV of exact block length, ignored for ECB mode or if `API_IV_PREFIX` is used (use `""`).

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to expect the IV to be prepended before the ciphertext in the input (not applicable for ECB mode).

#### Return Value

`String:` Decrypted plaintext in hex-encoded string or empty string on error.

#### Remarks

Input data may be any even number of hex characters, but not zero.
Default padding is `Pkcs5` for ECB and CBC mode and `NoPad` for all other modes.

---

### <a id="VB_cipherEncryptBytes"></a>cipherEncryptBytes

Encrypts data in a byte array using the specified block cipher algorithm, mode and padding.
The key and initialization vector are passed as byte arrays.

#### Syntax

[VBA]

```

Public Function cipherEncryptBytes ( _
    lpInput() As Byte, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As Byte()

```

#### Parameters

lpInput

:   Input data to be encrypted.

lpKey

:   Key of exact length for block cipher algorithm.

lpIV

:   Initialization Vector (IV) of exactly the block size or empty array for ECB mode.

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to prepend the IV before the ciphertext in the output
(ignored for ECB mode).

#### Return Value

`Byte():` Ciphertext in byte array or empty array on error.

#### Remarks

Default padding is `Pkcs5` for ECB and CBC mode and `NoPad` for all other modes.

---

### <a id="VB_cipherEncryptHex"></a>cipherEncryptHex

Encrypt hex-encoded data using the specified block cipher algorithm, mode and padding.
The key and initialization vector are passed as hex-encoded strings.

#### Syntax

[VBA]

```

Public Function cipherEncryptHex ( _
    szInputHex As String, _
    szKeyHex As String, _
    szIvHex As String, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

szInputHex

:   Input data to be encrypted.

szKeyHex

:   Hex-encoded key of exact key length.

szIvHex

:   Hex-encoded IV of exact block length or `""` for ECB mode.

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to prepend the IV before the ciphertext in the output
(ignored for ECB mode).

#### Return Value

`String:` Encrypted ciphertext in hex-encoded string or empty string on error.

#### Remarks

Input data may be any even number of hex characters, but not zero.
Default padding is `Pkcs5` for ECB and CBC mode and `NoPad` for all other modes.

---

### <a id="VB_cipherFileDecrypt"></a>cipherFileDecrypt

Decrypt a file with block cipher.

#### Syntax

[VBA]

```

Public Function cipherFileDecrypt ( _
    szFileOut As String, _
    szFileIn As String, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

szFileOut

:   Name of output file to be created or overwritten.

szFileIn

:   Name of input file.

lpKey

:   Key of exact length for block cipher algorithm.

lpIV

:   Initialization Vector (IV) of exactly the block size, or empty array for ECB mode or if IV already prefixed to input.

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to expect the IV to be prepended before the ciphertext in the input
(ignored for ECB mode).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

`szFileOut` and `szFileIn` must **not** be the same.

---

### <a id="VB_cipherFileEncrypt"></a>cipherFileEncrypt

Encrypt a file with block cipher.

#### Syntax

[VBA]

```

Public Function cipherFileEncrypt ( _
    szFileOut As String, _
    szFileIn As String, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    szAlgModePad As String, _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

szFileOut

:   Name of output file to be created or overwritten.

szFileIn

:   Name of input file.

lpKey

:   Key of exact length for block cipher algorithm.

lpIV

:   Initialization Vector (IV) of exactly the block size or empty array for ECB mode.

szAlgModePad

:   String with block cipher algorithm, mode and padding,
e.g. `"aes128/cbc/pkcs5"`

```

Alg:  aes128|aes192|aes256|tdea|3des|desede3
Mode: ecb|cbc|ofb|cfb|ctr
Pad:  pkcs5|nopad|oneandzeroes|ansix923|w3c
```

nOptions

:   Add `API_IV_PREFIX` to prepend the IV before the ciphertext in the output
(ignored for ECB mode).

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

`szFileOut` and `szFileIn` must **not** be the same.

---

### <a id="VB_cipherFinal"></a>cipherFinal

Closes and clears the CIPHER context.

#### Syntax

[VBA]

```

Public Function cipherFinal ( _
    hContext As Long _
) As Long

```

#### Parameters

hContext

:   Handle to the CIPHER context.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

---

### <a id="VB_cipherInit"></a>cipherInit

Initializes the CIPHER context with the key, algorithm and mode ready for repeated incremental operations.

#### Syntax

[VBA]

```

Public Function cipherInit ( _
    fEncrypt As Integer, _
    szAlgAndMode As String, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

fEncrypt

:   Direction flag: set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

szAlgAndMode

:   String with block cipher algorithm and mode, e.g. `"aes128/cbc"`

lpKey

:   Key of exact length for block cipher algorithm.

lpIV

:   Initialization Vector (IV) of exactly the block size or empty array for ECB mode.

nOptions

:   Option flags, set as zero for defaults.

#### Return Value

`Long:` Nonzero handle of the CIPHER context, or *zero* if an error occurs.

---

### <a id="VB_cipherInitHex"></a>cipherInitHex

Initializes the CIPHER context with hex-encoded key, algorithm and mode ready for repeated incremental operations.

#### Syntax

[VBA]

```

Public Function cipherInitHex ( _
    fEncrypt As Integer, _
    szAlgAndMode As String, _
    szKeyHex As String, _
    szIvHex As String, _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

fEncrypt

:   Direction flag: set as `ENCRYPT` (True) to encrypt or `DECRYPT` (False) to decrypt.

szAlgAndMode

:   String with block cipher algorithm and mode, e.g. `"aes128/cbc"`

szKeyHex

:   Hex-encoded key of exact length for block cipher algorithm.

szIvHex

:   Hex-encoded initialization vector (IV) of exactly the block size or `""` for ECB mode.

nOptions

:   Option flags, set as zero for defaults.

#### Return Value

`Long:` Nonzero handle of the CIPHER context, or *zero* if an error occurs.

---

### <a id="VB_cipherKeyUnwrap"></a>cipherKeyUnwrap

Unwraps (decrypts) key material with a key-encryption key.

#### Syntax

[VBA]

```

Public Function cipherKeyUnwrap ( _
    lpData() As Byte, _
    lpKek() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpData

:   Wrapped key.

lpKek

:   Key encryption key.

nOptions

:   Algorithm to be used. Select one from:

```

API_BC_AES128
API_BC_AES192
API_BC_AES256
API_BC_3DES
```

#### Return Value

`Byte():` Unwrapped key material (or empty array on error).

---

### <a id="VB_cipherKeyWrap"></a>cipherKeyWrap

Wraps (encrypts) key material with a key-encryption key.

#### Syntax

[VBA]

```

Public Function cipherKeyWrap ( _
    lpData() As Byte, _
    lpKek() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpData

:   Key material to be wrapped.

lpKek

:   Key encryption key.

nOptions

:   Algorithm to be used. Select one from:

```

API_BC_AES128
API_BC_AES192
API_BC_AES256
API_BC_3DES
```

#### Return Value

`Byte():` Wrapped key (or empty array on error).

---

### <a id="VB_cipherStreamBytes"></a>cipherStreamBytes

Encipher data in array of bytes using specified stream cipher.

#### Syntax

[VBA]

```

Public Function cipherStreamBytes ( _
    lpInput() As Byte, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    nOptions As Long, _
    Optional nCounter As Long = 0 _
) As Byte()

```

#### Parameters

lpInput

:   Input data.

lpKey

:   Key.

lpIV

:   Initialization Vector (IV, nonce). Use an empty array for Arcfour.

nOptions

:   Algorithm to be used. Select one from:

```

API_SC_ARCFOUR
API_SC_SALSA20
API_SC_CHACHA20
```

nCounter

:   Counter value for ChaCha20 only, otherwise ignored.

#### Return Value

`Byte():` Ciphertext in byte array, or empty array on error.

#### Remarks

*Arcfour:* any length key; use an empty array for IV.  

*Salsa20:* key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.  

*ChaCha20:* key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.  

Note different order of parameters from core function.

---

### <a id="VB_cipherStreamFile"></a>cipherStreamFile

Encipher data in a file using specified stream cipher.

#### Syntax

[VBA]

```

Public Function cipherStreamFile ( _
    szFileOut As String, _
    szFileIn As String, _
    lpKey() As Byte, _
    lpIV() As Byte, _
    nOptions As Long, _
    Optional nCounter As Long = 0 _
) As Long

```

#### Parameters

szFileOut

:   Output file to be created.

szFileIn

:   Input file to be processed.

lpKey

:   Key.

lpIV

:   Initialization Vector (IV, nonce). Use an empty array for Arcfour.

nOptions

:   Algorithm to be used. Select one from:

```

API_SC_ARCFOUR
API_SC_SALSA20
API_SC_CHACHA20
```

nCounter

:   Counter value for ChaCha20 only, otherwise ignored.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

#### Remarks

*Arcfour:* any length key; use an empty array for IV.  

*Salsa20:* key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.  

*ChaCha20:* key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.  

Note different order of parameters from core function.

---

### <a id="VB_cipherStreamFinal"></a>cipherStreamFinal

Close the CIPHERSTREAM context and destroy the key.

#### Syntax

[VBA]

```

Public Function cipherStreamFinal ( _
    hContext As Long _
) As Long

```

#### Parameters

hContext

:   Handle to the CIPHERSTREAM context.

#### Return Value

`Long:`

---

### <a id="VB_cipherStreamHex"></a>cipherStreamHex

Encipher data in a hex-encoded string using specified stream cipher.

#### Syntax

[VBA]

```

Public Function cipherStreamHex ( _
    szInputHex As String, _
    szKeyHex As String, _
    szIvHex As String, _
    nOptions As Long, _
    Optional nCounter As Long = 0 _
) As String

```

#### Parameters

szInputHex

:   Hex-encoded input data.

szKeyHex

:   Hex-encoded key.

szIvHex

:   Hex-encoded Initialization Vector (IV, nonce). Use "" for Arcfour.

nOptions

:   Algorithm to be used. Select one from:

```

API_SC_ARCFOUR
API_SC_SALSA20
API_SC_CHACHA20
```

nCounter

:   Counter value for ChaCha20 only, otherwise ignored.

#### Return Value

`String:` Ciphertext in hex-encoded string or empty string on error.

#### Remarks

*Arcfour:* any length key; specify "" for IV.  

*Salsa20:* key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.  

*ChaCha20:* key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.  

Note different order of parameters from core function.

#### Example

```

' Test vector 3
Debug.Print cipherStreamHex("00000000000000000000", "ef012345", "", API_SC_ARCFOUR)
' OK=D6A141A7EC3C38DFBD61
```

---

### <a id="VB_cipherStreamInit"></a>cipherStreamInit

Initialize the CIPHERSTREAM context ready for repeated operations of [cipherStreamUpdate](#VB_cipherStreamUpdate).

#### Syntax

[VBA]

```

Public Function cipherStreamInit ( _
    lpKey() As Byte, _
    lpIV() As Byte, _
    nOptions As Long, _
    Optional nCounter As Long = 0 _
) As Long

```

#### Parameters

lpKey

:   Key.

lpIV

:   Initialization Vector (IV, nonce). Use an empty array for Arcfour.

nOptions

:   Algorithm to be used. Select one from:

```

API_SC_ARCFOUR
API_SC_SALSA20
API_SC_CHACHA20
```

nCounter

:   Counter value for ChaCha20 only, otherwise ignored.

#### Return Value

`Long:` Nonzero handle of the CIPHERSTREAM context, or *zero* if an error occurs.

#### Remarks

*Arcfour:* any length key; use an empty array for IV.  

*Salsa20:* key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.  

*ChaCha20:* key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.  

Note different order of parameters from core function.

---

### <a id="VB_cipherStreamUpdate"></a>cipherStreamUpdate

Encrypt input using current CIPHERSTREAM context (in incremental mode).

#### Syntax

[VBA]

```

Public Function cipherStreamUpdate ( _
    hContext As Long, _
    lpData() As Byte _
) As Byte()

```

#### Parameters

hContext

:   Handle to the CIPHERSTREAM context.

lpData

:   Data to be encrypted.

#### Return Value

`Byte():` Encrypted array of exactly the same length as input; or an empty array on error

---

### <a id="VB_cipherUpdate"></a>cipherUpdate

Encrypts or decrypts a chunk of input (in incremental mode).

#### Syntax

[VBA]

```

Public Function cipherUpdate ( _
    hContext As Long, _
    lpData() As Byte _
) As Byte()

```

#### Parameters

hContext

:   Handle to the CIPHER context.

lpData

:   Input data to be processed.

#### Return Value

`Byte():` Encrypted/decrypted block the same length as the input, or an empty array on error.

#### Remarks

The input byte array must be a length exactly a multiple of the block size, except for the last chunk in CTR/OFB/CFB mode.
Input in ECB/CBC mode must be suitably padded to the correct length.

---

### <a id="VB_cipherUpdateHex"></a>cipherUpdateHex

Encrypts or decrypts a chunk of hex-encoded input (in incremental mode).

#### Syntax

[VBA]

```

Public Function cipherUpdateHex ( _
    hContext As Long, _
    szInputHex As String _
) As String

```

#### Parameters

hContext

:   Handle to the CIPHER context.

szInputHex

:   Hex-encoded input data.

#### Return Value

`String:` Hex-encoded encrypted/decrypted chunk the same length as the input, or empty string `""` on error.

#### Remarks

The input must represent data of a length exactly a multiple of the block size, except for the last chunk in CTR/OFB/CFB mode.
Input in ECB/CBC mode must be suitably padded to the correct length.

---

### <a id="VB_cnvB64Filter"></a>cnvB64Filter

Strips any invalid base64 characters from a string.

#### Syntax

[VBA]

```

Public Function cnvB64Filter ( _
    strB64 As String _
) As String

```

#### Parameters

strB64

:   String to be filtered.

#### Return Value

`String:` Filtered string.

---

### <a id="VB_cnvB64StrFromBytes"></a>cnvB64StrFromBytes

Encodes an array of bytes as a base64-encoded string.

#### Syntax

[VBA]

```

Public Function cnvB64StrFromBytes ( _
    abData() As Byte _
) As String

```

#### Parameters

abData

:   Input byte array.

#### Return Value

`String:` Base64-encoded string.

#### Remarks

Same as [cnvToBase64](#VB_cnvToBase64).

---

### <a id="VB_cnvB64StrFromHexStr"></a>cnvB64StrFromHexStr

Re-encodes a hexadecimal-encoded binary value as base64.

#### Syntax

[VBA]

```

Public Function cnvB64StrFromHexStr ( _
    strHex As String _
) As String

```

#### Parameters

strHex

:   Hex string representing a binary value.

#### Return Value

`String:` Binary value encoded in base64

---

### <a id="VB_cnvB64StrFromString"></a>cnvB64StrFromString

Encodes an ANSI string as a base64-encoded string.

#### Syntax

[VBA]

```

Public Function cnvB64StrFromString ( _
    strData As String _
) As String

```

#### Parameters

strData

:   String to be encoded.

#### Return Value

`String:` Base64-encoded string.

#### Remarks

Expecting a string of 8-bit "ANSI" characters.

---

### <a id="VB_cnvBytesFromB64Str"></a>cnvBytesFromB64Str

Decodes a base64-encoded string as an array of Bytes.

#### Syntax

[VBA]

```

Public Function cnvBytesFromB64Str ( _
    strB64 As String _
) As Byte()

```

#### Parameters

strB64

:   Base64 data to be decoded.

#### Return Value

`Byte():` Array of bytes.

#### Remarks

Same as [cnvFromBase64](#VB_cnvFromBase64).

---

### <a id="VB_cnvBytesFromHexStr"></a>cnvBytesFromHexStr

Decodes a hexadecimal-encoded string as an array of Bytes.

#### Syntax

[VBA]

```

Public Function cnvBytesFromHexStr ( _
    strHex As String _
) As Byte()

```

#### Parameters

strHex

:   Hexadecimal data to be decoded.

#### Return Value

`Byte():` Array of bytes.

#### Remarks

Same as [cnvFromHex](#VB_cnvFromHex).

---

### <a id="VB_cnvBytesLen"></a>cnvBytesLen

Find length of byte array.

#### Syntax

[VBA]

```

Public Function cnvBytesLen ( _
    ab() As Byte _
) As Long

```

#### Parameters

ab

:   Input byte array.

#### Return Value

`Long:` Number of bytes in array.

#### Remarks

Safe to use even if array is empty.

#### Example

```

Dim ab() As Byte
Debug.Print cnvBytesLen(ab) ' Expecting 0
ReDim ab(10)    ' NB actually 11 elements (0..10)
Debug.Print cnvBytesLen(ab) ' 11
ab = vbNullString   ' Set to empty array
Debug.Print cnvBytesLen(ab) ' 0
```

---

### <a id="VB_cnvBytesMid"></a>cnvBytesMid

Return a substring of bytes of specified length from within a given byte array

#### Syntax

[VBA]

```

Public Function cnvBytesMid ( _
    Bytes() As Byte, _
    nOffset As Long, _
    Optional nBytes As Long = -1 _
) As Byte()

```

#### Parameters

Bytes

:   Byte array from which to return a substring (of bytes)

nOffset

:   Offset at which substring begins. First byte is at offset zero.

nBytes

:   Number of bytes in substring (optional). If negative, copy to end of input.

#### Return Value

`Byte():`

---

### <a id="VB_cnvFromBase64"></a>cnvFromBase64

Decodes a base64-encoded string as an array of bytes.

#### Syntax

[VBA]

```

Public Function cnvFromBase64 ( _
    strBase64 As String _
) As Byte()

```

#### Parameters

strBase64

:   Base64 data to be decoded.

#### Return Value

`Byte():` Array of bytes.

#### Remarks

A shorter synonym for [cnvBytesFromB64Str](#VB_cnvBytesFromB64Str)

---

### <a id="VB_cnvFromHex"></a>cnvFromHex

Decodes a hexadecimal-encoded string as an array of bytes.

#### Syntax

[VBA]

```

Public Function cnvFromHex ( _
    strHex As String _
) As Byte()

```

#### Parameters

strHex

:   Hexadecimal-encoded data to be decoded.

#### Return Value

`Byte():` Array of bytes.

#### Remarks

A shorter synonym for [cnvBytesFromHexStr](#VB_cnvBytesFromHexStr)

---

### <a id="VB_cnvHexFilter"></a>cnvHexFilter

Strips any invalid hex characters from a hex string.

#### Syntax

[VBA]

```

Public Function cnvHexFilter ( _
    strHex As String _
) As String

```

#### Parameters

strHex

:   String to be filtered.

#### Return Value

`String:` Filtered string.

---

### <a id="VB_cnvHexFromBytesMid"></a>cnvHexFromBytesMid

Encodes a substring of an array of bytes as a hexadecimal-encoded string.

#### Syntax

[VBA]

```

Public Function cnvHexFromBytesMid ( _
    abData() As Byte, _
    nOffset As Long, _
    nBytes As Long _
) As String

```

#### Parameters

abData

:   Input byte array.

nOffset

:   Offset at which substring begins. First byte is at offset zero.

nBytes

:   Number of bytes in substring to encode.

#### Return Value

`String:` Hexadecimal-encoded string.

#### Example

```

Debug.Print cnvHexFromBytesMid(cnvBytesFromHexStr("00112233445566"), 3, 2) ' 3344
```

---

### <a id="VB_cnvHexStrFromB64Str"></a>cnvHexStrFromB64Str

Re-encodes a base64-encoded binary value as hexadecimal.

#### Syntax

[VBA]

```

Public Function cnvHexStrFromB64Str ( _
    strB64 As String _
) As String

```

#### Parameters

strB64

:   Base64 string representing a binary value.

#### Return Value

`String:` Binary value encoded in hexadecimal

---

### <a id="VB_cnvHexStrFromBytes"></a>cnvHexStrFromBytes

Encodes an array of bytes as a hexadecimal-encoded string.

#### Syntax

[VBA]

```

Public Function cnvHexStrFromBytes ( _
    abData() As Byte _
) As String

```

#### Parameters

abData

:   Input byte array.

#### Return Value

`String:` Hexadecimal-encoded string.

#### Remarks

Same as [cnvToHex](#VB_cnvToHex).

---

### <a id="VB_cnvHexStrFromString"></a>cnvHexStrFromString

Encodes an ANSI string as a hexadecimal-encoded string.

#### Syntax

[VBA]

```

Public Function cnvHexStrFromString ( _
    strData As String _
) As String

```

#### Parameters

strData

:   String to be encoded.

#### Return Value

`String:` Hexadecimal-encoded string.

#### Remarks

Expecting a string of 8-bit "ANSI" characters.

---

### <a id="VB_cnvStringFromHexStr"></a>cnvStringFromHexStr

Decodes a hexadecimal-encoded string as an ANSI string.

#### Syntax

[VBA]

```

Public Function cnvStringFromHexStr ( _
    ByVal strHex As String _
) As String

```

#### Parameters

strHex

:   Hexadecimal data to be decoded.

#### Return Value

`String:` Decoded string. For example, "6162632E" will be converted to "abc."

#### Remarks

Output is a string of "ANSI" characters of value between 0 and 255.

---

### <a id="VB_cnvToBase64"></a>cnvToBase64

Encodes an array of bytes as a base64-encoded string.

#### Syntax

[VBA]

```

Public Function cnvToBase64 ( _
    lpData() As Byte _
) As String

```

#### Parameters

lpData

:   Input byte array

#### Return Value

`String:` Base64-encoded string

#### Remarks

A shorter synonym for [cnvB64StrFromBytes](#VB_cnvB64StrFromBytes)

---

### <a id="VB_cnvToHex"></a>cnvToHex

Encodes an array of bytes as a hexadecimal-encoded string.

#### Syntax

[VBA]

```

Public Function cnvToHex ( _
    lpData() As Byte _
) As String

```

#### Parameters

lpData

:   Input byte array

#### Return Value

`String:` Hexadecimal-encoded string

#### Remarks

A shorter synonym for [cnvHexStrFromBytes](#VB_cnvHexStrFromBytes)

---

### <a id="VB_comprCompress"></a>comprCompress

Compress data using compression algorithm.

#### Syntax

[VBA]

```

Public Function comprCompress ( _
    lpInput() As Byte, _
    Optional nOptions As Long = API_COMPR_ZLIB _
) As Byte()

```

#### Parameters

lpInput

:   Data to be compressed.

nOptions

:   Compression algorithm to be used. Select one from:

```

API_COMPR_ZLIB (0)
API_COMPR_ZSTD
```

#### Return Value

`Byte():` Compressed data, or an empty array on error.

---

### <a id="VB_comprUncompress"></a>comprUncompress

Uncompress data using compression algorithm.

#### Syntax

[VBA]

```

Public Function comprUncompress ( _
    lpInput() As Byte, _
    Optional nOptions As Long = API_COMPR_ZLIB _
) As Byte()

```

#### Parameters

lpInput

:   Data to be uncompressed.

nOptions

:   Compression algorithm to be used. Select one from:

```

API_COMPR_ZLIB (0)
API_COMPR_ZSTD
```

#### Return Value

`Byte():` Uncompressed data, or an empty array on error.

---

### <a id="VB_crcBytes"></a>crcBytes

Compute the CRC-32 checksum of an array of bytes.

#### Syntax

[VBA]

```

Public Function crcBytes ( _
    lpInput() As Byte _
) As Long

```

#### Parameters

lpInput

:   Input data.

#### Return Value

`Long:` CRC-32 checksum as a 32-bit integer value.

---

### <a id="VB_crcFile"></a>crcFile

Compute the CRC-32 checksum of a file.

#### Syntax

[VBA]

```

Public Function crcFile ( _
    szFileName As String _
) As Long

```

#### Parameters

szFileName

:   Name of input file.

#### Return Value

`Long:` CRC-32 checksum as a 32-bit integer value.

---

### <a id="VB_crcString"></a>crcString

Compute the CRC-32 checksum of an ANSI string.

#### Syntax

[VBA]

```

Public Function crcString ( _
    szInput As String _
) As Long

```

#### Parameters

szInput

:   Input data.

#### Return Value

`Long:` CRC-32 checksum as a 32-bit integer value.

---

### <a id="VB_errFormatErrorMessage"></a>errFormatErrorMessage

Return an error message string for the last error.

#### Syntax

[VBA]

```

Public Function errFormatErrorMessage ( _
    Optional nErrCode As Long = 0, _
    Optional szMsg As String = "" _
) As String

```

#### Parameters

nErrCode

:   Error code returned by last call.

szMsg

:   Optional message to add.

#### Return Value

`String:` Error message as a string including previous ErrorCode, if available.

#### Example

```

Error (11): Parameter out of range (RANGE_ERROR)
```

---

### <a id="VB_hashAddBytes"></a>hashAddBytes

Add an array of bytes to be digested.

#### Syntax

[VBA]

```

Public Function hashAddBytes ( _
    hContext As Long, _
    lpData() As Byte _
) As Long

```

#### Parameters

hContext

:   Handle to the HASH context.

lpData

:   Byte array containing the next part of the message.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

---

### <a id="VB_hashAddString"></a>hashAddString

Add a string to be digested.

#### Syntax

[VBA]

```

Public Function hashAddString ( _
    hContext As Long, _
    szData As String _
) As Long

```

#### Parameters

hContext

:   Handle to the HASH context.

szData

:   String containing the next part of the message.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

---

### <a id="VB_hashBytes"></a>hashBytes

Compute hash digest in byte format of byte input.

#### Syntax

[VBA]

```

Public Function hashBytes ( _
    lpMessage() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpMessage

:   Message to be digested in byte array.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
API_HASH_ASCON_HASH
API_HASH_ASCON_HASHA
```

#### Return Value

`Byte():` Message digest in byte array.

---

### <a id="VB_hashFile"></a>hashFile

Compute hash digest in byte format of a file.

#### Syntax

[VBA]

```

Public Function hashFile ( _
    szFileName As String, _
    nOptions As Long _
) As Byte()

```

#### Parameters

szFileName

:   Name of file containing message data.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
```

Add `API_HASH_MODE_TEXT` to hash in "text" mode instead of default "binary" mode.

#### Return Value

`Byte():` Message digest in byte array.

#### Remarks

The default mode is "binary" where each byte is treated individually.
In "text" mode CR-LF pairs will be treated as a single newline (LF) character.

---

### <a id="VB_hashFinal"></a>hashFinal

Return the final message digest value.

#### Syntax

[VBA]

```

Public Function hashFinal ( _
    hContext As Long _
) As Byte()

```

#### Parameters

hContext

:   Handle to the HASH context.

#### Return Value

`Byte():` Digest in byte array or empty array on error.

#### Remarks

Computes the result of all `hashAddBytes` and `hashAddString` calls since `HASH_Init`.

---

### <a id="VB_hashHexFromBits"></a>hashHexFromBits

Compute hash digest in hex format from bit-oriented input.

#### Syntax

[VBA]

```

Public Function hashHexFromBits ( _
    lpData() As Byte, _
    nDataBitLen As Long, _
    nOptions As Long _
) As String

```

#### Parameters

lpData

:   Bit-oriented message data in byte array.

nDataBitLen

:   length of the message data in *bits*.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
```

#### Return Value

`String:` Message digest in hex-encoded format.

#### Remarks

Only the SHA family of hash functions is supported in bit-oriented mode.
Pass a bitstring as an array of bytes in `lpData` in big-endian order with the most-significant bit first.
The bitstring will be truncated to the number of bits specified in `nDataBitLen` and extraneous bits on the right will be ignored.

#### Example

```

' NIST SHAVS CAVS 11.0 "SHA-1 ShortMsg" information
lpData = cnvBytesFromHexStr("5180")  ' 9-bit bitstring = 0101 0001 1
strDigest = hashHexFromBits(lpData, 9, API_HASH_SHA1)
Debug.Print "MD = " & strDigest
Debug.Print "OK = 0f582fa68b71ecdf1dcfc4946019cf5a18225bd2"
```

---

### <a id="VB_hashHexFromBytes"></a>hashHexFromBytes

Compute hash digest in hex format of byte input.

#### Syntax

[VBA]

```

Public Function hashHexFromBytes ( _
    lpMessage() As Byte, _
    nOptions As Long _
) As String

```

#### Parameters

lpMessage

:   Message to be digested in byte array.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
API_HASH_ASCON_HASH
API_HASH_ASCON_HASHA
```

#### Return Value

`String:` Message digest in hex-encoded format.

---

### <a id="VB_hashHexFromFile"></a>hashHexFromFile

Compute hash digest in hex format of a file.

#### Syntax

[VBA]

```

Public Function hashHexFromFile ( _
    szFileName As String, _
    nOptions As Long _
) As String

```

#### Parameters

szFileName

:   Name of file containing message data.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
```

Add `API_HASH_MODE_TEXT` to hash in "text" mode instead of default "binary" mode.

#### Return Value

`String:` Message digest in hex-encoded format.

#### Remarks

The default mode is "binary" where each byte is treated individually.
In "text" mode CR-LF pairs will be treated as a single newline (LF) character.

---

### <a id="VB_hashHexFromHex"></a>hashHexFromHex

Compute hash digest in hex-encoded format from hex-encoded input.

#### Syntax

[VBA]

```

Public Function hashHexFromHex ( _
    szMsgHex As String, _
    nOptions As Long _
) As String

```

#### Parameters

szMsgHex

:   Message to be digested in hex-encoded format.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
API_HASH_ASCON_HASH
API_HASH_ASCON_HASHA
```

#### Return Value

`String:` Message digest in hex-encoded format.

---

### <a id="VB_hashHexFromString"></a>hashHexFromString

Compute hash digest in hex-encoded format from hex-encoded input.

#### Syntax

[VBA]

```

Public Function hashHexFromString ( _
    szMessage As String, _
    nOptions As Long _
) As String

```

#### Parameters

szMessage

:   Message data string.

nOptions

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
API_HASH_ASCON_HASH
API_HASH_ASCON_HASHA
```

#### Return Value

`String:` Message digest in hex-encoded format.

---

### <a id="VB_hashInit"></a>hashInit

Initialise the HASH context ready for incremental operations.

#### Syntax

[VBA]

```

Public Function hashInit ( _
    Optional nAlg As Long = 0 _
) As Long

```

#### Parameters

nAlg

:   Algorithm to be used. Select one from:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
```

#### Return Value

`Long:` Nonzero handle of the HASH context, or *zero* if an error occurs.

#### Remarks

Only the SHA-1, SHA-2 and SHA-3 families of hash algorithms are supported in incremental mode.
While the context handle is valid, add data to be digested in blocks of any length using
[hashAddBytes](#VB_hashAddBytes) or [hashAddString](#VB_hashAddString).

---

### <a id="VB_hashLength"></a>hashLength

Return length of message digest output in bytes.

#### Syntax

[VBA]

```

Public Function hashLength ( _
    nAlgId As Long _
) As Long

```

#### Parameters

nAlgId

:   Algorithm Id flag. Select one of `API_HASH_*` or `API_HMAC_*`, for example:

```

API_HASH_SHA1
API_HASH_SHA224
API_HASH_SHA256
API_HASH_SHA384
API_HASH_SHA512
API_HASH_SHA3_224
API_HASH_SHA3_256
API_HASH_SHA3_384
API_HASH_SHA3_512
API_HASH_MD5
API_HASH_MD2
API_HASH_RMD160
API_HASH_ASCON_HASH
API_HASH_ASCON_HASHA
```

#### Return Value

`Long:` Length of the hash function output in bytes; else a negative error code.

#### Example

```

Debug.Print hashLength(API_HASH_SHA512)
64
```

---

### <a id="VB_macAddBytes"></a>macAddBytes

Adds an array of bytes to be authenticated.

#### Syntax

[VBA]

```

Public Function macAddBytes ( _
    hContext As Long, _
    lpData() As Byte _
) As Long

```

#### Parameters

hContext

:   Handle to the MAC context.

lpData

:   Byte array containing the next part of the message.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

---

### <a id="VB_macAddString"></a>macAddString

Adds a string to be authenticated.

#### Syntax

[VBA]

```

Public Function macAddString ( _
    hContext As Long, _
    szData As String _
) As Long

```

#### Parameters

hContext

:   Handle to the MAC context.

szData

:   String containing the next part of the message.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check)

---

### <a id="VB_macBytes"></a>macBytes

Computes a keyed MAC in byte format from byte input.

#### Syntax

[VBA]

```

Public Function macBytes ( _
    lpMessage() As Byte, _
    lpKey() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

lpMessage

:   Message to be signed in byte format.

lpKey

:   Key in byte format.

nOptions

:   Algorithm to be used. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
API_HMAC_MD5
API_HMAC_RMD160
API_HMAC_SHA3_224
API_HMAC_SHA3_256
API_HMAC_SHA3_384
API_HMAC_SHA3_512
API_CMAC_TDEA
API_CMAC_AES128
API_CMAC_AES192
API_CMAC_AES256
API_MAC_POLY1305
API_KMAC_128
API_KMAC_256
```

#### Return Value

`Byte():` MAC value in hex-encoded format.

---

### <a id="VB_macFinal"></a>macFinal

Returns the final MAC value.

#### Syntax

[VBA]

```

Public Function macFinal ( _
    hContext As Long _
) As Byte()

```

#### Parameters

hContext

:   Handle to the MAC context.

#### Return Value

`Byte():` MAC in byte array or empty array on error.

#### Remarks

Computes the result of all `macAddBytes` and `macAddString` calls since `macInit`.

---

### <a id="VB_macHexFromBytes"></a>macHexFromBytes

Computes a keyed MAC in hex-encoded format from byte input.

#### Syntax

[VBA]

```

Public Function macHexFromBytes ( _
    lpMessage() As Byte, _
    lpKey() As Byte, _
    nOptions As Long _
) As String

```

#### Parameters

lpMessage

:   Message to be signed in byte format.

lpKey

:   Key in byte format.

nOptions

:   Algorithm to be used. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
API_HMAC_MD5
API_HMAC_RMD160
API_HMAC_SHA3_224
API_HMAC_SHA3_256
API_HMAC_SHA3_384
API_HMAC_SHA3_512
API_CMAC_TDEA
API_CMAC_AES128
API_CMAC_AES192
API_CMAC_AES256
API_MAC_POLY1305
API_KMAC_128
API_KMAC_256
```

#### Return Value

`String:` MAC value in hex-encoded format.

---

### <a id="VB_macHexFromHex"></a>macHexFromHex

Computes a keyed MAC in hex-encoded format from hex-encoded input.

#### Syntax

[VBA]

```

Public Function macHexFromHex ( _
    szMsgHex As String, _
    szKeyHex As String, _
    nOptions As Long _
) As String

```

#### Parameters

szMsgHex

:   Message to be signed in hex-encoded format.

szKeyHex

:   Key in hex-encoded format.

nOptions

:   Algorithm to be used. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
API_HMAC_MD5
API_HMAC_RMD160
API_HMAC_SHA3_224
API_HMAC_SHA3_256
API_HMAC_SHA3_384
API_HMAC_SHA3_512
API_CMAC_TDEA
API_CMAC_AES128
API_CMAC_AES192
API_CMAC_AES256
API_MAC_POLY1305
API_KMAC_128
API_KMAC_256
```

#### Return Value

`String:` MAC value in hex-encoded format.

---

### <a id="VB_macInit"></a>macInit

Initialises the MAC context ready to receive data to authenticate.

#### Syntax

[VBA]

```

Public Function macInit ( _
    lpKey() As Byte, _
    nAlg As Long _
) As Long

```

#### Parameters

lpKey

:   Key in byte format.

nAlg

:   Algorithm to be used. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
```

#### Return Value

`Long:` Nonzero handle of the MAC context, or *zero* if an error occurs.

#### Remarks

Once initialized, use the context for subsequent calls to `macAddBytes`, `macAddString` and `macFinal`.

---

### <a id="VB_padBytesBlock"></a>padBytesBlock

Creates an input block suitably padded for encryption by a block cipher in ECB or CBC mode.

#### Syntax

[VBA]

```

Public Function padBytesBlock ( _
    lpInput() As Byte, _
    nBlkLen As Long, _
    Optional nOptions As Long = 0 _
) As Byte()

```

#### Parameters

lpInput

:   Plaintext bytes to be padded.

nBlkLen

:   Cipher block length in bytes (8 or 16).

nOptions

:   Use 0 for default PKCS5 padding or select one of:

```

API_PAD_1ZERO
API_PAD_AX923
API_PAD_W3C
```

#### Return Value

`Byte():` Padded data in byte array.

---

### <a id="VB_padHexBlock"></a>padHexBlock

Creates a hex-encoded input block suitably padded for encryption by a block cipher in ECB or CBC mode.

#### Syntax

[VBA]

```

Public Function padHexBlock ( _
    szInput As String, _
    nBlkLen As Long, _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

szInput

:   Hexadecimal-encoded data to be padded.

nBlkLen

:   Cipher block length in bytes (8 or 16).

nOptions

:   Use 0 for default PKCS5 padding or select one of:

```

API_PAD_1ZERO
API_PAD_AX923
API_PAD_W3C
```

#### Return Value

`String:` Padded data in byte array.

---

### <a id="VB_padHexString"></a>padHexString

Add PKCS5 padding to a hex string up to next multiple of block length [DEPRECATED].

#### Syntax

[VBA]

```

Public Function padHexString ( _
    ByVal strInputHex As String, _
    nBlockLen As Long _
) As String

```

#### Parameters

strInputHex

:   Hexadecimal-encoded data to be padded.

nBlockLen

:   Cipher block length in bytes (8 or 16).

#### Return Value

`String:` Padded hex string or empty string on error.

#### Deprecated

Use `padHexBlock()`.

---

### <a id="VB_padUnpadBytes"></a>padUnpadBytes

Removes the padding from an encryption block.

#### Syntax

[VBA]

```

Public Function padUnpadBytes ( _
    lpInput() As Byte, _
    nBlkLen As Long, _
    Optional nOptions As Long = 0 _
) As Byte()

```

#### Parameters

lpInput

:   Padded data.

nBlkLen

:   Cipher block length in bytes (8 or 16).

nOptions

:   Use 0 for default PKCS5 padding or select one of:

```

API_PAD_1ZERO
API_PAD_AX923
API_PAD_W3C
```

#### Return Value

`Byte():` Unpadded data in byte array or *unchanged* data on error.

#### Remarks

An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

---

### <a id="VB_padUnpadHex"></a>padUnpadHex

Removes the padding from a hex-encoded encryption block.

#### Syntax

[VBA]

```

Public Function padUnpadHex ( _
    szInput As String, _
    nBlkLen As Long, _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

szInput

:   Hex-encoded padded data.

nBlkLen

:   Cipher block length in bytes (8 or 16).

nOptions

:   Use 0 for default PKCS5 padding or select one of:

```

API_PAD_1ZERO
API_PAD_AX923
API_PAD_W3C
```

#### Return Value

`String:` Unpadded data in hex-encoded string or *unchanged* data on error.

#### Remarks

An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

---

### <a id="VB_pbeKdf2"></a>pbeKdf2

Derives a key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1.

#### Syntax

[VBA]

```

Public Function pbeKdf2 ( _
    dkBytes As Long, _
    lpPwd() As Byte, _
    lpSalt() As Byte, _
    nCount As Long, _
    nOptions As Long _
) As Byte()

```

#### Parameters

dkBytes

:   Required length of key in bytes.

lpPwd

:   Password encoded as byte array.

lpSalt

:   Salt in a byte array.

nCount

:   Iteration count.

nOptions

:   Hash algorithm to use in HMAC PRF. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
API_HMAC_MD5
```

#### Return Value

`Byte():` Key in byte array.

---

### <a id="VB_pbeKdf2Hex"></a>pbeKdf2Hex

Derives a hex-encoded key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1. The salt and derived key are encoded in hexadecimal.

#### Syntax

[VBA]

```

Public Function pbeKdf2Hex ( _
    dkBytes As Long, _
    szPwd As String, _
    szSaltHex As String, _
    nCount As Long, _
    nOptions As Long _
) As String

```

#### Parameters

dkBytes

:   Required length of key in bytes.

szPwd

:   Password (as normal text).

szSaltHex

:   Salt in hex-encoded format.

nCount

:   Iteration count.

nOptions

:   Hash algorithm to use in HMAC PRF. Select one from:

```

API_HMAC_SHA1
API_HMAC_SHA224
API_HMAC_SHA256
API_HMAC_SHA384
API_HMAC_SHA512
API_HMAC_MD5
```

#### Return Value

`String:` Key in hex format.

---

### <a id="VB_pbeScrypt"></a>pbeScrypt

Derives a key of any length from a password using the SCRYPT algorithm from RFC7914.

#### Syntax

[VBA]

```

Public Function pbeScrypt ( _
    dkBytes As Long, _
    lpPwd() As Byte, _
    lpSalt() As Byte, _
    nParamN As Long, _
    nParamR As Long, _
    nParamP As Long, _
    Optional nOptions As Long = 0 _
) As Byte()

```

#### Parameters

dkBytes

:   Required length of key in bytes.

lpPwd

:   Password encoded as byte array.

lpSalt

:   Salt in a byte array.

nParamN

:   CPU/Memory cost parameter `N` (`"costParameter"`), a number greater than one and a power of 2.

nParamR

:   Block size `r` (`"blockSize"`).

nParamP

:   Parallelization parameter `p` (`"parallelizationParameter"`).

nOptions

:   For future use.

#### Return Value

`Byte():` Key in byte array.

---

### <a id="VB_pbeScryptHex"></a>pbeScryptHex

Derives a hex-encoded key of any length from a password using the SCRYPT algorithm from RFC7914. The salt and derived key are encoded in hexadecimal.

#### Syntax

[VBA]

```

Public Function pbeScryptHex ( _
    dkBytes As Long, _
    szPwd As String, _
    szSaltHex As String, _
    nParamN As Long, _
    nParamR As Long, _
    nParamP As Long, _
    Optional nOptions As Long = 0 _
) As String

```

#### Parameters

dkBytes

:   Required length of key in bytes.

szPwd

:   Password (as normal text).

szSaltHex

:   Salt in hex-encoded format.

nParamN

:   CPU/Memory cost parameter `N` (`"costParameter"`), a number greater than one and a power of 2.

nParamR

:   Block size `r` (`"blockSize"`).

nParamP

:   Parallelization parameter `p` (`"parallelizationParameter"`).

nOptions

:   For future use.

#### Return Value

`String:` Key in hex format.

#### Example

```

Debug.Print pbeScryptHex(64, "password", "4E61436C", 1024, 8, 16)
' FDBABE1C9D3472007856E7190D01E9FE7C6AD7CBC8237830E77376634B3731622EAF30D92E22A3886FF109279D9830DAC727AFB94A83EE6D8360CBDFA2CC0640
```

---

### <a id="VB_prfBytes"></a>prfBytes

Generate output bytes using a pseudorandom function (PRF).

#### Syntax

[VBA]

```

Public Function prfBytes ( _
    nBytes As Long, _
    lpMessage() As Byte, _
    lpKey() As Byte, _
    nOptions As Long, _
    Optional szCustom As String = "" _
) As Byte()

```

#### Parameters

nBytes

:   Required number of output bytes.

lpMessage

:   Input message data.

lpKey

:   Key (expected 128 or 256 bits long).

nOptions

:   PRF function to be used. Select one from:

```

API_KMAC_128
API_KMAC_256
```

szCustom

:   Customization string (optional).

#### Return Value

`Byte():` Output data in byte array.

#### Remarks

The KMAC128 and KMAC256 PRF functions are described in NIST SP800-185 (*SHA-3 Derived Functions*),
and use SHAKE128 and SHAKE256, respectively.
Note different order of parameters from core function.

---

### <a id="VB_rngInitialize"></a>rngInitialize

Initialize the RNG generator using a seed file.

#### Syntax

[VBA]

```

Public Function rngInitialize ( _
    szSeedFile As String _
) As Long

```

#### Parameters

szSeedFile

:   Full path name of seed file. If the seed file does not exist, it will be created using any available entropy.

#### Return Value

`Long:` Zero if successful.

---

### <a id="VB_rngInitializeEx"></a>rngInitializeEx

Query and initialize the RNG generator using Intel(R) DRNG, if available.

#### Syntax

[VBA]

```

Public Function rngInitializeEx ( _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

nOptions

:   Specify `API_RNG_NO_INTEL_DRNG` to explicitly turn off support.

#### Return Value

`Long:` Support status for Intel(R) DRNG. If available, then returns a positive value (1,2,3); else a negative error code.

---

### <a id="VB_rngKeyBytes"></a>rngKeyBytes

Generate a random key value.

#### Syntax

[VBA]

```

Public Function rngKeyBytes ( _
    nBytes As Long, _
    Optional szSeed As String = "" _
) As Byte()

```

#### Parameters

nBytes

:   Required number of random bytes.

szSeed

:   User-supplied entropy in string format (optional).

#### Return Value

`Byte():` Array of random bytes.

---

### <a id="VB_rngKeyHex"></a>rngKeyHex

Generate a random key in hex format.

#### Syntax

[VBA]

```

Public Function rngKeyHex ( _
    nBytes As Long, _
    Optional szSeed As String = "" _
) As String

```

#### Parameters

nBytes

:   Required number of random bytes.

szSeed

:   User-supplied entropy in string format (optional).

#### Return Value

`String:` Random bytes in hex format.

---

### <a id="VB_rngNonce"></a>rngNonce

Generate a random nonce.

#### Syntax

[VBA]

```

Public Function rngNonce ( _
    nBytes As Long _
) As Byte()

```

#### Parameters

nBytes

:   Required number of random bytes.

#### Return Value

`Byte():` Array of random bytes.

---

### <a id="VB_rngNonceHex"></a>rngNonceHex

Generate a hex-encoded sequence of bytes.

#### Syntax

[VBA]

```

Public Function rngNonceHex ( _
    nBytes As Long _
) As String

```

#### Parameters

nBytes

:   Required number of random bytes.

#### Return Value

`String:` Hex-encoded random bytes.

---

### <a id="VB_unpadHexString"></a>unpadHexString

Strips PKCS5 padding from a hex string [DEPRECATED].

#### Syntax

[VBA]

```

Public Function unpadHexString ( _
    strInputHex As String, _
    nBlockLen As Long _
) As String

```

#### Parameters

strInputHex

:   Hexadecimal-encoded padded data.

nBlockLen

:   Cipher block length in bytes (8 or 16).

#### Return Value

`String:` Unpadded data in hex string or *unchanged* data on error.

#### Remarks

An error is indicated by returning the *original* data
which will always be longer than the expected unpadded result.

#### Deprecated

Use [padUnpadHex](#VB_padUnpadHex).

---

### <a id="VB_wipeBytes"></a>wipeBytes

Zeroise data in memory.

#### Syntax

[VBA]

```

Public Function wipeBytes ( _
    lpData() As Byte _
) As Long

```

#### Parameters

lpData

:   Data to be wiped.

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

This function does not free any memory; it just zeroises it.

---

### <a id="VB_wipeFile"></a>wipeFile

Securely wipes and deletes a file using 7-pass DOD standards.

#### Syntax

[VBA]

```

Public Function wipeFile ( _
    szFileName As String, _
    Optional nOptions As Long = 0 _
) As Long

```

#### Parameters

szFileName

:   File to be deleted.

nOptions

:   Option flags. Select one of

```

API_WIPEFILE_DOD7 (0)
API_WIPEFILE_SIMPLE
```

#### Return Value

`Long:` Zero (0) on success, or a nonzero error code (use [apiErrorLookup](#VB_apiErrorLookup) to check).

#### Remarks

The default option uses the 7-pass DOD Standard according to [NISPOM] before deleting.
`API_WIPEFILE_SIMPLE` overwrites the file with a single pass of zero bytes (quicker but less secure).

---

### <a id="VB_wipeString"></a>wipeString

Zeroise a string.

#### Syntax

[VBA]

```

Public Function wipeString ( _
    szData As String _
) As String

```

#### Parameters

szData

:   String to be wiped.

#### Return Value

`String:` An empty string.

#### Remarks

On its own this just zeroizes the string.
To clear the string securely, do the following

```

strData = wipeString(strData)
```

---

### <a id="VB_xofBytes"></a>xofBytes

Generate bytes using an extendable-output function (XOF).

#### Syntax

[VBA]

```

Public Function xofBytes ( _
    nBytes As Long, _
    lpMessage() As Byte, _
    nOptions As Long _
) As Byte()

```

#### Parameters

nBytes

:   Required number of output bytes.

lpMessage

:   Input message data.

nOptions

:   XOF algorithm to be used. Select one from:

```

API_XOF_SHAKE128
API_XOF_SHAKE256
API_XOF_MGF1_SHA1
API_XOF_MGF1_SHA256
API_XOF_MGF1_SHA512
API_XOF_ASCON_XOF
API_XOF_ASCON_XOFA
```

#### Return Value

`Byte():` Output data in byte array.

---

### <a id="VB_zlibDeflate"></a>zlibDeflate

Compress data using the ZLIB deflate algorithm.

#### Syntax

[VBA]

```

Public Function zlibDeflate ( _
    lpInput() As Byte _
) As Byte()

```

#### Parameters

lpInput

:   Data to be compressed.

#### Return Value

`Byte():` Compressed data.

---

### <a id="VB_zlibInflate"></a>zlibInflate

Inflate compressed data using the ZLIB algorithm.

#### Syntax

[VBA]

```

Public Function zlibInflate ( _
    lpInput() As Byte _
) As Byte()

```

#### Parameters

lpInput

:   Compressed data to be inflated.

#### Return Value

`Byte():` Uncompressed data, or an empty array on error.

#### Remarks

An empty array may also be returned in the trivial case where the original data was the empty array itself.

---

[[Contents](#topofpage)] [[Index](#index)]

<a id="cppfunctions"></a>C++ (STL) Functions
--------------------------------------------

See [Using with C++ (STL)](#UsingWithCpp).

* <a id="crsysapi::Aead::DecryptWithTag"></a>[crsysapi::Aead::DecryptWithTag](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_aead.html#af96c2083b84e175688404aa5b6f35a33 "External link") - Decrypt data using specified AEAD algorithm in one-off operation with AAD and options.
* <a id="crsysapi::Aead::EncryptWithTag"></a>[crsysapi::Aead::EncryptWithTag](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_aead.html#a0f1807e4cd20f3aa3e401738dcc39ba2 "External link") - Encrypt data using specified AEAD algorithm in one-off operation with AAD and options.
* <a id="crsysapi::Cipher::Final"></a>[crsysapi::Cipher::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#a9fb8ddb966e48754d13f72a27fed803f "External link") - Clear the Cipher object.
* <a id="crsysapi::Cipher::InitDecrypt"></a>[crsysapi::Cipher::InitDecrypt](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#ab4e4c6e06158886884ec7d27e651de54 "External link") - Initialise the Cipher object ready for repeated incremental decryption operations.
* <a id="crsysapi::Cipher::InitEncrypt"></a>[crsysapi::Cipher::InitEncrypt](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#a09a0220dc782f125dcd710ded8d8ab4e "External link") - Initialise the Cipher object ready for repeated incremental encryption operations.
* <a id="crsysapi::Cipher::Update"></a>[crsysapi::Cipher::Update](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher.html#ab583533e39762d886d59fb9a9c21d5b8 "External link") - Transform byte input data with previously initialized key, mode and direction.
* <a id="crsysapi::CipherStream::Bytes"></a>[crsysapi::CipherStream::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher_stream.html#a540163cc4bebfb5e73994d54f37931a2 "External link") - Enciphers data in array of bytes using specified stream cipher.
* <a id="crsysapi::CipherStream::File"></a>[crsysapi::CipherStream::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cipher_stream.html#abf1c89b187d94adf62478fc23787acd4 "External link") - Enciphers data in a file using specified stream cipher.
* <a id="crsysapi::Cnv::FromBase64"></a>[crsysapi::Cnv::FromBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a91d63843b7242278db2c5154dd64861d "External link") - Decodes a base64-encoded string as an array of bytes.
* <a id="crsysapi::Cnv::FromHex"></a>[crsysapi::Cnv::FromHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#ad46a5b3546d7ee7fd4596dfdad91fc17 "External link") - Decodes a hexadecimal-encoded string as an array of bytes.
* <a id="crsysapi::Cnv::ShortPathName"></a>[crsysapi::Cnv::ShortPathName](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a5d9ddd076ab0a313c968322364974a22 "External link") - Retrieve the Windows short path form of the specified path.
* <a id="crsysapi::Cnv::ToBase64_1"></a>[crsysapi::Cnv::ToBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a7e16727e2e36e4fb9132d3a13ee00b03 "External link") [1/2]  - Encodes an array of bytes as a base64-encoded string.
* <a id="crsysapi::Cnv::ToBase64_2"></a>[crsysapi::Cnv::ToBase64](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#aea585209477576a176a2200c95e40601 "External link") [2/2]  - Encodes a string as a base64-encoded string.
* <a id="crsysapi::Cnv::ToHex_1"></a>[crsysapi::Cnv::ToHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a45776fd3a075f9d035c323c22cdd237c "External link") [1/2]  - Encodes an array of bytes as a hexadecimal-encoded string.
* <a id="crsysapi::Cnv::ToHex_2"></a>[crsysapi::Cnv::ToHex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_cnv.html#a33d0f961ec85ecce19e8f3948460def4 "External link") [2/2]  - Encodes a string as a hexadecimal-encoded string.
* <a id="crsysapi::Crc::Bytes"></a>[crsysapi::Crc::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#a435134cbae3789b8a7fe8177a1e0a955 "External link") - Compute CRC-32 checksum for byte data.
* <a id="crsysapi::Crc::File"></a>[crsysapi::Crc::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#ad00b9be8e20180f9b248d147522d949b "External link") - Compute CRC-32 checksum for a file.
* <a id="crsysapi::Crc::String"></a>[crsysapi::Crc::String](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_crc.html#ad2360320a20354ea3f06f94f7caefc1e "External link") - Compute CRC-32 checksum for a string.
* <a id="crsysapi::Err::ErrorCode"></a>[crsysapi::Err::ErrorCode](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#af3164ad23c9c1002133fdcb7bbf05225 "External link") - Retrieve error code of the error that occurred when calling the last function (if available).
* <a id="crsysapi::Err::ErrorLookup"></a>[crsysapi::Err::ErrorLookup](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#a15d3fd8bc5938342cff4201e82fe032e "External link") - Look up description for error code.
* <a id="crsysapi::Err::FormatErrorMessage"></a>[crsysapi::Err::FormatErrorMessage](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_err.html#af58077604f154b4bf861b458018332d5 "External link") - Return an error message string for the last error.
* <a id="crsysapi::Gen::CompileTime"></a>[crsysapi::Gen::CompileTime](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a9d77fbd3a604f7231dc83909670ac735 "External link") - Get date and time the core native DLL module was last compiled.
* <a id="crsysapi::Gen::LicenceType"></a>[crsysapi::Gen::LicenceType](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a7c09a642f3241754076151a2296b6635 "External link") - Get licence type as a string.
* <a id="crsysapi::Gen::ModuleInfo"></a>[crsysapi::Gen::ModuleInfo](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a1f363d4e6373d5612b247b1df03bd2a3 "External link") - Get additional information about the core DLL module.
* <a id="crsysapi::Gen::ModuleName"></a>[crsysapi::Gen::ModuleName](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#acbeb4e6e67a6f2cda8f193b3c435dd22 "External link") - Get full path name of the current process's core native DLL.
* <a id="crsysapi::Gen::Platform"></a>[crsysapi::Gen::Platform](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#aa4fa152ba3f20d2705a567469e559bad "External link") - Get platform the core native DLL was compiled for.
* <a id="crsysapi::Gen::Version"></a>[crsysapi::Gen::Version](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_gen.html#a8cd280838013e607c24d4b754b9338f6 "External link") - Get version number of the core native DLL as an integer value.
* <a id="crsysapi::Hash::AddData_1"></a>[crsysapi::Hash::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a7ce2fe7f104b3840474b946e164a3afb "External link") [1/2]  - Adds a chunk of data in a byte array to be digested by the Hash object.
* <a id="crsysapi::Hash::AddData_2"></a>[crsysapi::Hash::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a9fb5f9a9936309add9eda61f2e9ae2f5 "External link") [2/2]  - Adds a chunk of data in a string to be digested by the Hash object.
* <a id="crsysapi::Hash::Final"></a>[crsysapi::Hash::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a2e5f4533e2645dc5dd8459ed25885a4f "External link") - Computes final message digest for the Hash object.
* <a id="crsysapi::Hash::Init"></a>[crsysapi::Hash::Init](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_hash.html#a96bd905a5b16dba31732fe104d257492 "External link") - Initialises the Hash object ready for repeated incremental operations.
* <a id="crsysapi::Mac::AddData_1"></a>[crsysapi::Mac::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a2b019edcd6d0826100d8f9145dce951f "External link") [1/2]  - Adds a chunk of data in a byte array to be digested by the Mac object.
* <a id="crsysapi::Mac::AddData_2"></a>[crsysapi::Mac::AddData](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a6fe5fba860d553101ae251c44db3ad84 "External link") [2/2]  - Adds a chunk of data in a string to be digested by the Mac object.
* <a id="crsysapi::Mac::Final"></a>[crsysapi::Mac::Final](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a2f0784f5560451049e9eda267e623da9 "External link") - Computes final MAC value for the Mac object.
* <a id="crsysapi::Mac::Init"></a>[crsysapi::Mac::Init](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_mac.html#a80b29ab03fc8d9c07a20a7838552efa8 "External link") - Initialises the Mac object ready for repeated incremental operations.
* <a id="crsysapi::Pbe::Kdf2"></a>[crsysapi::Pbe::Kdf2](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_pbe.html#a2c385d52c1582a83f5687c23e409f75d "External link") - Derives a key of any length from a password using the PBKDF2 algorithm from PKCS#5 v2.1.
* <a id="crsysapi::Prf::Bytes"></a>[crsysapi::Prf::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_prf.html#a8a68d8282f3b6e098ae465db4b89e4a4 "External link") - Generate output bytes using a pseudorandom function (PRF).
* <a id="crsysapi::Rng::Bytes"></a>[crsysapi::Rng::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a6512dc0fdaddf32ebe4072173bb53627 "External link") - Generate an array of random bytes.
* <a id="crsysapi::Rng::Hex"></a>[crsysapi::Rng::Hex](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a94b854ad70cc6c31ab4ffc9597304ae6 "External link") - Generate an array of n random bytes encoded in hex.
* <a id="crsysapi::Rng::Initialize"></a>[crsysapi::Rng::Initialize](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a11e073fb364369f8dc5dd138c5821b4f "External link") - Initialize the RNG generator using a seed file.
* <a id="crsysapi::Rng::InitializeEx"></a>[crsysapi::Rng::InitializeEx](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a38f1ea8802d5eae55561ee60a13ce32d "External link") - Query and initialize the RNG generator using Intel(R) DRNG, if available.
* <a id="crsysapi::Rng::Number"></a>[crsysapi::Rng::Number](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a9c11b3035208a82a75edbd94e58f26f0 "External link") - Generate a random integer in a given range.
* <a id="crsysapi::Rng::Octet"></a>[crsysapi::Rng::Octet](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a99bc1f305c16cb10dad277e0a8df5548 "External link") - Generate a single random octet (byte)
* <a id="crsysapi::Rng::UpdateSeedFile"></a>[crsysapi::Rng::UpdateSeedFile](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_rng.html#a6ea18a6064720dd4270d18c08ca51776 "External link") - Update the RNG seed file with more entropy.
* <a id="crsysapi::Wipe::Data"></a>[crsysapi::Wipe::Data](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#aa081cd1e059d775c1d5a67e956f766e6 "External link") - Zeroises data in memory.
* <a id="crsysapi::Wipe::File"></a>[crsysapi::Wipe::File](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#a60c4d6caf053d66866704b0989d20eb5 "External link") - Securely wipe and delete a file with options.
* <a id="crsysapi::Wipe::String"></a>[crsysapi::Wipe::String](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_wipe.html#abbc9b94c430c6039c3186cb4af472030 "External link") - Zeroises a string.
* <a id="crsysapi::Xof::Bytes"></a>[crsysapi::Xof::Bytes](https://cryptosys.net/cppapi/html/classcrsysapi_1_1_xof.html#a885aa3379908793503497c119b04107c "External link") - Generate bytes using an extendable-output function (XOF).

[[Contents](#topofpage)] [[Index](#index)]

<a id="activexmethods"></a>ActiveX Classes and Methods
------------------------------------------------------

This table shows all the classes and methods available in the 
CryptoSys API ActiveX wrapper `diCryptOCX.dll`. 
These methods can be called from ASP pages and other COM applications. 
Most functions take their parameters in hexadecimal format.
See [Using with COM/ASP](#UsingWithASP).

Class index:  
[aes128](#x_aes128) |
[blf](#x_blf) |
[conv](#x_conv) |
[crc32](#x_crc32) |
[des](#x_des) |
[gen](#x_gen) |
[hash](#x_hash) |
[mac](#x_mac) |
[md5](#x_md5) |
[pbe](#x_pbe) |
[pc1](#x_pc1) |
[rng](#x_rng) |
[sha1](#x_sha1) |
[sha256](#x_sha256) |
[tdea](#x_tdea)

| Class | Method | Syntax | Returns | Remarks |
| --- | --- | --- | --- | --- |
| <a id="x_aes128"></a><a id="x_tdea"></a><a id="x_des"></a><a id="x_blf"></a> <a id="x_hexmode"></a> **aes128 tdea des blf** | HexMode | `Public Function HexMode(ByVal strInput As String,  ByVal strHexKey As String, ByVal bEncrypt As Boolean,  ByVal strMode As String, ByVal strHexIV As String) As String` | Ciphertext or plaintext in hex format | *strInput, strHexKey, strHexIV* required in hex format. *szInput* must be an exact multiple of the block length in bytes (use `PadHex`). Set *bEncrypt* as `True` to encrypt and `False` to decrypt. Set *szMode* as "`ECB`", "`CBC`", "`CFB`", "`OFB`" or "`CTR`".  Set *szHexIV* as an empty string for ECB mode. |
| <a id="x_padhex"></a> **aes128 tdea des blf** | PadHex | `Public Function PadHex(ByVal strData As String) As String` | Hex data padded according to CMS/PKCS#5/#7. | *szData* required in hex format. |
| <a id="x_unpadhex"></a> **aes128 tdea des blf** | UnpadHex | `Public Function UnpadHex(ByVal strData As String) As String` | Hex data with padding stripped according to CMS/PKCS#5/#7 or untouched data if padding is invalid. | *szData* required in hex format. |
| <a id="x_pc1"></a><a id="x_pc1_encrypthex"></a>**pc1** | EncryptHex | `Public Function EncryptHex(ByVal sInputHex As String, ByVal strHexKey As String) As String` | Encrypted data in hex format. | Input data *szInputHex* and *szHexKey* required in hex format. Both input and key may be of any length greater than zero. |
| <a id="x_hash"></a><a id="x_hash_hexfromfile"></a> **hash** | HexFromFile | `Public Function HexFromFile(ByVal strFileName As String, hashAlgorithm As Long) As String` | Message digest hash in hex format of binary file. | Choose *hashAlgorithm* from properties { `HASH_MD2` | `HASH_MD5` | `HASH_RMD160` | `HASH_SHA1` | `HASH_SHA224` | `HASH_SHA256` | `HASH_SHA384` | `HASH_SHA512` | `HASH_SHA3_224` | `HASH_SHA3_256` | `HASH_SHA3_384` | `HASH_SHA3_512` } |
| <a id="x_hash_hexfromhex"></a> **hash** | HexFromHex | `Public Function HexFromHex(ByVal strHexData As String, hashAlgorithm As Long) As String` | Message digest hash in hex format of hex-encoded input data. |  |
| <a id="x_hash_hexfromstring"></a> **hash** | HexFromString | `Public Function HexFromString(ByVal strData As String, hashAlgorithm As Long) As String` | Message digest hash in hex format of input tex. | *szData* is ordinary ANSI text, not hexadecimal. |
| <a id="x_mac"></a><a id="x_mac_hexfromhex"></a> **mac** | HexFromHex | `Public Function HexFromHex(ByVal strHexData As String, ByVal strHexKey As String, macAlgorithm As Long) As String` | Keyed message authentication code in hex format of hex-encoded data using hex-encoded key. | Choose *macAlgorithm* from properties { `CMAC_AES128` | `CMAC_AES192` | `CMAC_AES256` | `CMAC_TDEA` | `HMAC_MD5` | `HMAC_RMD160` | `HMAC_SHA1` | `HMAC_SHA224` | `HMAC_SHA256` | `HMAC_SHA384` | `HMAC_SHA512` | `HMAC_SHA3_224` | `HMAC_SHA3_256` | `HMAC_SHA3_384` | `HMAC_SHA3_512` } |
| <a id="x_md5"></a><a id="x_sha1"></a><a id="x_sha256"></a> <a id="x_stringhexhash"></a> **md5 sha1 sha256** | StringHexHash | `Public Function StringHexHash(ByVal strData As String) As String` | Hash digest in hex format of input text. | *szData* is ordinary ANSI text, not hexadecimal. |
| <a id="x_hexhexhash"></a> **md5 sha1 sha256** | HexHexHash | `Public Function HexHexHash(ByVal strHexData As String) As String` | Hash digest in hex format of input data also in hex format. | *szHexData* is in hex format. |
| <a id="x_filehexhash"></a> **md5 sha1 sha256** | FileHexHash | `Public Function FileHexHash(ByVal strFileName As String) As String` | Hash digest in hex format of binary data in named file. | CR-LF combinations are treated as two individual bytes. |
| <a id="x_filetexthexhash"></a> **md5 sha1 sha256** | FileTextHexHash | `Public Function FileTextHexHash(ByVal strFileName As String) As String` | Hash digest in hex format of "text" data in named file. | CR-LF combinations are treated as single newline character. |
| <a id="x_hmachex"></a> **md5 sha1 sha256** | HmacHex | `Public Function HmacHex(ByVal strHexText As String, ByVal strHexKey As String) As String` | Keyed hash digest of input text using HMAC algorithm. | Both *szHexText* and *szHexKey* required in hex format. |
| <a id="x_pbe"></a><a id="x_pbe_dkf2fromstring"></a> **pbe** | DKF2FromString | `Public Function DKF2FromString(ByVal nBytes As Long, ByVal strPassword As String, ByVal strSaltHex As String, nCount As Long) As String` | Derived key in hex format using the PBKDF2 algorithm from PKCS #5 with default algorithm `hmacWithSHA1`. | *szPassword* is a plain text string, not hexadecimal, but *szSaltHex* is required in hex format. |
| <a id="x_rng"></a><a id="x_rng_keyhex"></a> **rng** | KeyHex | `Public Function KeyHex(ByVal nBytes As Long) As String` | Returns random number in hex format suitable for a cryptographic key. |  |
| <a id="x_keyhexwithseed"></a> **rng** | KeyHexWithSeed | `Public Function KeyHexWithSeed(ByVal nBytes As Long, ByVal strSeed As String) As String` | Returns random number in hex format suitable for a cryptographic key. | Pass user-defined entropy (seed data) in the string *szSeed*. |
| <a id="x_rng_noncehex"></a> **rng** | NonceHex | `Public Function NonceHex(ByVal nBytes As Long) As String` | Returns a random nonce (number used once) in hex format. |  |
| <a id="x_rng_number"></a> **rng** | Number | `Public Function Number(ByVal nLower As Long, ByVal nUpper As Long) As Long` | Returns a random integer in the range [nLower, nUpper]. |  |
| <a id="x_crc32"></a><a id="x_crc32_filehex"></a> **crc32** | FileHex | `Public Function FileHex(ByVal strFileName As String) As String` | CRC-32 checksum in hex format of binary data in a named file. |  |
| <a id="x_crc32_stringhex"></a> **crc32** | StringHex | `Public Function StringHex(ByVal strData As String) As String` | CRC-32 checksum in hex format of an ANSI string. |  |
| <a id="x_conv"></a><a id="x_conv_stringfrombytes"></a> **conv** | StringFromBytes | `Public Function StringFromBytes(ByVal abData As Variant) As String` | Converts an array of Bytes into an ANSI string. |  |
| <a id="x_conv_bytesfromstring"></a> **conv** | BytesFromString | `Public Function BytesFromString(ByVal str As String) As Variant` | Converts an ANSI string into an array of Bytes. | Returns array as a Variant type. |
| <a id="x_conv_stringfromhex"></a> **conv** | StringFromHex | `Public Function StringFromHex(ByVal strHex As String) As String` | Converts a hex-encoded string into an ANSI string. |  |
| <a id="x_conv_hexfromstring"></a> **conv** | HexFromString | `Public Function HexFromString(ByVal strData As String) As String` | Converts an ANSI string into hex format. |  |
| <a id="x_conv_bytesfromhex"></a> **conv** | BytesFromHex | `Public Function BytesFromHex(ByVal strHex As String) As Variant` | Converts a hex-encoded string into an array of Bytes. | Returns array as a Variant type. |
| <a id="x_conv_hexfrombytes"></a> **conv** | HexFromBytes | `Public Function HexFromBytes(ByVal abData As Variant) As String` | Converts an array of Bytes into a hex-encoded string. |  |
| <a id="x_conv_base64fromstring"></a> **conv** | Base64FromString | `Public Function Base64FromString(ByVal strData As String) As String` | Converts an ANSI string into base64 format. |  |
| <a id="x_conv_stringfrombase64"></a> **conv** | StringFromBase64 | `Public Function StringFromBase64(ByVal strBase64 As String) As String` | Converts a base64-encoded string into an ANSI string. | Only use if you know the all the decoded data are ANSI characters. |
| <a id="x_conv_bytesfrombase64"></a> **conv** | BytesFromBase64 | `Public Function BytesFromBase64(ByVal strBase64 As String) As Variant` | Converts a base64-encoded string into an array of Bytes. | Returns array as a Variant type. |
| <a id="x_conv_base64frombytes"></a> **conv** | Base64FromBytes | `Public Function Base64FromBytes(ByVal abData As Variant) As String` | Converts an array of Bytes into a base64-encoded string. |  |
| <a id="x_conv_hexfrombase64"></a> **conv** | HexFromBase64 | `Public Function BytesFromBase64(ByVal strBase64 As String) As String` | Converts a base64-encoded string directly into a hex-encoded string. |  |
| <a id="x_conv_base64fromhex"></a> **conv** | Base64FromHex | `Public Function Base64FromHex(ByVal strHex As String) As String` | Converts a hex-encoded string directly into a base64-encoded string. |  |
| <a id="x_gen"></a><a id="x_gen_version"></a> **gen** | Version | `Public Function Version() As Long` | Returns the underlying CryptoSys core native DLL version number in the form  Major-version*100*100 + Minor-version*100 + Revision-number. | E.g. version 6.2.1 would return 60201. |
| <a id="x_gen_activexversion"></a> **gen** | ActivexVersion | `Public Function ActivexVersion() As String` | Returns the version number of the ActiveX module. | Returns a string, e.g. "3.1.0". |
| <a id="x_gen_licencetype"></a> **gen** | LicenceType | `Public Function LicenceType() As String` | Returns the CryptoSys API licence type as a String:  	"D" for licensed developer edition or "T" for trial edition. |  |
| <a id="x_gen_compiletime"></a> **gen** | CompileTime | `Public Function CompileTime() As String` | Returns the time and date the underlying CryptoSys Win32 DLL file was compiled. |  |
| <a id="x_gen_modulename"></a> **gen** | ModuleName | `Public Function ModuleName() As String` | Returns the full path name of the underlying CryptoSys Win32 DLL file being used. |  |

[[Contents](#topofpage)] [[Index](#index)]

<a id="dotnetmethods"></a>.NET Classes and Methods
--------------------------------------------------

To program in the .NET languages C# and `VB.NET` (VB200x), use the classes and methods in the
CryptoSys API .NET Class Library `diCrSysAPINet.dll`.

There is a full listing of all the .NET methods at [List of .NET Methods](#methodlist).

For more guidance on programming, see [Using with .NET: C# and `VB.NET`](#UsingWithDotNet).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="xrefdotnet"></a>Cross-reference between Functions and .NET Methods

The following table shows the cross-references between the core ANSI C/VBA functions and the .NET methods.
Plus, where relevant, the equivalent [VBA wrapper function](#vbawrapperfunctions).

| Function | Equivalent .NET Method | VBA Wrapper |
| --- | --- | --- |
| [`AEAD_Encrypt`](#AEAD_Encrypt) | [Aead.Encrypt Method](#M_Aead_Encrypt) |  |
| [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag) | [Aead.EncryptWithTag Method](#M_Aead_EncryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm) [Aead.EncryptWithTag Method](#M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts) | [`aeadEncryptWithTag`](#VB_aeadEncryptWithTag) |
| [`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag) | [Aead.DecryptWithTag Method](#M_Aead_DecryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm) [Aead.DecryptWithTag Method](#M_Aead_DecryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts) | [`aeadDecryptWithTag`](#VB_aeadDecryptWithTag) |
| [`AEAD_Decrypt`](#AEAD_Decrypt) | [Aead.Decrypt Method](#M_Aead_Decrypt) |  |
| [`AEAD_InitKey`](#AEAD_InitKey) | [Aead.InitKey Method](#M_Aead_InitKey) | [`aeadInitKey`](#VB_aeadInitKey) |
| [`AEAD_SetNonce`](#AEAD_SetNonce) | [Aead.SetNonce Method](#M_Aead_SetNonce) | [`aeadSetNonce`](#VB_aeadSetNonce) |
| [`AEAD_AddAAD`](#AEAD_AddAAD) | [Aead.AddAAD Method](#M_Aead_AddAAD) | [`aeadAddAAD`](#VB_aeadAddAAD) |
| [`AEAD_StartEncrypt`](#AEAD_StartEncrypt) | [Aead.StartEncrypt Method](#M_Aead_StartEncrypt) | [`aeadStartEncrypt`](#VB_aeadStartEncrypt) |
| [`AEAD_StartDecrypt`](#AEAD_StartDecrypt) | [Aead.StartDecrypt Method](#M_Aead_StartDecrypt) | [`aeadStartDecrypt`](#VB_aeadStartDecrypt) |
| [`AEAD_Update`](#AEAD_Update) | [Aead.Update Method](#M_Aead_Update) | [`aeadUpdate`](#VB_aeadUpdate) |
| [`AEAD_FinishEncrypt`](#AEAD_FinishEncrypt) | [Aead.FinishEncrypt Method](#M_Aead_FinishEncrypt) | [`aeadFinishEncrypt`](#VB_aeadFinishEncrypt) |
| [`AEAD_FinishDecrypt`](#AEAD_FinishDecrypt) | [Aead.FinishDecrypt Method](#M_Aead_FinishDecrypt) | [`aeadFinishDecrypt`](#VB_aeadFinishDecrypt) |
| [`AEAD_Destroy`](#AEAD_Destroy) | [Aead.Dispose Method](#M_Aead_Dispose) | [`aeadDestroy`](#VB_aeadDestroy) |
| [`AES128_B64Mode`](#AES128_B64Mode) | [Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`AES128_Bytes`](#AES128_Bytes) | [Aes128.Encrypt Method](#M_Aes128_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes128.Decrypt Method](#M_Aes128_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES128_BytesMode`](#AES128_BytesMode) | [Aes128.Encrypt Method](#M_Aes128_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes128.Decrypt Method](#M_Aes128_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES128_File`](#AES128_File) | [Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`AES128_FileExt`](#AES128_FileExt) | [Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`AES128_FileHex`](#AES128_FileHex) | [Aes128.FileEncrypt Method](#M_Aes128_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Aes128.FileDecrypt Method](#M_Aes128_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`AES128_Final`](#AES128_Final) | [Aes128.Dispose Method](#M_Aes128_Dispose) |  |
| [`AES128_Hex`](#AES128_Hex) | [Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeString) (String, String, Mode, String) [Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`AES128_HexMode`](#AES128_HexMode) | [Aes128.Encrypt Method](#M_Aes128_Encrypt_StringStringModeString) (String, String, Mode, String) [Aes128.Decrypt Method](#M_Aes128_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`AES128_Init`](#AES128_Init) | [Aes128.InitEncrypt Method](#M_Aes128_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Aes128.InitDecrypt Method](#M_Aes128_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`AES128_InitError`](#AES128_InitError) | [Aes128.ErrCode Property](#M_Aes128_ErrCodeProperty) |  |
| [`AES128_InitHex`](#AES128_InitHex) | [Aes128.InitEncrypt Method](#M_Aes128_InitEncrypt_StringModeString) (String, Mode, String) [Aes128.InitDecrypt Method](#M_Aes128_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`AES128_Update`](#AES128_Update) | [Aes128.Update Method](#M_Aes128_Update_Byte) (Byte[]) |  |
| [`AES128_UpdateHex`](#AES128_UpdateHex) | [Aes128.Update Method](#M_Aes128_Update_String) (String) |  |
| [`AES192_B64Mode`](#AES192_B64Mode) | [Aes192.Encrypt Method](#M_Aes192_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Aes192.Decrypt Method](#M_Aes192_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`AES192_Bytes`](#AES192_Bytes) | [Aes192.Encrypt Method](#M_Aes192_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes192.Decrypt Method](#M_Aes192_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES192_BytesMode`](#AES192_BytesMode) | [Aes192.Encrypt Method](#M_Aes192_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes192.Decrypt Method](#M_Aes192_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES192_File`](#AES192_File) | [Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`AES192_FileExt`](#AES192_FileExt) | [Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`AES192_FileHex`](#AES192_FileHex) | [Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`AES192_Final`](#AES192_Final) | [Aes192.Dispose Method](#M_Aes192_Dispose) |  |
| [`AES192_Hex`](#AES192_Hex) | [Aes192.FileEncrypt Method](#M_Aes192_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Aes192.FileDecrypt Method](#M_Aes192_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`AES192_HexMode`](#AES192_HexMode) | [Aes192.Encrypt Method](#M_Aes192_Encrypt_StringStringModeString) (String, String, Mode, String) [Aes192.Decrypt Method](#M_Aes192_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`AES192_Init`](#AES192_Init) | [Aes192.InitEncrypt Method](#M_Aes192_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Aes192.InitDecrypt Method](#M_Aes192_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`AES192_InitError`](#AES192_InitError) | [Aes192.ErrCode Property](#M_Aes192_ErrCodeProperty) |  |
| [`AES192_InitHex`](#AES192_InitHex) | [Aes192.InitEncrypt Method](#M_Aes192_InitEncrypt_StringModeString) (String, Mode, String) [Aes192.InitDecrypt Method](#M_Aes192_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`AES192_Update`](#AES192_Update) | [Aes192.Update Method](#M_Aes192_Update_Byte) (Byte[]) |  |
| [`AES192_UpdateHex`](#AES192_UpdateHex) | [Aes192.Update Method](#M_Aes192_Update_String) (String) |  |
| [`AES256_B64Mode`](#AES256_B64Mode) | [Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`AES256_Bytes`](#AES256_Bytes) | [Aes256.Encrypt Method](#M_Aes256_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes256.Decrypt Method](#M_Aes256_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES256_BytesMode`](#AES256_BytesMode) | [Aes256.Encrypt Method](#M_Aes256_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Aes256.Decrypt Method](#M_Aes256_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`AES256_File`](#AES256_File) | [Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`AES256_FileExt`](#AES256_FileExt) | [Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`AES256_FileHex`](#AES256_FileHex) | [Aes256.FileEncrypt Method](#M_Aes256_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Aes256.FileDecrypt Method](#M_Aes256_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`AES256_Final`](#AES256_Final) | [Aes256.Dispose Method](#M_Aes256_Dispose) |  |
| [`AES256_Hex`](#AES256_Hex) | [Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeString) (String, String, Mode, String) [Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`AES256_HexMode`](#AES256_HexMode) | [Aes256.Encrypt Method](#M_Aes256_Encrypt_StringStringModeString) (String, String, Mode, String) [Aes256.Decrypt Method](#M_Aes256_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`AES256_Init`](#AES256_Init) | [Aes256.InitEncrypt Method](#M_Aes256_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Aes256.InitDecrypt Method](#M_Aes256_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`AES256_InitError`](#AES256_InitError) | [Aes256.ErrCode Property](#M_Aes256_ErrCodeProperty) |  |
| [`AES256_InitHex`](#AES256_InitHex) | [Aes256.InitEncrypt Method](#M_Aes256_InitEncrypt_StringModeString) (String, Mode, String) [Aes256.InitDecrypt Method](#M_Aes256_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`AES256_Update`](#AES256_Update) | [Aes256.Update Method](#M_Aes256_Update_Byte) (Byte[]) |  |
| [`AES256_UpdateHex`](#AES256_UpdateHex) | [Aes256.Update Method](#M_Aes256_Update_String) (String) |  |
| [`API_CompileTime`](#API_CompileTime) | [General.CompileTime Method](#M_General_CompileTime) | [`apiCompileTime`](#VB_apiCompileTime) |
| [`API_ErrorCode`](#API_ErrorCode) | [General.ErrorCode Method](#M_General_ErrorCode) [General.FormatErrorMessage Method](#M_General_FormatErrorMessage) | [`apiErrorCode`](#VB_apiErrorCode) [`errFormatErrorMessage`](#VB_errFormatErrorMessage) |
| [`API_ErrorLookup`](#API_ErrorLookup) | [General.ErrorLookup Method](#M_General_ErrorLookup) [General.FormatErrorMessage Method](#M_General_FormatErrorMessage) | [`apiErrorLookup`](#VB_apiErrorLookup) [`errFormatErrorMessage`](#VB_errFormatErrorMessage) |
| [`API_LicenceType`](#API_LicenceType) | [General.LicenceType Method](#M_General_LicenceType) | [`apiLicenceType`](#VB_apiLicenceType) |
| [`API_ModuleInfo`](#API_ModuleInfo) | [General.ModuleInfo Method](#M_General_ModuleInfo) | [`apiModuleInfo`](#VB_apiModuleInfo) |
| [`API_ModuleName`](#API_ModuleName) | [General.ModuleName Method](#M_General_ModuleName) | [`apiModuleName`](#VB_apiModuleName) |
| [`API_Platform`](#API_Platform) | [General.Platform Method](#M_General_Platform) | [`apiPlatform`](#VB_apiPlatform) |
| [`API_PowerUpTests`](#API_PowerUpTests) | [General.PowerUpTests Method](#M_General_PowerUpTests) |  |
| [`API_Version`](#API_Version) | [General.Version Method](#M_General_Version) | [`apiVersion`](#VB_apiVersion) |
| [`BLF_B64Mode`](#BLF_B64Mode) | [Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`BLF_Bytes`](#BLF_Bytes) | [Blowfish.Encrypt Method](#M_Blowfish_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Blowfish.Decrypt Method](#M_Blowfish_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`BLF_BytesMode`](#BLF_BytesMode) | [Blowfish.Encrypt Method](#M_Blowfish_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Blowfish.Decrypt Method](#M_Blowfish_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) | [`blfBytesBlock`](#VB_blfBytesBlock) |
| [`BLF_File`](#BLF_File) | [Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`BLF_FileExt`](#BLF_FileExt) | [Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`BLF_FileHex`](#BLF_FileHex) | [Blowfish.FileEncrypt Method](#M_Blowfish_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Blowfish.FileDecrypt Method](#M_Blowfish_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`BLF_Final`](#BLF_Final) | [Blowfish.Dispose Method](#M_Blowfish_Dispose) |  |
| [`BLF_Hex`](#BLF_Hex) | [Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeString) (String, String, Mode, String) [Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`BLF_HexMode`](#BLF_HexMode) | [Blowfish.Encrypt Method](#M_Blowfish_Encrypt_StringStringModeString) (String, String, Mode, String) [Blowfish.Decrypt Method](#M_Blowfish_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`BLF_Init`](#BLF_Init) | [Blowfish.InitEncrypt Method](#M_Blowfish_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Blowfish.InitDecrypt Method](#M_Blowfish_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`BLF_InitError`](#BLF_InitError) | [Blowfish.ErrCode Property](#M_Blowfish_ErrCodeProperty) |  |
| [`BLF_InitHex`](#BLF_InitHex) | [Blowfish.InitEncrypt Method](#M_Blowfish_InitEncrypt_StringModeString) (String, Mode, String) [Blowfish.InitDecrypt Method](#M_Blowfish_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`BLF_Update`](#BLF_Update) | [Blowfish.Update Method](#M_Blowfish_Update_Byte) (Byte[]) |  |
| [`BLF_UpdateHex`](#BLF_UpdateHex) | [Blowfish.Update Method](#M_Blowfish_Update_String) (String) |  |
| [`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes) | [Cipher.Decrypt Method](#M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts) | [`cipherDecryptBytes`](#VB_cipherDecryptBytes) |
| [`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes) | [Cipher.Encrypt Method](#M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts) | [`cipherEncryptBytes`](#VB_cipherEncryptBytes) |
| [`CIPHER_DecryptHex`](#CIPHER_DecryptHex) | [Cipher.Decrypt Method](#M_Cipher_Decrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts) | [`cipherDecryptHex`](#VB_cipherDecryptHex) |
| [`CIPHER_EncryptHex`](#CIPHER_EncryptHex) | [Cipher.Encrypt Method](#M_Cipher_Encrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts) | [`cipherEncryptHex`](#VB_cipherEncryptHex) |
| [`CIPHER_FileDecrypt`](#CIPHER_FileDecrypt) | [Cipher.FileDecrypt Method](#M_Cipher_FileDecrypt) | [`cipherFileDecrypt`](#VB_cipherFileDecrypt) |
| [`CIPHER_FileEncrypt`](#CIPHER_FileEncrypt) | [Cipher.FileEncrypt Method](#M_Cipher_FileEncrypt) | [`cipherFileEncrypt`](#VB_cipherFileEncrypt) |
| [`CIPHER_Init`](#CIPHER_Init) | [Cipher.InitEncrypt Method](#M_Cipher_InitEncrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode) [Cipher.InitDecrypt Method](#M_Cipher_InitDecrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode) | [`cipherInit`](#VB_cipherInit) |
| [`CIPHER_InitHex`](#CIPHER_InitHex) | [Cipher.InitEncrypt Method](#M_Cipher_InitEncrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode) [Cipher.InitDecrypt Method](#M_Cipher_InitDecrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode) | [`cipherInitHex`](#VB_cipherInitHex) |
| [`CIPHER_Update`](#CIPHER_Update) | [Cipher.Update Method](#M_Cipher_Update_Byte) (Byte[]) | [`cipherUpdate`](#VB_cipherUpdate) |
| [`CIPHER_UpdateHex`](#CIPHER_UpdateHex) | [Cipher.Update Method](#M_Cipher_Update_String) (String) | [`cipherUpdateHex`](#VB_cipherUpdateHex) |
| [`CIPHER_Final`](#CIPHER_Final) | [Cipher.Dispose Method](#M_Cipher_Dispose) | [`cipherFinal`](#VB_cipherFinal) |
| [`CIPHER_KeyWrap`](#CIPHER_KeyWrap) | [Cipher.KeyWrap Method](#M_Cipher_KeyWrap) | [`cipherKeyWrap`](#VB_cipherKeyWrap) |
| [`CIPHER_KeyUnwrap`](#CIPHER_KeyUnwrap) | [Cipher.KeyUnwrap Method](#M_Cipher_KeyUnwrap) | [`cipherKeyUnwrap`](#VB_cipherKeyUnwrap) |
| [`CIPHER_StreamBytes`](#CIPHER_StreamBytes) | [CipherStream.Bytes Method](#M_CipherStream_Bytes) | [`cipherStreamBytes`](#VB_cipherStreamBytes) |
| [`CIPHER_StreamFile`](#CIPHER_StreamFile) | [CipherStream.File Method](#M_CipherStream_File) | [`cipherStreamFile`](#VB_cipherStreamFile) |
| [`CIPHER_StreamFinal`](#CIPHER_StreamFinal) | [CipherStream.Dispose Method](#M_CipherStream_Dispose) | [`cipherStreamFinal`](#VB_cipherStreamFinal) |
| [`CIPHER_StreamHex`](#CIPHER_StreamHex) | [CipherStream.Hex Method](#M_CipherStream_Hex) | [`cipherStreamHex`](#VB_cipherStreamHex) |
| [`CIPHER_StreamInit`](#CIPHER_StreamInit) | [CipherStream.Init Method](#M_CipherStream_Init) | [`cipherStreamInit`](#VB_cipherStreamInit) |
| [`CIPHER_StreamUpdate`](#CIPHER_StreamUpdate) | [CipherStream.Update Method](#M_CipherStream_Update) | [`cipherStreamUpdate`](#VB_cipherStreamUpdate) |
| [`CNV_B64Filter`](#CNV_B64Filter) | [Cnv.Base64Filter Method](#M_Cnv_Base64Filter) | [`cnvB64Filter`](#VB_cnvB64Filter) |
| [`CNV_B64StrFromBytes`](#CNV_B64StrFromBytes) | [Cnv.ToBase64 Method](#M_Cnv_ToBase64_Byte) (Byte[]) | [`cnvToBase64`](#VB_cnvToBase64) |
| [`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str) | [Cnv.FromBase64 Method](#M_Cnv_FromBase64) | [`cnvFromBase64`](#VB_cnvFromBase64) |
| [`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr) | [Cnv.FromHex Method](#M_Cnv_FromHex) | [`cnvFromHex`](#VB_cnvFromHex) |
| [`CNV_HexFilter`](#CNV_HexFilter) | [Cnv.HexFilter Method](#M_Cnv_HexFilter) | [`cnvHexFilter`](#VB_cnvHexFilter) |
| [`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes) | [Cnv.ToHex Method](#M_Cnv_ToHex_Byte) (Byte[]) | [`cnvToHex`](#VB_cnvToHex) |
| [`CNV_ShortPathName`](#CNV_ShortPathName) | [Cnv.ShortPathName Method](#M_Cnv_ShortPathName) |  |
| [`COMPR_Compress`](#COMPR_Compress) | [Compr.Compress Method](#M_Compr_Compress) | [`comprCompress`](#VB_comprCompress) |
| [`COMPR_Uncompress`](#COMPR_Uncompress) | [Compr.Uncompress Method](#M_Compr_Uncompress) | [`comprUncompress`](#VB_comprUncompress) |
| [`CRC_Bytes`](#CRC_Bytes) | [Crc.Data Method](#M_Crc_Data_Byte) (Byte[]) | [`crcBytes`](#VB_crcBytes) |
| [`CRC_File`](#CRC_File) | [Crc.File Method](#M_Crc_File) | [`crcFile`](#VB_crcFile) |
| [`CRC_String`](#CRC_String) | [Crc.Data Method](#M_Crc_Data_String) (String) | [`crcString`](#VB_crcString) |
| [`DES_B64Mode`](#DES_B64Mode) | [Des.Encrypt Method](#M_Des_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Des.Decrypt Method](#M_Des_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`DES_Bytes`](#DES_Bytes) | [Des.Encrypt Method](#M_Des_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Des.Decrypt Method](#M_Des_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`DES_BytesMode`](#DES_BytesMode) | [Des.Encrypt Method](#M_Des_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Des.Decrypt Method](#M_Des_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`DES_CheckKey`](#DES_CheckKey) | [Des.CheckKey Method (Byte[])](#M_Des_CheckKey_Byte) [Tdea.CheckKey Method (Byte[])](#M_Tdea_CheckKey_Byte) |  |
| [`DES_CheckKeyHex`](#DES_CheckKeyHex) | [Des.CheckKey Method (String)](#M_Des_CheckKey_String) [Tdea.CheckKey Method (String)](#M_Tdea_CheckKey_String) |  |
| [`DES_File`](#DES_File) | [Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`DES_FileExt`](#DES_FileExt) | [Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`DES_FileHex`](#DES_FileHex) | [Des.FileEncrypt Method](#M_Des_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Des.FileDecrypt Method](#M_Des_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`DES_Final`](#DES_Final) | [Des.Dispose Method](#M_Des_Dispose) |  |
| [`DES_Hex`](#DES_Hex) | [Des.Encrypt Method](#M_Des_Encrypt_StringStringModeString) (String, String, Mode, String) [Des.Decrypt Method](#M_Des_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`DES_HexMode`](#DES_HexMode) | [Des.Encrypt Method](#M_Des_Encrypt_StringStringModeString) (String, String, Mode, String) [Des.Decrypt Method](#M_Des_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`DES_Init`](#DES_Init) | [Des.InitEncrypt Method](#M_Des_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Des.InitDecrypt Method](#M_Des_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`DES_InitError`](#DES_InitError) | [Des.ErrCode Property](#M_Des_ErrCodeProperty) |  |
| [`DES_InitHex`](#DES_InitHex) | [Des.InitEncrypt Method](#M_Des_InitEncrypt_StringModeString) (String, Mode, String) [Des.InitDecrypt Method](#M_Des_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`DES_Update`](#DES_Update) | [Des.Update Method](#M_Des_Update_Byte) (Byte[]) |  |
| [`DES_UpdateHex`](#DES_UpdateHex) | [Des.Update Method](#M_Des_Update_String) (String) |  |
| [`GCM_Decrypt`](#GCM_Decrypt) | [Gcm.Decrypt Method](#M_Gcm_Decrypt) - @superseded |  |
| [`GCM_Encrypt`](#GCM_Encrypt) | [Gcm.Encrypt Method](#M_Gcm_Encrypt) - @superseded |  |
| [`GCM_FinishKey`](#GCM_FinishKey) | [Gcm.Dispose Method](#M_Gcm_Dispose) - @superseded |  |
| [`GCM_InitKey`](#GCM_InitKey) | [Gcm.InitKey Method](#M_Gcm_InitKey) - @superseded |  |
| [`GCM_NextDecrypt`](#GCM_NextDecrypt) | [Gcm.NextDecrypt Method](#M_Gcm_NextDecrypt) - @superseded |  |
| [`GCM_NextEncrypt`](#GCM_NextEncrypt) | [Gcm.NextEncrypt Method](#M_Gcm_NextEncrypt) - @superseded |  |
| [`HASH_Bytes`](#HASH_Bytes) | [Hash.BytesFromBytes Method](#M_Hash_BytesFromBytes) | [`hashBytes`](#VB_hashBytes) |
| [`HASH_File`](#HASH_File) | [Hash.BytesFromFile Method](#M_Hash_BytesFromFile) | [`hashFile`](#VB_hashFile) |
| [`HASH_HexFromBits`](#HASH_HexFromBits) | [Hash.HexFromBits Method](#M_Hash_HexFromBits) | [`hashHexFromBits`](#VB_hashHexFromBits) |
| [`HASH_HexFromBytes`](#HASH_HexFromBytes) | [Hash.HexFromBytes Method](#M_Hash_HexFromBytes) [Hash.HexFromString Method](#M_Hash_HexFromString) | [`hashHexFromBytes`](#VB_hashHexFromBytes) [`hashHexFromString`](#VB_hashHexFromString) |
| [`HASH_HexFromFile`](#HASH_HexFromFile) | [Hash.HexFromFile Method](#M_Hash_HexFromFile) | [`hashHexFromFile`](#VB_hashHexFromFile) |
| [`HASH_HexFromHex`](#HASH_HexFromHex) | [Hash.HexFromHex Method](#M_Hash_HexFromHex) | [`hashHexFromHex`](#VB_hashHexFromHex) |
| [`HASH_Length`](#HASH_Length) | [Hash.LengthInBytes Method](#M_Hash_LengthInBytes) | [`hashLength`](#VB_hashLength) |
| [`HASH_Init`](#HASH_Init) | [Hash.Init Method](#M_Hash_Init) | [`hashInit`](#VB_hashInit) |
| [`HASH_AddBytes`](#HASH_AddBytes) | [Hash.AddData Method](#M_Hash_AddData_Byte) (Byte[]) [Hash.AddData Method](#M_Hash_AddData_String) (String) | [`hashAddBytes`](#VB_hashAddBytes) [`hashAddString`](#VB_hashAddString) |
| [`HASH_Final`](#HASH_Final) | [Hash.Final Method](#M_Hash_Final) | [`hashFinal`](#VB_hashFinal) |
| [`HASH_Reset`](#HASH_Reset) | [Hash.Reset Method](#M_Hash_Reset) |  |
| [`HASH_DigestLength`](#HASH_DigestLength) | [Hash.LengthInBytes Method](#M_Hash_LengthInBytes) |  |
| [`MAC_Bytes`](#MAC_Bytes) | [Mac.BytesFromBytes Method](#M_Mac_BytesFromBytes) | [`macBytes`](#VB_macBytes) |
| [`MAC_HexFromBytes`](#MAC_HexFromBytes) | [Mac.HexFromBytes Method](#M_Mac_HexFromBytes) | [`macHexFromBytes`](#VB_macHexFromBytes) |
| [`MAC_HexFromHex`](#MAC_HexFromHex) | [Mac.HexFromHex Method](#M_Mac_HexFromHex) | [`macHexFromHex`](#VB_macHexFromHex) |
| [`MAC_Init`](#MAC_Init) | [Mac.Init Method](#M_Mac_Init) | [`macInit`](#VB_macInit) |
| [`MAC_AddBytes`](#MAC_AddBytes) | [Mac.AddData Method](#M_Mac_AddData_Byte) (Byte[]) [Mac.AddData Method](#M_Mac_AddData_String) (String) | [`macAddBytes`](#VB_macAddBytes) [`macAddString`](#VB_macAddString) |
| [`MAC_Final`](#MAC_Final) | [Mac.Final Method](#M_Mac_Final) | [`macFinal`](#VB_macFinal) |
| [`MAC_Reset`](#MAC_Reset) | [Mac.Reset Method](#M_Mac_Reset) |  |
| [`MAC_CodeLength`](#MAC_CodeLength) | *(no equivalent in .NET)* |  |
| [`MD5_AddBytes`](#MD5_AddBytes) | [Md5.AddData Method](#M_Md5_AddData_Byte) (Byte[]) |  |
| [`MD5_AddString`](#MD5_AddString) | [Md5.AddData Method](#M_Md5_AddData_String) (String) |  |
| [`MD5_BytesHash`](#MD5_BytesHash) | [Md5.BytesHash Method](#M_Md5_BytesHash) |  |
| [`MD5_BytesHexHash`](#MD5_BytesHexHash) | [Md5.HexHash Method](#M_Md5_HexHash_Byte) (Byte[]) |  |
| [`MD5_FileHexHash`](#MD5_FileHexHash) | [Md5.FileHexHash Method](#M_Md5_FileHexHash) [Md5.FileTextHexHash Method](#M_Md5_FileTextHexHash) |  |
| [`MD5_HexDigest`](#MD5_HexDigest) | [Md5.HexDigest Method](#M_Md5_HexDigest) |  |
| [`MD5_Hmac`](#MD5_Hmac) | [Md5.Hmac Method](#M_Md5_Hmac_ByteByte) (Byte[], Byte[]) |  |
| [`MD5_HmacHex`](#MD5_HmacHex) | [Md5.Hmac Method](#M_Md5_Hmac_StringString) (String, String) |  |
| [`MD5_Init`](#MD5_Init) | [Md5.Init Method](#M_Md5_Init) |  |
| [`MD5_Reset`](#MD5_Reset) | [Md5.Reset Method](#M_Md5_Reset) |  |
| [`MD5_StringHexHash`](#MD5_StringHexHash) | [Md5.HexHash Method](#M_Md5_HexHash_String) (String) |  |
| [`PAD_BytesBlock`](#PAD_BytesBlock) | [Cipher.Pad Method](#M_Cipher_Pad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding) | [`padBytesBlock`](#VB_padBytesBlock) |
| [`PAD_HexBlock`](#PAD_HexBlock) | [Cipher.Pad Method](#M_Cipher_Pad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding) | [`padHexBlock`](#VB_padHexBlock) |
| [`PAD_UnpadBytes`](#PAD_UnpadBytes) | [Cipher.Unpad Method](#M_Cipher_Unpad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding) | [`padUnpadBytes`](#VB_padUnpadBytes) |
| [`PAD_UnpadHex`](#PAD_UnpadHex) | [Cipher.Unpad Method](#M_Cipher_Unpad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding) | [`padUnpadHex`](#VB_padUnpadHex) |
| [`PBE_Kdf2`](#PBE_Kdf2) | [Pbe.Kdf2 Method](#M_Pbe_Kdf2_Int32ByteByteInt32HashAlgorithm) (Int32, Byte[], Byte[], Int32, HashAlgorithm) | [`pbeKdf2`](#VB_pbeKdf2) |
| [`PBE_Kdf2Hex`](#PBE_Kdf2Hex) | [Pbe.Kdf2 Method](#M_Pbe_Kdf2_Int32StringStringInt32HashAlgorithm) (Int32, String, String, Int32, HashAlgorithm) | [`pbeKdf2Hex`](#VB_pbeKdf2Hex) |
| [`PBE_Scrypt`](#PBE_Scrypt) | [Pbe.Scrypt Method](#M_Pbe_Scrypt_Int32ByteByteInt32Int32Int32) | [`pbeScrypt`](#VB_pbeScrypt) |
| [`PBE_ScryptHex`](#PBE_ScryptHex) | [Pbe.Scrypt Method](#M_Pbe_Scrypt_Int32StringStringInt32Int32Int32) | [`pbeScryptHex`](#VB_pbeScryptHex) |
| [`PC1_Bytes`](#PC1_Bytes) | [Pc1.Encrypt Method](#M_Pc1_Encrypt_ByteByte) (Byte[], Byte[]) |  |
| [`PC1_File`](#PC1_File) | [Pc1.File Method](#M_Pc1_File) |  |
| [`PC1_Hex`](#PC1_Hex) | [Pc1.Encrypt Method](#M_Pc1_Encrypt_StringString) (String, String) |  |
| [`PRF_Bytes`](#PRF_Bytes) | [Prf.Bytes Method](#M_Prf_Bytes) | [`prfBytes`](#VB_prfBytes) |
| [`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt) | [Rng.BytesWithPrompt Method](#M_Rng_BytesWithPrompt_Int32Rng_Strength) (Int32, Rng.Strength) [Rng.BytesWithPrompt Method](#M_Rng_BytesWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength) |  |
| [`RNG_HexWithPrompt`](#RNG_HexWithPrompt) | [Rng.HexWithPrompt Method](#M_Rng_HexWithPrompt_Int32) (Int32) [Rng.HexWithPrompt Method](#M_Rng_HexWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength) |  |
| [`RNG_Initialize`](#RNG_Initialize) | [Rng.Initialize Method](#M_Rng_Initialize) [Rng.InitializeEx Method](#M_Rng_InitializeEx) | `[rngInitialize](#VB_rngInitialize)` `[rngInitializeEx](#VB_rngInitializeEx)` |
| [`RNG_KeyBytes`](#RNG_KeyBytes) | [Rng.KeyBytes Method](#M_Rng_KeyBytes_Int32String) (Int32, String) [Rng.KeyBytes Method](#M_Rng_KeyBytes_Int32Byte) (Int32, Byte[]) | [`rngKeyBytes`](#VB_rngKeyBytes) |
| [`RNG_KeyHex`](#RNG_KeyHex) | [Rng.KeyHex Method](#M_Rng_KeyHex_Int32String) (Int32, String) [Rng.KeyHex Method](#M_Rng_KeyHex_Int32Byte) (Int32, Byte[]) | [`rngKeyHex`](#VB_rngKeyHex) |
| [`RNG_MakeSeedFile`](#RNG_MakeSeedFile) | [Rng.MakeSeedFile Method](#M_Rng_MakeSeedFile_StringRng_Strength) (String, Rng.Strength) [Rng.MakeSeedFile Method](#M_Rng_MakeSeedFile_StringStringRng_Strength) (String, String, Rng.Strength) |  |
| [`RNG_NonceData`](#RNG_NonceData) | [Rng.NonceBytes Method](#M_Rng_NonceBytes) | [`rngNonce`](#VB_rngNonce) |
| [`RNG_NonceDataHex`](#RNG_NonceDataHex) | [Rng.NonceHex Method](#M_Rng_NonceHex) | [`rngNonceHex`](#VB_rngNonceHex) |
| [`RNG_Number`](#RNG_Number) | [Rng.Number Method](#M_Rng_Number) |  |
| [`RNG_Test`](#RNG_Test) | [Rng.Test Method](#M_Rng_Test) |  |
| [`RNG_TestDRBGVS`](#RNG_TestDRBGVS) | [Rng.TestDrbgvs Method](#M_Rng_TestDrbgvs) |  |
| [`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile) | [Rng.UpdateSeedFile Method](#M_Rng_UpdateSeedFile) |  |
| [`SHA1_AddBytes`](#SHA1_AddBytes) | [Sha1.AddData Method](#M_Sha1_AddData_Byte) (Byte[]) |  |
| [`SHA1_AddString`](#SHA1_AddString) | [Sha1.AddData Method](#M_Sha1_AddData_String) (String) |  |
| [`SHA1_BytesHash`](#SHA1_BytesHash) | [Sha1.BytesHash Method](#M_Sha1_BytesHash) |  |
| [`SHA1_BytesHexHash`](#SHA1_BytesHexHash) | [Sha1.HexHash Method](#M_Sha1_HexHash_Byte) (Byte[]) |  |
| [`SHA1_FileHexHash`](#SHA1_FileHexHash) | [Sha1.FileHexHash Method](#M_Sha1_FileHexHash) [Sha1.FileTextHexHash Method](#M_Sha1_FileTextHexHash) |  |
| [`SHA1_HexDigest`](#SHA1_HexDigest) | [Sha1.HexDigest Method](#M_Sha1_HexDigest) |  |
| [`SHA1_Hmac`](#SHA1_Hmac) | [Sha1.Hmac Method](#M_Sha1_Hmac_ByteByte) (Byte[], Byte[]) |  |
| [`SHA1_HmacHex`](#SHA1_HmacHex) | [Sha1.Hmac Method](#M_Sha1_Hmac_StringString) (String, String) |  |
| [`SHA1_Init`](#SHA1_Init) | [Sha1.Init Method](#M_Sha1_Init) |  |
| [`SHA1_Reset`](#SHA1_Reset) | [Sha1.Reset Method](#M_Sha1_Reset) |  |
| [`SHA1_StringHexHash`](#SHA1_StringHexHash) | [Sha1.HexHash Method](#M_Sha1_HexHash_String) (String) |  |
| [`SHA2_AddBytes`](#SHA2_AddBytes) | [Sha256.AddData Method](#M_Sha256_AddData_Byte) (Byte[]) |  |
| [`SHA2_AddString`](#SHA2_AddString) | [Sha256.AddData Method](#M_Sha256_AddData_String) (String) |  |
| [`SHA2_BytesHash`](#SHA2_BytesHash) | [Sha256.BytesHash Method](#M_Sha256_BytesHash) |  |
| [`SHA2_BytesHexHash`](#SHA2_BytesHexHash) | [Sha256.HexHash Method](#M_Sha256_HexHash_Byte) (Byte[]) |  |
| [`SHA2_FileHexHash`](#SHA2_FileHexHash) | [Sha256.FileHexHash Method](#M_Sha256_FileHexHash) [Sha256.FileTextHexHash Method](#M_Sha256_FileTextHexHash) |  |
| [`SHA2_HexDigest`](#SHA2_HexDigest) | [Sha256.HexDigest Method](#M_Sha256_HexDigest) |  |
| [`SHA2_Hmac`](#SHA2_Hmac) | [Sha256.Hmac Method](#M_Sha256_Hmac_ByteByte) (Byte[], Byte[]) |  |
| [`SHA2_HmacHex`](#SHA2_HmacHex) | [Sha256.Hmac Method](#M_Sha256_Hmac_StringString) (String, String) |  |
| [`SHA2_Init`](#SHA2_Init) | [Sha256.Init Method](#M_Sha256_Init) |  |
| [`SHA2_Reset`](#SHA2_Reset) | [Sha256.Reset Method](#M_Sha256_Reset) |  |
| [`SHA3_AddBytes`](#SHA3_AddBytes) | [Sha3.AddData Method](#M_Sha3_AddData_Byte) (Byte[]) |  |
| [`SHA3_AddString`](#SHA3_AddString) | [Sha3.AddData Method](#M_Sha3_AddData_String) (String) |  |
| [`SHA3_HexDigest`](#SHA3_HexDigest) | [Sha3.HexDigest Method](#M_Sha3_HexDigest) |  |
| [`SHA3_Init`](#SHA3_Init) | [Sha3.Init Method](#M_Sha3_Init) |  |
| [`SHA3_LengthInBytes`](#SHA3_LengthInBytes) | [Sha3.LengthInBytes Property](#M_Sha3_LengthInBytesProperty) |  |
| [`SHA3_Reset`](#SHA3_Reset) | [Sha3.Reset Method](#M_Sha3_Reset) |  |
| [`TDEA_B64Mode`](#TDEA_B64Mode) | [Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) [Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase) |  |
| [`TDEA_Bytes`](#TDEA_Bytes) | [Tdea.Encrypt Method](#M_Tdea_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Tdea.Decrypt Method](#M_Tdea_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`TDEA_BytesMode`](#TDEA_BytesMode) | [Tdea.Encrypt Method](#M_Tdea_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) [Tdea.Decrypt Method](#M_Tdea_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[]) |  |
| [`TDEA_File`](#TDEA_File) | [Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) [Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[]) |  |
| [`TDEA_FileExt`](#TDEA_FileExt) | [Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) [Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption) |  |
| [`TDEA_FileHex`](#TDEA_FileHex) | [Tdea.FileEncrypt Method](#M_Tdea_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String) [Tdea.FileDecrypt Method](#M_Tdea_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String) |  |
| [`TDEA_Final`](#TDEA_Final) | [Tdea.Dispose Method](#M_Tdea_Dispose) |  |
| [`TDEA_Hex`](#TDEA_Hex) | [Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeString) (String, String, Mode, String) [Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`TDEA_HexMode`](#TDEA_HexMode) | [Tdea.Encrypt Method](#M_Tdea_Encrypt_StringStringModeString) (String, String, Mode, String) [Tdea.Decrypt Method](#M_Tdea_Decrypt_StringStringModeString) (String, String, Mode, String) |  |
| [`TDEA_Init`](#TDEA_Init) | [Tdea.InitEncrypt Method](#M_Tdea_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[]) [Tdea.InitDecrypt Method](#M_Tdea_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[]) |  |
| [`TDEA_InitError`](#TDEA_InitError) | [Tdea.ErrCode Property](#M_Tdea_ErrCodeProperty) |  |
| [`TDEA_InitHex`](#TDEA_InitHex) | [Tdea.InitEncrypt Method](#M_Tdea_InitEncrypt_StringModeString) (String, Mode, String) [Tdea.InitDecrypt Method](#M_Tdea_InitDecrypt_StringModeString) (String, Mode, String) |  |
| [`TDEA_Update`](#TDEA_Update) | [Tdea.Update Method](#M_Tdea_Update_Byte) (Byte[]) |  |
| [`TDEA_UpdateHex`](#TDEA_UpdateHex) | [Tdea.Update Method](#M_Tdea_Update_String) (String) |  |
| [`WIPE_Data`](#WIPE_Data) | [Wipe.Data Method](#M_Wipe_Data) [Wipe.String Method](#M_Wipe_String) | [`wipeBytes`](#VB_wipeBytes) [`wipeString`](#VB_wipeString) |
| [`WIPE_File`](#WIPE_File) | [Wipe.File Method](#M_Wipe_File) | [`wipeFile`](#VB_wipeFile) |
| [`XOF_Bytes`](#XOF_Bytes) | [Xof.Bytes Method](#M_Xof_Bytes) | [`xofBytes`](#VB_xofBytes) |
| [`ZLIB_Deflate`](#ZLIB_Deflate) | [Zlib.Deflate Method](#M_Zlib_Deflate) | [`zlibDeflate`](#VB_zlibDeflate) |
| [`ZLIB_Inflate`](#ZLIB_Inflate) | [Zlib.Inflate Method](#M_Zlib_Inflate_Byte) (Byte[]) [Zlib.Inflate Method](#M_Zlib_Inflate_ByteInt32) (Byte[], Int32) | [`zlibInflate`](#VB_zlibInflate) |

[[Contents](#topofpage)] [[Index](#index)]

### <a id="dotnethelp"></a>.NET Help File

The .NET classes and methods have different parameters and return values to the VBA/C functions
described above in this manual. 
See the [Summary of .NET Classes](#dotnetsummary) below and also
the separate help file `CryptoSysAPI.chm`.

[[Contents](#topofpage)] [[Index](#index)]

<a id="dotnetsummary"></a>Summary of .NET Classes
-------------------------------------------------

This manual now includes the complete information from the .NET Help File plus cross-references to the equivalent
VB6/C functions and examples in `VB.NET`.
For a summary showing the VB6/C equivalent functions for these .NET methods, see 
[Cross-reference between Functions and .NET Methods](#xrefdotnet).

---

Class index:   
[Aead](#mx_Aead) |
[Aes128](#mx_Aes128) |
[Aes192](#mx_Aes192) |
[Aes256](#mx_Aes256) |
[Blowfish](#mx_Blowfish) |
[Cipher](#mx_Cipher) |
[CipherStream](#mx_CipherStream) |
[Cnv](#mx_Cnv) |
[Compr](#mx_Compr) |
[Crc](#mx_Crc) |
[Des](#mx_Des) |
[Gcm](#mx_Gcm) |
[General](#mx_General) |
[Hash](#mx_Hash) |
[Mac](#mx_Mac) |
[Md5](#mx_Md5) |
[Pbe](#mx_Pbe) |
[Pc1](#mx_Pc1) |
[Prf](#mx_Prf) |
[Rng](#mx_Rng) |
[Sha1](#mx_Sha1) |
[Sha256](#mx_Sha256) |
[Sha3](#mx_Sha3) |
[Tdea](#mx_Tdea) |
[Wipe](#mx_Wipe) |
[Xof](#mx_Xof) |
[Zlib](#mx_Zlib)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="mx_Aead"></a>Aead Class

* [Aead.AddAAD Method](#M_Aead_AddAAD)

    + Add a chunk of additional authenticated data (in incremental mode)
* [Aead.Authenticate Method](#M_Aead_Authenticate)

    + Authenticate additional data using tag
* [Aead.Decrypt Method](#M_Aead_Decrypt)

    + Decrypt and authenticate input using specified AEAD algorithm in one-off operation
* [Aead.DecryptWithTag Method ](#M_Aead_DecryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm)

    + Decrypt data using specified AEAD algorithm in one-off operation. The authentication tag is expected to be appended to the input ciphertext.
* [Aead.DecryptWithTag Method ](#M_Aead_DecryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)

    + Decrypt data using specified AEAD algorithm in one-off operation with AAD and options. The authentication tag is expected to be appended to the input ciphertext.
* [Aead.Dispose Method](#M_Aead_Dispose)

    + Dispose of this object and clear any key schedules
* [Aead.Encrypt Method](#M_Aead_Encrypt)

    + Encrypt input using specified AEAD algorithm in one-off operation.
* [Aead.EncryptWithTag Method ](#M_Aead_EncryptWithTag_ByteByteByteAead_Algorithm) (Byte[], Byte[], Byte[], Aead.Algorithm)

    + Encrypt data using specified AEAD algorithm in one-off operation. The authentication tag is appended to the output.
* [Aead.EncryptWithTag Method ](#M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts) (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)

    + Encrypt data using specified AEAD algorithm in one-off operation with AAD and options. The authentication tag is appended to the output.
* [Aead.FinishDecrypt Method](#M_Aead_FinishDecrypt)

    + Finishes the authenticated decryption (in incremental mode)
* [Aead.FinishEncrypt Method](#M_Aead_FinishEncrypt)

    + Finishes the authenticated encryption (in incremental mode)
* [Aead.InitKey Method](#M_Aead_InitKey)

    + Initializes the context with the key and algorithm ready for repeated incremental operations
* [Aead.Instance Method](#M_Aead_Instance)

    + Create the one and only instance
* [Aead.Mac Method](#M_Aead_Mac)

    + Compute Message Authentication Code (tag) over input data
* [Aead.SetNonce Method](#M_Aead_SetNonce)

    + Set the nonce (in incremental mode)
* [Aead.StartDecrypt Method](#M_Aead_StartDecrypt)

    + Start authenticated decryption (in incremental mode)
* [Aead.StartEncrypt Method](#M_Aead_StartEncrypt)

    + Start authenticated encryption (in incremental mode)
* [Aead.Update Method](#M_Aead_Update)

    + Encrypts or decrypts a chunk of input (in incremental mode)
* [Aead.ErrCode Property](#M_Aead_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Aes128"></a>Aes128 Class

* [Aes128.Decrypt Method ](#M_Aes128_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Aes128.Decrypt Method ](#M_Aes128_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Aes128.Decrypt Method ](#M_Aes128_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Aes128.Dispose Method](#M_Aes128_Dispose)

    + Dispose of this object and clear any key schedules
* [Aes128.Encrypt Method ](#M_Aes128_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Aes128.Encrypt Method ](#M_Aes128_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Aes128.Encrypt Method ](#M_Aes128_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Aes128.FileDecrypt Method ](#M_Aes128_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Aes128.FileDecrypt Method ](#M_Aes128_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Aes128.FileDecrypt Method ](#M_Aes128_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Aes128.FileEncrypt Method ](#M_Aes128_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Aes128.FileEncrypt Method ](#M_Aes128_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Aes128.FileEncrypt Method ](#M_Aes128_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Aes128.InitDecrypt Method ](#M_Aes128_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Aes128.InitDecrypt Method ](#M_Aes128_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Aes128.InitEncrypt Method ](#M_Aes128_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Aes128.InitEncrypt Method ](#M_Aes128_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Aes128.Instance Method](#M_Aes128_Instance)

    + Create the one and only instance
* [Aes128.Pad Method ](#M_Aes128_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Aes128.Pad Method ](#M_Aes128_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Aes128.Unpad Method ](#M_Aes128_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Aes128.Unpad Method ](#M_Aes128_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Aes128.Update Method ](#M_Aes128_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction
* [Aes128.Update Method ](#M_Aes128_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Aes128.ErrCode Property](#M_Aes128_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Aes192"></a>Aes192 Class

* [Aes192.Decrypt Method ](#M_Aes192_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Aes192.Decrypt Method ](#M_Aes192_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Aes192.Decrypt Method ](#M_Aes192_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Aes192.Dispose Method](#M_Aes192_Dispose)

    + Dispose of this object and clear any key schedules
* [Aes192.Encrypt Method ](#M_Aes192_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Aes192.Encrypt Method ](#M_Aes192_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Aes192.Encrypt Method ](#M_Aes192_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Aes192.FileDecrypt Method ](#M_Aes192_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Aes192.FileDecrypt Method ](#M_Aes192_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Aes192.FileDecrypt Method ](#M_Aes192_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Aes192.FileEncrypt Method ](#M_Aes192_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Aes192.FileEncrypt Method ](#M_Aes192_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Aes192.FileEncrypt Method ](#M_Aes192_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Aes192.InitDecrypt Method ](#M_Aes192_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Aes192.InitDecrypt Method ](#M_Aes192_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Aes192.InitEncrypt Method ](#M_Aes192_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Aes192.InitEncrypt Method ](#M_Aes192_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Aes192.Instance Method](#M_Aes192_Instance)

    + Create the one and only instance
* [Aes192.Pad Method ](#M_Aes192_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Aes192.Pad Method ](#M_Aes192_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Aes192.Unpad Method ](#M_Aes192_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Aes192.Unpad Method ](#M_Aes192_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Aes192.Update Method ](#M_Aes192_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction
* [Aes192.Update Method ](#M_Aes192_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Aes192.ErrCode Property](#M_Aes192_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Aes256"></a>Aes256 Class

* [Aes256.Decrypt Method ](#M_Aes256_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Aes256.Decrypt Method ](#M_Aes256_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Aes256.Decrypt Method ](#M_Aes256_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Aes256.Dispose Method](#M_Aes256_Dispose)

    + Dispose of this object and clear any key schedules
* [Aes256.Encrypt Method ](#M_Aes256_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Aes256.Encrypt Method ](#M_Aes256_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Aes256.Encrypt Method ](#M_Aes256_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Aes256.FileDecrypt Method ](#M_Aes256_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Aes256.FileDecrypt Method ](#M_Aes256_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Aes256.FileDecrypt Method ](#M_Aes256_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Aes256.FileEncrypt Method ](#M_Aes256_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Aes256.FileEncrypt Method ](#M_Aes256_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Aes256.FileEncrypt Method ](#M_Aes256_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Aes256.InitDecrypt Method ](#M_Aes256_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Aes256.InitDecrypt Method ](#M_Aes256_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Aes256.InitEncrypt Method ](#M_Aes256_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Aes256.InitEncrypt Method ](#M_Aes256_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Aes256.Instance Method](#M_Aes256_Instance)

    + Create the one and only instance
* [Aes256.Pad Method ](#M_Aes256_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Aes256.Pad Method ](#M_Aes256_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Aes256.Unpad Method ](#M_Aes256_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Aes256.Unpad Method ](#M_Aes256_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Aes256.Update Method ](#M_Aes256_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction
* [Aes256.Update Method ](#M_Aes256_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Aes256.ErrCode Property](#M_Aes256_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Blowfish"></a>Blowfish Class

* [Blowfish.Decrypt Method ](#M_Blowfish_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Blowfish.Decrypt Method ](#M_Blowfish_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Blowfish.Decrypt Method ](#M_Blowfish_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Blowfish.Dispose Method](#M_Blowfish_Dispose)

    + Dispose of this object and clear any key schedules
* [Blowfish.Encrypt Method ](#M_Blowfish_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Blowfish.Encrypt Method ](#M_Blowfish_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Blowfish.Encrypt Method ](#M_Blowfish_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Blowfish.FileDecrypt Method ](#M_Blowfish_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Blowfish.FileDecrypt Method ](#M_Blowfish_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Blowfish.FileDecrypt Method ](#M_Blowfish_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Blowfish.FileEncrypt Method ](#M_Blowfish_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Blowfish.FileEncrypt Method ](#M_Blowfish_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Blowfish.FileEncrypt Method ](#M_Blowfish_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Blowfish.InitDecrypt Method ](#M_Blowfish_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Blowfish.InitDecrypt Method ](#M_Blowfish_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Blowfish.InitEncrypt Method ](#M_Blowfish_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Blowfish.InitEncrypt Method ](#M_Blowfish_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Blowfish.Instance Method](#M_Blowfish_Instance)

    + Create the one and only instance
* [Blowfish.Pad Method ](#M_Blowfish_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Blowfish.Pad Method ](#M_Blowfish_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Blowfish.Unpad Method ](#M_Blowfish_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Blowfish.Unpad Method ](#M_Blowfish_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Blowfish.Update Method ](#M_Blowfish_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction
* [Blowfish.Update Method ](#M_Blowfish_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Blowfish.ErrCode Property](#M_Blowfish_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Cipher"></a>Cipher Class

* [Cipher.BlockBytes Method](#M_Cipher_BlockBytes)

    + Return the block size in bytes for a given cipher algorithm
* [Cipher.Decrypt Method ](#M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)

    + Decrypt data in a byte array using the specified block cipher algorithm, mode and padding.
* [Cipher.Decrypt Method ](#M_Cipher_Decrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)

    + Decrypt hex-encoded data using specified block cipher algorithm, mode and padding.
* [Cipher.Dispose Method](#M_Cipher_Dispose)

    + Dispose of this object and clear any stored data.
* [Cipher.Encrypt Method ](#M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts) (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)

    + Encrypt data in a byte array using the specified block cipher algorithm, mode and padding.
* [Cipher.Encrypt Method ](#M_Cipher_Encrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts) (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)

    + Encrypt hex-encoded data using specified block cipher algorithm, mode and padding.
* [Cipher.FileDecrypt Method](#M_Cipher_FileDecrypt)

    + Decrypt a file with block cipher
* [Cipher.FileEncrypt Method](#M_Cipher_FileEncrypt)

    + Encrypt a file with block cipher
* [Cipher.InitDecrypt Method ](#M_Cipher_InitDecrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode)

    + Initializes with key, iv, algorithm and mode ready to start decrypting with repeated update operations.
* [Cipher.InitDecrypt Method ](#M_Cipher_InitDecrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode)

    + Initializes with hex-encoded key, iv, algorithm and mode ready to start decrypting with repeated update operations.
* [Cipher.InitEncrypt Method ](#M_Cipher_InitEncrypt_ByteByteCipherAlgorithmMode) (Byte[], Byte[], CipherAlgorithm, Mode)

    + Initializes with key, iv, algorithm and mode ready to start encrypting with repeated update operations.
* [Cipher.InitEncrypt Method ](#M_Cipher_InitEncrypt_StringStringCipherAlgorithmMode) (String, String, CipherAlgorithm, Mode)

    + Initializes with hex-encoded key, iv, algorithm and mode ready to start encrypting with repeated update operations.
* [Cipher.Instance Method](#M_Cipher_Instance)

    + Create the one and only instance
* [Cipher.KeyBytes Method](#M_Cipher_KeyBytes)

    + Return the key size in bytes for a given cipher algorithm
* [Cipher.KeyUnwrap Method](#M_Cipher_KeyUnwrap)

    + Unwraps (decrypts) key material with a key-encryption key
* [Cipher.KeyWrap Method](#M_Cipher_KeyWrap)

    + Wraps (encrypts) key material with a key-encryption key
* [Cipher.Pad Method ](#M_Cipher_Pad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding)

    + Pad byte array for block cipher.
* [Cipher.Pad Method ](#M_Cipher_Pad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding)

    + Pads hex-encoded string for block cipher.
* [Cipher.Unpad Method ](#M_Cipher_Unpad_ByteCipherAlgorithmPadding) (Byte[], CipherAlgorithm, Padding)

    + Remove padding from an encryption block.
* [Cipher.Unpad Method ](#M_Cipher_Unpad_StringCipherAlgorithmPadding) (String, CipherAlgorithm, Padding)

    + Remove padding from a hex-encoded encryption block.
* [Cipher.Update Method ](#M_Cipher_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction.
* [Cipher.Update Method ](#M_Cipher_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Cipher.ErrCode Property](#M_Cipher_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_CipherStream"></a>CipherStream Class

* [CipherStream.Bytes Method](#M_CipherStream_Bytes)

    + Enciphers data in array of bytes using specified stream cipher.
* [CipherStream.Dispose Method](#M_CipherStream_Dispose)

    + Dispose of this object and clear any key schedules
* [CipherStream.File Method](#M_CipherStream_File)

    + Enciphers data in a file using specified stream cipher.
* [CipherStream.Hex Method](#M_CipherStream_Hex)

    + Enciphers data in a hex-encoded string using specified stream cipher.
* [CipherStream.Init Method](#M_CipherStream_Init)

    + Initializes the context ready for repeated operations of CipherStream.Update
* [CipherStream.Instance Method](#M_CipherStream_Instance)

    + Create the one and only instance
* [CipherStream.Update Method](#M_CipherStream_Update)

    + Encrypts input using current context
* [CipherStream.ErrCode Property](#M_CipherStream_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Cnv"></a>Cnv Class

* [Cnv.Base64Filter Method](#M_Cnv_Base64Filter)

    + Filters non-base64 characters from a string
* [Cnv.Base64FromHex Method](#M_Cnv_Base64FromHex)

    + Converts hexadecimal-encoded data into base64-encoded data
* [Cnv.FromBase64 Method](#M_Cnv_FromBase64)

    + Converts a base64-encoded string to an equivalent array of 8-bit unsigned integers.
* [Cnv.FromHex Method](#M_Cnv_FromHex)

    + Converts a hexadecimal-encoded string to an equivalent array of 8-bit unsigned integers.
* [Cnv.HexFilter Method](#M_Cnv_HexFilter)

    + Filters non-hexadecimal characters from a string
* [Cnv.HexFromBase64 Method](#M_Cnv_HexFromBase64)

    + Converts base64-encoded data into hexadecimal-encoded data
* [Cnv.ShortPathName Method](#M_Cnv_ShortPathName)

    + Retrieve the Windows short path form of the specified path.
* [Cnv.StringFromBase64 Method](#M_Cnv_StringFromBase64)

    + Converts a base64-encoded string into a text string
* [Cnv.StringFromHex Method](#M_Cnv_StringFromHex)

    + Converts a hexadecimal-encoded string into a text string
* [Cnv.ToBase64 Method ](#M_Cnv_ToBase64_Byte) (Byte[])

    + Converts 8-bit binary data to equivalent base64-encoded string format
* [Cnv.ToBase64 Method ](#M_Cnv_ToBase64_String) (String)

    + Converts a string of ANSI characters to equivalent base64-encoded string format
* [Cnv.ToHex Method ](#M_Cnv_ToHex_Byte) (Byte[])

    + Converts 8-bit binary data to equivalent hexadecimal string format
* [Cnv.ToHex Method ](#M_Cnv_ToHex_String) (String)

    + Converts a string of ANSI characters to equivalent hexadecimal string format

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Compr"></a>Compr Class

* [Compr.Compress Method](#M_Compr_Compress)

    + Compress data using compression algorithm.
* [Compr.Uncompress Method](#M_Compr_Uncompress)

    + Uncompress data using compression algorithm.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Crc"></a>Crc Class

* [Crc.Data Method ](#M_Crc_Data_Byte) (Byte[])

    + Computes CRC-32 checksum for data
* [Crc.Data Method ](#M_Crc_Data_String) (String)

    + Computes CRC-32 checksum for a string
* [Crc.File Method](#M_Crc_File)

    + Computes CRC-32 checksum for a file

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Des"></a>Des Class

* [Des.CheckKey Method ](#M_Des_CheckKey_Byte) (Byte[])

    + Verifies that no part of the key is a weak or semi-weak DES key.
* [Des.CheckKey Method ](#M_Des_CheckKey_String) (String)

    + Verifies that no part of the key is a weak or semi-weak DES key.
* [Des.Decrypt Method ](#M_Des_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Des.Decrypt Method ](#M_Des_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Des.Decrypt Method ](#M_Des_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Des.Dispose Method](#M_Des_Dispose)

    + Dispose of this object and clear any key schedules
* [Des.Encrypt Method ](#M_Des_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Des.Encrypt Method ](#M_Des_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Des.Encrypt Method ](#M_Des_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Des.FileDecrypt Method ](#M_Des_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Des.FileDecrypt Method ](#M_Des_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Des.FileDecrypt Method ](#M_Des_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Des.FileEncrypt Method ](#M_Des_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Des.FileEncrypt Method ](#M_Des_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Des.FileEncrypt Method ](#M_Des_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Des.InitDecrypt Method ](#M_Des_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Des.InitDecrypt Method ](#M_Des_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Des.InitEncrypt Method ](#M_Des_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Des.InitEncrypt Method ](#M_Des_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Des.Instance Method](#M_Des_Instance)

    + Create the one and only instance
* [Des.Pad Method ](#M_Des_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Des.Pad Method ](#M_Des_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Des.Unpad Method ](#M_Des_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Des.Unpad Method ](#M_Des_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Des.Update Method ](#M_Des_Update_Byte) (Byte[])

    + Transforms byte input data with previously initialized key, mode and direction
* [Des.Update Method ](#M_Des_Update_String) (String)

    + Transforms hex string data with previously initialized key, mode and direction
* [Des.ErrCode Property](#M_Des_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Gcm"></a>Gcm Class

* [Gcm.Decrypt Method](#M_Gcm_Decrypt)

    + Decrypt input using AES-GCM in one-off operation
* [Gcm.Dispose Method](#M_Gcm_Dispose)

    + Dispose of this object and clear any key schedules
* [Gcm.Encrypt Method](#M_Gcm_Encrypt)

    + Encrypt input using AES-GCM in one-off operation
* [Gcm.Gmac Method](#M_Gcm_Gmac)

    + Compute GMAC using AES-GCM in one-off operation
* [Gcm.InitKey Method](#M_Gcm_InitKey)

    + Initializes the context with the key ready for repeated operations of Gcm.NextEncrypt, Gcm.NextDecrypt, or Gcm.NextGmac.
* [Gcm.Instance Method](#M_Gcm_Instance)

    + Create the one and only instance
* [Gcm.NextDecrypt Method](#M_Gcm_NextDecrypt)

    + Carries out the GCM decryption operation using the key set up by an earlier call to Gcm.InitKey.
* [Gcm.NextEncrypt Method](#M_Gcm_NextEncrypt)

    + Carries out the GCM encryption operation using the key set up by an earlier call to Gcm.InitKey.
* [Gcm.NextGmac Method](#M_Gcm_NextGmac)

    + Carries out the GMAC operation using the key set up by an earlier call to Gcm.InitKey.
* [Gcm.ErrCode Property](#M_Gcm_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_General"></a>General Class

* [General.CompileTime Method](#M_General_CompileTime)

    + Gets date and time the CryptoSys DLL module was last compiled
* [General.ErrorCode Method](#M_General_ErrorCode)

    + Returns the error code of the error that occurred when calling the last function
* [General.ErrorLookup Method](#M_General_ErrorLookup)

    + Looks up error code
* [General.FormatErrorMessage Method](#M_General_FormatErrorMessage)

    + Return an error message string for the last error.
* [General.IsWin64 Method](#M_General_IsWin64)

    + Returns flag indicating the platform of the core DLL.
* [General.LicenceType Method](#M_General_LicenceType)

    + Gets licence type.
* [General.ModuleInfo Method](#M_General_ModuleInfo)

    + Get additional information about the core DLL module.
* [General.ModuleName Method](#M_General_ModuleName)

    + Gets full path name of core CryptoSys DLL module
* [General.NetVersion Method](#M_General_NetVersion)

    + Return the version of this .NET module.
* [General.Platform Method](#M_General_Platform)

    + Return the platform the core DLL was compiled for.
* [General.PowerUpTests Method](#M_General_PowerUpTests)

    + Performs FIPS-140-2 start-up tests
* [General.Version Method](#M_General_Version)

    + Returns version number of core CryptoSys DLL.

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Hash"></a>Hash Class

* [Hash.AddData Method ](#M_Hash_AddData_Byte) (Byte[])

    + Adds a chunk of data in a byte array to be digested by the Hash object.
* [Hash.AddData Method ](#M_Hash_AddData_String) (String)

    + Adds a chunk of data in a string to be digested by the Hash object.
* [Hash.BytesFromBytes Method](#M_Hash_BytesFromBytes)

    + Computes hash value in byte format of byte input
* [Hash.BytesFromFile Method](#M_Hash_BytesFromFile)

    + Computes hash value in byte format of a binary file
* [Hash.Dispose Method](#M_Hash_Dispose)

    + Dispose of this object and clear any stored data.
* [Hash.Final Method](#M_Hash_Final)

    + Computes final message digest for the Hash object.
* [Hash.HexFromBits Method](#M_Hash_HexFromBits)

    + Computes hash value in hex format from bit-oriented input
* [Hash.HexFromBytes Method](#M_Hash_HexFromBytes)

    + Computes hash value in hex format of byte input
* [Hash.HexFromFile Method](#M_Hash_HexFromFile)

    + Computes hash value in hex format of a binary file
* [Hash.HexFromHex Method](#M_Hash_HexFromHex)

    + Computes hash value in hex format of hex-encoded input
* [Hash.HexFromString Method](#M_Hash_HexFromString)

    + Computes hash value in hex format of string input
* [Hash.HexFromTextFile Method](#M_Hash_HexFromTextFile)

    + Computes hash value in hex format of a text file, treating CR-LF pairs as a single LF
* [Hash.Init Method](#M_Hash_Init)

    + Initialises the Hash object ready for repeated incremental operations.
* [Hash.Instance Method](#M_Hash_Instance)

    + Create the one and only instance
* [Hash.LengthInBytes Method](#M_Hash_LengthInBytes)

    + Returns the number of bytes in the message digest for the given hash algorithm.
* [Hash.Reset Method](#M_Hash_Reset)

    + Resets the context of the Hash object.
* [Hash.ErrCode Property](#M_Hash_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Mac"></a>Mac Class

* [Mac.AddData Method ](#M_Mac_AddData_Byte) (Byte[])

    + Adds a chunk of data in a byte array to be authenticated by the Mac object.
* [Mac.AddData Method ](#M_Mac_AddData_String) (String)

    + Adds a chunk of data in a string to be authenticated by the Mac object.
* [Mac.BytesFromBytes Method](#M_Mac_BytesFromBytes)

    + Computes MAC value in byte format from byte input
* [Mac.Dispose Method](#M_Mac_Dispose)

    + Dispose of this object and clear any stored data.
* [Mac.Final Method](#M_Mac_Final)

    + Computes final MAC value for the Mac object.
* [Mac.HexFromBytes Method](#M_Mac_HexFromBytes)

    + Computes MAC value in hex-encoded format from byte input
* [Mac.HexFromHex Method](#M_Mac_HexFromHex)

    + Computes MAC value in hex-encoded format from hex-encoded input
* [Mac.Init Method](#M_Mac_Init)

    + Initialises the Mac object ready for repeated incremental operations.
* [Mac.Instance Method](#M_Mac_Instance)

    + Create the one and only instance
* [Mac.Reset Method](#M_Mac_Reset)

    + Resets the context of the Mac object.
* [Mac.ErrCode Property](#M_Mac_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Md5"></a>Md5 Class

* [Md5.AddData Method ](#M_Md5_AddData_Byte) (Byte[])

    + Adds an array of 8-bit bytes to the digest
* [Md5.AddData Method ](#M_Md5_AddData_String) (String)

    + Adds a string of Ansi characters to the digest
* [Md5.BytesHash Method](#M_Md5_BytesHash)

    + Creates message digest as array of bytes from message in byte array
* [Md5.Dispose Method](#M_Md5_Dispose)

    + Dispose of this object and clear any stored data
* [Md5.FileHexHash Method](#M_Md5_FileHexHash)

    + Creates hash digest of a binary file
* [Md5.FileTextHexHash Method](#M_Md5_FileTextHexHash)

    + Creates hash digest of a "text" file treating CR-LF pairs as a single newline char
* [Md5.HexDigest Method](#M_Md5_HexDigest)

    + Computes final message digest in hex format
* [Md5.HexHash Method ](#M_Md5_HexHash_Byte) (Byte[])

    + Creates message digest in hex format from message in byte array
* [Md5.HexHash Method ](#M_Md5_HexHash_String) (String)

    + Creates message digest in hex format from message in Ansi string
* [Md5.Hmac Method ](#M_Md5_Hmac_ByteByte) (Byte[], Byte[])

    + Computes the keyed hash digest of binary data using HMAC algorithm
* [Md5.Hmac Method ](#M_Md5_Hmac_StringString) (String, String)

    + Computes the keyed hash digest using HMAC algorithm passing data as hex strings
* [Md5.Init Method](#M_Md5_Init)

    + Initializes the context
* [Md5.Instance Method](#M_Md5_Instance)

    + Create the one and only instance
* [Md5.Reset Method](#M_Md5_Reset)

    + Resets the context
* [Md5.ErrCode Property](#M_Md5_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Pbe"></a>Pbe Class

* [Pbe.Kdf2 Method ](#M_Pbe_Kdf2_Int32ByteByteInt32HashAlgorithm) (Int32, Byte[], Byte[], Int32, HashAlgorithm)

    + Derives a key of any length from a password using the PBKDF2 algorithm using specified HMAC algorithm
* [Pbe.Kdf2 Method ](#M_Pbe_Kdf2_Int32StringStringInt32HashAlgorithm) (Int32, String, String, Int32, HashAlgorithm)

    + Derives a key in hex format of any length from a password with the salt in hex format using specified HMAC algorithm
* [Pbe.Scrypt Method ](#M_Pbe_Scrypt_Int32ByteByteInt32Int32Int32) (Int32, Byte[], Byte[], Int32, Int32, Int32)

    + Derives a key of any length from a password using the SCRYPT algorithm.
* [Pbe.Scrypt Method ](#M_Pbe_Scrypt_Int32StringStringInt32Int32Int32) (Int32, String, String, Int32, Int32, Int32)

    + Derives a key in hex format from a password with the salt in hex format

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Pc1"></a>Pc1 Class

* [Pc1.Encrypt Method ](#M_Pc1_Encrypt_ByteByte) (Byte[], Byte[])

    + Encrypt byte array input using RC4-compatible algorithm
* [Pc1.Encrypt Method ](#M_Pc1_Encrypt_StringString) (String, String)

    + Encrypt hex-encoded input using RC4-compatible algorithm
* [Pc1.File Method](#M_Pc1_File)

    + Encrypt a file using RC4-compatible algorithm

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Prf"></a>Prf Class

* [Prf.Bytes Method](#M_Prf_Bytes)

    + Generate output bytes using a pseudorandom function (PRF).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Rng"></a>Rng Class

* [Rng.BytesWithPrompt Method ](#M_Rng_BytesWithPrompt_Int32Rng_Strength) (Int32, Rng.Strength)

    + Generates an array of random bytes with a prompt for keyboard input
* [Rng.BytesWithPrompt Method ](#M_Rng_BytesWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength)

    + Generates an array of random bytes with a prompt for keyboard input
* [Rng.HexWithPrompt Method ](#M_Rng_HexWithPrompt_Int32) (Int32)

    + Generates random bytes in hex format with a prompt for keyboard input
* [Rng.HexWithPrompt Method ](#M_Rng_HexWithPrompt_Int32StringRng_Strength) (Int32, String, Rng.Strength)

    + Generates random bytes in hex format with a prompt for keyboard input
* [Rng.Initialize Method](#M_Rng_Initialize)

    + Initialize the RNG generator with a seed file.
* [Rng.InitializeEx Method](#M_Rng_InitializeEx)

    + Query and initialize the RNG generator using Intel(R) DRNG, if available.
* [Rng.KeyBytes Method ](#M_Rng_KeyBytes_Int32Byte) (Int32, Byte[])

    + Generates a random key with user-supplied entropy
* [Rng.KeyBytes Method ](#M_Rng_KeyBytes_Int32String) (Int32, String)

    + Generates a random key
* [Rng.KeyHex Method ](#M_Rng_KeyHex_Int32Byte) (Int32, Byte[])

    + Generates a random key in hex format with user-supplied entropy
* [Rng.KeyHex Method ](#M_Rng_KeyHex_Int32String) (Int32, String)

    + Generates a random key in hex format
* [Rng.MakeSeedFile Method ](#M_Rng_MakeSeedFile_StringRng_Strength) (String, Rng.Strength)

    + Create a new seed file suitable for use with Rng.Initialize
* [Rng.MakeSeedFile Method ](#M_Rng_MakeSeedFile_StringStringRng_Strength) (String, String, Rng.Strength)

    + Create a new seed file suitable for use with Rng.Initialize
* [Rng.NonceBytes Method](#M_Rng_NonceBytes)

    + Generates a random nonce
* [Rng.NonceHex Method](#M_Rng_NonceHex)

    + Generates a random nonce in hex format
* [Rng.Number Method](#M_Rng_Number)

    + Generates a random integer in a given range
* [Rng.Octet Method](#M_Rng_Octet)

    + Generates a single random octet (byte)
* [Rng.Test Method](#M_Rng_Test)

    + Carries out a NIST SP800-90 health check and FIPS140-2 statistical tests on the random number generator
* [Rng.TestDrbgvs Method](#M_Rng_TestDrbgvs)

    + Tests the random number generator for conformance to NIST SP 800-90A using the relevant test specified in the Deterministic Random Bit Generator Validation System (DRBGVS).
* [Rng.UpdateSeedFile Method](#M_Rng_UpdateSeedFile)

    + Updates the RNG seed file

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Sha1"></a>Sha1 Class

* [Sha1.AddData Method ](#M_Sha1_AddData_Byte) (Byte[])

    + Adds an array of 8-bit bytes to the digest
* [Sha1.AddData Method ](#M_Sha1_AddData_String) (String)

    + Adds a string of Ansi characters to the digest
* [Sha1.BytesHash Method](#M_Sha1_BytesHash)

    + Creates message digest as array of bytes from message in byte array
* [Sha1.Dispose Method](#M_Sha1_Dispose)

    + Dispose of this object and clear any stored data
* [Sha1.FileHexHash Method](#M_Sha1_FileHexHash)

    + Creates hash digest of a binary file
* [Sha1.FileTextHexHash Method](#M_Sha1_FileTextHexHash)

    + Creates hash digest of a "text" file treating CR-LF pairs as a single newline char
* [Sha1.HexDigest Method](#M_Sha1_HexDigest)

    + Computes final message digest in hex format
* [Sha1.HexHash Method ](#M_Sha1_HexHash_Byte) (Byte[])

    + Creates message digest in hex format from message in byte array
* [Sha1.HexHash Method ](#M_Sha1_HexHash_String) (String)

    + Creates message digest in hex format from message in Ansi string
* [Sha1.Hmac Method ](#M_Sha1_Hmac_ByteByte) (Byte[], Byte[])

    + Computes the keyed hash digest of binary data using HMAC algorithm
* [Sha1.Hmac Method ](#M_Sha1_Hmac_StringString) (String, String)

    + Computes the keyed hash digest using HMAC algorithm passing data as hex strings
* [Sha1.Init Method](#M_Sha1_Init)

    + Initializes the context
* [Sha1.Instance Method](#M_Sha1_Instance)

    + Create the one and only instance
* [Sha1.Reset Method](#M_Sha1_Reset)

    + Resets the context
* [Sha1.ErrCode Property](#M_Sha1_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Sha256"></a>Sha256 Class

* [Sha256.AddData Method ](#M_Sha256_AddData_Byte) (Byte[])

    + Adds an array of 8-bit bytes to the digest
* [Sha256.AddData Method ](#M_Sha256_AddData_String) (String)

    + Adds a string of Ansi characters to the digest
* [Sha256.BytesHash Method](#M_Sha256_BytesHash)

    + Creates message digest as array of bytes from message in byte array
* [Sha256.Dispose Method](#M_Sha256_Dispose)

    + Dispose of this object and clear any stored data
* [Sha256.FileHexHash Method](#M_Sha256_FileHexHash)

    + Creates hash digest of a binary file
* [Sha256.FileTextHexHash Method](#M_Sha256_FileTextHexHash)

    + Creates hash digest of a "text" file treating CR-LF pairs as a single newline char
* [Sha256.HexDigest Method](#M_Sha256_HexDigest)

    + Computes final message digest in hex format
* [Sha256.HexHash Method ](#M_Sha256_HexHash_Byte) (Byte[])

    + Creates message digest in hex format from message in byte array
* [Sha256.HexHash Method ](#M_Sha256_HexHash_String) (String)

    + Creates message digest in hex format from message in Ansi string
* [Sha256.Hmac Method ](#M_Sha256_Hmac_ByteByte) (Byte[], Byte[])

    + Computes the keyed hash digest of binary data using HMAC algorithm
* [Sha256.Hmac Method ](#M_Sha256_Hmac_StringString) (String, String)

    + Computes the keyed hash digest using HMAC algorithm passing data as hex strings
* [Sha256.Init Method](#M_Sha256_Init)

    + Initializes the context
* [Sha256.Instance Method](#M_Sha256_Instance)

    + Create the one and only instance
* [Sha256.Reset Method](#M_Sha256_Reset)

    + Resets the context
* [Sha256.ErrCode Property](#M_Sha256_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Sha3"></a>Sha3 Class

* [Sha3.AddData Method ](#M_Sha3_AddData_Byte) (Byte[])

    + Adds an array of 8-bit bytes to the digest
* [Sha3.AddData Method ](#M_Sha3_AddData_String) (String)

    + Adds a string of Ansi characters to the digest
* [Sha3.Dispose Method](#M_Sha3_Dispose)

    + Dispose of this object and clear any stored data
* [Sha3.HexDigest Method](#M_Sha3_HexDigest)

    + Computes final message digest in hex format
* [Sha3.Init Method](#M_Sha3_Init)

    + Initialises the object ready to receive data to digest
* [Sha3.Instance Method](#M_Sha3_Instance)

    + Create the one and only instance
* [Sha3.Reset Method](#M_Sha3_Reset)

    + Resets the context
* [Sha3.ErrCode Property](#M_Sha3_ErrCodeProperty)
* [Sha3.LengthInBytes Property](#M_Sha3_LengthInBytesProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Tdea"></a>Tdea Class

* [Tdea.CheckKey Method ](#M_Tdea_CheckKey_Byte) (Byte[])

    + Verifies that no part of the key is a weak or semi-weak TDEA key.
* [Tdea.CheckKey Method ](#M_Tdea_CheckKey_String) (String)

    + Verifies that no part of the key is a weak or semi-weak TDEA key.
* [Tdea.Decrypt Method ](#M_Tdea_Decrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Decrypt data in byte array
* [Tdea.Decrypt Method ](#M_Tdea_Decrypt_StringStringModeString) (String, String, Mode, String)

    + Decrypt hex-encoded data string
* [Tdea.Decrypt Method ](#M_Tdea_Decrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Decrypt encoded data string
* [Tdea.Dispose Method](#M_Tdea_Dispose)

    + Dispose of this object and clear any key schedules
* [Tdea.Encrypt Method ](#M_Tdea_Encrypt_ByteByteModeByte) (Byte[], Byte[], Mode, Byte[])

    + Encrypt data in byte array
* [Tdea.Encrypt Method ](#M_Tdea_Encrypt_StringStringModeString) (String, String, Mode, String)

    + Encrypt hex-encoded data string
* [Tdea.Encrypt Method ](#M_Tdea_Encrypt_StringStringModeStringEncodingBase) (String, String, Mode, String, EncodingBase)

    + Encrypt encoded data string
* [Tdea.FileDecrypt Method ](#M_Tdea_FileDecrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Decrypt a file
* [Tdea.FileDecrypt Method ](#M_Tdea_FileDecrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Decrypt a file with advanced options
* [Tdea.FileDecrypt Method ](#M_Tdea_FileDecrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Decrypt a file passing key and IV as hex strings
* [Tdea.FileEncrypt Method ](#M_Tdea_FileEncrypt_StringStringByteModeByte) (String, String, Byte[], Mode, Byte[])

    + Encrypt a file
* [Tdea.FileEncrypt Method ](#M_Tdea_FileEncrypt_StringStringByteModeByteCipherFileOption) (String, String, Byte[], Mode, Byte[], CipherFileOption)

    + Encrypt a file with advanced options
* [Tdea.FileEncrypt Method ](#M_Tdea_FileEncrypt_StringStringStringModeString) (String, String, String, Mode, String)

    + Encrypt a file passing key and IV as hex strings
* [Tdea.InitDecrypt Method ](#M_Tdea_InitDecrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start decrypting
* [Tdea.InitDecrypt Method ](#M_Tdea_InitDecrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start decrypting
* [Tdea.InitEncrypt Method ](#M_Tdea_InitEncrypt_ByteModeByte) (Byte[], Mode, Byte[])

    + Initializes with key, mode and IV ready to start encrypting
* [Tdea.InitEncrypt Method ](#M_Tdea_InitEncrypt_StringModeString) (String, Mode, String)

    + Initializes with hex key, mode and hex IV ready to start encrypting
* [Tdea.Instance Method](#M_Tdea_Instance)

    + Create the one and only instance
* [Tdea.Pad Method ](#M_Tdea_Pad_Byte) (Byte[])

    + Pads byte array to correct length for ECB and CBC encryption
* [Tdea.Pad Method ](#M_Tdea_Pad_String) (String)

    + Pads hex-encoded string to correct length for ECB and CBC encryption
* [Tdea.Unpad Method ](#M_Tdea_Unpad_Byte) (Byte[])

    + Removes the padding from an encryption block
* [Tdea.Unpad Method ](#M_Tdea_Unpad_String) (String)

    + Removes the padding from a hex-encoded encryption block
* [Tdea.Update Method ](#M_Tdea_Update_Byte) (Byte[])

    + Transform byte input data with previously initialized key, mode and direction
* [Tdea.Update Method ](#M_Tdea_Update_String) (String)

    + Transform hex string data with previously initialized key, mode and direction
* [Tdea.ErrCode Property](#M_Tdea_ErrCodeProperty)

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Wipe"></a>Wipe Class

* [Wipe.Data Method](#M_Wipe_Data)

    + Zeroises data in memory
* [Wipe.File Method](#M_Wipe_File)

    + Securely wipe and delete a file.
* [Wipe.String Method](#M_Wipe_String)

    + Zeroises a StringBuilder

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Xof"></a>Xof Class

* [Xof.Bytes Method](#M_Xof_Bytes)

    + Generate bytes using an extendable-output function (XOF).

[[Contents](#topofpage)] [[Index](#index)]

### <a id="mx_Zlib"></a>Zlib Class

* [Zlib.Deflate Method](#M_Zlib_Deflate)

    + Compress data using the ZLIB deflate algorithm
* [Zlib.Inflate Method ](#M_Zlib_Inflate_Byte) (Byte[])

    + Inflate compressed data using the ZLIB algorithm.
* [Zlib.Inflate Method ](#M_Zlib_Inflate_ByteInt32) (Byte[], Int32)

    + Inflate compressed data using the ZLIB algorithm [superseded].

[[Contents](#topofpage)] [[Index](#index)]

<a id="methodlist"></a>List of .Net Methods
-------------------------------------------

Class index:   
[Aead](#mx_Aead) |
[Aes128](#mx_Aes128) |
[Aes192](#mx_Aes192) |
[Aes256](#mx_Aes256) |
[Blowfish](#mx_Blowfish) |
[Cipher](#mx_Cipher) |
[CipherStream](#mx_CipherStream) |
[Cnv](#mx_Cnv) |
[Compr](#mx_Compr) |
[Crc](#mx_Crc) |
[Des](#mx_Des) |
[Gcm](#mx_Gcm) |
[General](#mx_General) |
[Hash](#mx_Hash) |
[Mac](#mx_Mac) |
[Md5](#mx_Md5) |
[Pbe](#mx_Pbe) |
[Pc1](#mx_Pc1) |
[Prf](#mx_Prf) |
[Rng](#mx_Rng) |
[Sha1](#mx_Sha1) |
[Sha256](#mx_Sha256) |
[Sha3](#mx_Sha3) |
[Tdea](#mx_Tdea) |
[Wipe](#mx_Wipe) |
[Xof](#mx_Xof) |
[Zlib](#mx_Zlib)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_AddAAD"></a>Aead.AddAAD Method

 Add a chunk of additional authenticated data (in incremental mode) 

#### Syntax

[`C#`]

```
public int AddAAD(
	byte[] aad
)
```

[`VB.NET`]

```
Public Function AddAAD ( _
	aad As Byte() _
) As Integer
```

#### Parameters

aad

:   Chunk of additional data to add

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

May be repeated to add additional data in chunks. Must eventually be followed by either StartEncrypt() or StartDecrypt().

#### See Also

VB6/C equivalent: [`AEAD_AddAAD`](#AEAD_AddAAD)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Authenticate"></a>Aead.Authenticate Method

 Authenticate additional data using tag 

#### Syntax

[`C#`]

```
public static bool Authenticate(
	byte[] key,
	byte[] nonce,
	byte[] aad,
	byte[] tag,
	Aead.Algorithm alg
)
```

[`VB.NET`]

```
Public Shared Function Authenticate ( _
	key As Byte(), _
	nonce As Byte(), _
	aad As Byte(), _
	tag As Byte(), _
	alg As Aead.Algorithm _
) As Boolean
```

#### Parameters

key

:   Key of exact length for given algorithm (16 or 32 bytes).

nonce

:   Nonce of exact length for given algorithm (currently always 12 bytes)

aad

:   Data to be authenticated

tag

:   Tag value

alg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

AEAD algorithm to use

#### Return Value

True if authentication is valid; false if failed or an error occurred.

#### Remarks

Use General.ErrorCode to find the code of the last error. This is equivalent to Aead.Decrypt with a zero-length ciphertext input.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Decrypt"></a>Aead.Decrypt Method

 Decrypt and authenticate input using specified AEAD algorithm in one-off operation 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	byte[] nonce,
	byte[] aad,
	byte[] tag,
	Aead.Algorithm alg
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	nonce As Byte(), _
	aad As Byte(), _
	tag As Byte(), _
	alg As Aead.Algorithm _
) As Byte()
```

#### Parameters

input

:   Cipher text input data (required)

key

:   Key of exact length for given algorithm (16 or 32 bytes).

nonce

:   Nonce of exact length for given algorithm (currently always 12 bytes).

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

tag

:   Tag value (required)

alg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

AEAD algorithm to use

#### Return Value

Decrypted plaintext in byte array, or empty array on error

#### Remarks

Use General.ErrorCode to find the code of the last error. The plaintext is always the same length as the ciphertext. The tag must be input separately.

#### See Also

VB6/C equivalent: [`AEAD_Decrypt`](#AEAD_Decrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_DecryptWithTag_ByteByteByteAead_Algorithm"></a>Aead.DecryptWithTag Method (Byte[], Byte[], Byte[], Aead.Algorithm)

 Decrypt data using specified AEAD algorithm in one-off operation. The authentication tag is expected to be appended to the input ciphertext. 

#### Syntax

[`C#`]

```
public static byte[] DecryptWithTag(
	byte[] input,
	byte[] key,
	byte[] iv,
	Aead.Algorithm aeadAlg
)
```

[`VB.NET`]

```
Public Shared Function DecryptWithTag ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aeadAlg As Aead.Algorithm _
) As Byte()
```

#### Parameters

input

:   Input data to be decrypted.

key

:   Key of exact length for algorithm (16 or 32 bytes).

iv

:   Initialization Vector (IV) (aka nonce) (12 or 16 bytes).

aeadAlg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

Authenticated encryption algorithm.

#### Return Value

Plaintext in a byte array, or empty array on error (an empty array may also be the correct result - check General.ErrorCode for details).

#### Remarks

The input *must* include the 16-byte tag appended to the ciphertext. The output will be exactly 16 bytes shorter than the input. In all cases the tag *must* be exactly 16 bytes (128 bits). The IV must be 16 bytes (128 bits) for ASCON-128 otherwise 12 bytes (96 bits).

#### See Also

VB6/C equivalent: [`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_DecryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts"></a>Aead.DecryptWithTag Method (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)

 Decrypt data using specified AEAD algorithm in one-off operation with AAD and options. The authentication tag is expected to be appended to the input ciphertext. 

#### Syntax

[`C#`]

```
public static byte[] DecryptWithTag(
	byte[] input,
	byte[] key,
	byte[] iv,
	byte[] aad,
	Aead.Algorithm aeadAlg,
	Aead.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function DecryptWithTag ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aad As Byte(), _
	aeadAlg As Aead.Algorithm, _
	opts As Aead.Opts _
) As Byte()
```

#### Parameters

input

:   Input data to be decrypted.

key

:   Key of exact length for algorithm (16 or 32 bytes).

iv

:   (optional) Initialization Vector (IV) (aka nonce) exactly 12 bytes long. Set as null if already prefixed to input.

aad

:   Additional authenticated data (optional) - set as null to ignore.

aeadAlg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

Authenticated encryption algorithm.

opts

:   Type: [Aead.Opts](#T_Aead_Opts)  

Advanced options. Use Aead.Opts.PrefixIV to expect the IV to be prepended at the start of the input.

#### Return Value

Plaintext in a byte array, or empty array on error (an empty array may also be the correct result - check General.ErrorCode for details).

#### Remarks

The input *must* include the 16-byte tag appended to the ciphertext and may include a 12-byte prefixed IV. The output will either be exactly 16 bytes shorter than the input, or exactly 28 bytes shorter if the Cipher.Opts.PrefixIV option is used. In all cases the tag *must* be exactly 16 bytes (128 bits). The IV must be 16 bytes (128 bits) for ASCON-128 otherwise 12 bytes (96 bits). If additional authentication data (AAD) was provided during encryption then the exact same AAD data must be provided here.

#### See Also

VB6/C equivalent: [`AEAD_DecryptWithTag`](#AEAD_DecryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Dispose"></a>Aead.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`AEAD_Destroy`](#AEAD_Destroy)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Encrypt"></a>Aead.Encrypt Method

 Encrypt input using specified AEAD algorithm in one-off operation. 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	out byte[] tag,
	byte[] input,
	byte[] key,
	byte[] nonce,
	byte[] aad,
	Aead.Algorithm alg
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	<OutAttribute> ByRef tag As Byte(), _
	input As Byte(), _
	key As Byte(), _
	nonce As Byte(), _
	aad As Byte(), _
	alg As Aead.Algorithm _
) As Byte()
```

#### Parameters

tag

:   To receive the output authentication tag value. Currently always returned exactly 16 bytes long. This is a by-reference parameter. There is no need to initialize (but the VB compiler may complain).

input

:   Plain text input data (required)

key

:   Key of exact length for given algorithm (16 or 32 bytes)

nonce

:   Nonce of exact length for given algorithm (currently always 12 bytes)

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

alg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

AEAD algorithm to use

#### Return Value

Encrypted ciphertext in byte array, or empty array on error

#### Remarks

Use General.ErrorCode to find the code of the last error. The ciphertext is always the same length as the plaintext. The authentication tag is output separately.

#### See Also

VB6/C equivalent: [`AEAD_Encrypt`](#AEAD_Encrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_EncryptWithTag_ByteByteByteAead_Algorithm"></a>Aead.EncryptWithTag Method (Byte[], Byte[], Byte[], Aead.Algorithm)

 Encrypt data using specified AEAD algorithm in one-off operation. The authentication tag is appended to the output. 

#### Syntax

[`C#`]

```
public static byte[] EncryptWithTag(
	byte[] input,
	byte[] key,
	byte[] iv,
	Aead.Algorithm aeadAlg
)
```

[`VB.NET`]

```
Public Shared Function EncryptWithTag ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aeadAlg As Aead.Algorithm _
) As Byte()
```

#### Parameters

input

:   Input data to be encrypted.

key

:   Key of exact length for algorithm (16 or 32 bytes).

iv

:   Initialization Vector (IV) (aka nonce) (16 bytes for ASCON-128 else 12 bytes).

aeadAlg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

Authenticated encryption algorithm.

#### Return Value

Ciphertext with tag appended in a byte array, or empty array on error.

#### Remarks

The output will be exactly 16 bytes longer than the input.

#### See Also

VB6/C equivalent: [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_EncryptWithTag_ByteByteByteByteAead_AlgorithmAead_Opts"></a>Aead.EncryptWithTag Method (Byte[], Byte[], Byte[], Byte[], Aead.Algorithm, Aead.Opts)

 Encrypt data using specified AEAD algorithm in one-off operation with AAD and options. The authentication tag is appended to the output. 

#### Syntax

[`C#`]

```
public static byte[] EncryptWithTag(
	byte[] input,
	byte[] key,
	byte[] iv,
	byte[] aad,
	Aead.Algorithm aeadAlg,
	Aead.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function EncryptWithTag ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aad As Byte(), _
	aeadAlg As Aead.Algorithm, _
	opts As Aead.Opts _
) As Byte()
```

#### Parameters

input

:   Input data to be encrypted.

key

:   Key of exact length for algorithm (16 or 32 bytes).

iv

:   Initialization Vector (IV) (aka nonce) (16 bytes for ASCON-128 else 12 bytes).

aad

:   Additional authenticated data (optional) - set as null to ignore.

aeadAlg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

Authenticated encryption algorithm.

opts

:   Type: [Aead.Opts](#T_Aead_Opts)  

Advanced options (optional). Use Opts.PrefixIV to prepend the IV to the output

#### Return Value

Ciphertext with tag appended in a byte array, or empty array on error.

#### Remarks

The output will either be exactly 16 bytes longer than the input, or 28/32 bytes longer if Aead.Opts.PrefixIV is used.

#### See Also

VB6/C equivalent: [`AEAD_EncryptWithTag`](#AEAD_EncryptWithTag)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_FinishDecrypt"></a>Aead.FinishDecrypt Method

 Finishes the authenticated decryption (in incremental mode) 

#### Syntax

[`C#`]

```
public bool FinishDecrypt()
```

[`VB.NET`]

```
Public Function FinishDecrypt As Boolean
```

#### Return Value

True if the decryption is authenticated; false otherwise.

#### Remarks

Must be preceded by StartDecrypt() and zero or more calls to Update(). May be followed by SetNonce() to begin processing another packet with the same key and algorithm; otherwise should be followed by Dispose().

#### See Also

VB6/C equivalent: [`AEAD_FinishDecrypt`](#AEAD_FinishDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_FinishEncrypt"></a>Aead.FinishEncrypt Method

 Finishes the authenticated encryption (in incremental mode) 

#### Syntax

[`C#`]

```
public byte[] FinishEncrypt()
```

[`VB.NET`]

```
Public Function FinishEncrypt As Byte()
```

#### Return Value

Authentication tag value

#### Remarks

Must be preceded by StartEncrypt() and zero or more calls to Update(). May be followed by SetNonce() to begin processing another packet with the same key and algorithm; otherwise should be followed by Dispose().

#### See Also

VB6/C equivalent: [`AEAD_FinishEncrypt`](#AEAD_FinishEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_InitKey"></a>Aead.InitKey Method

 Initializes the context with the key and algorithm ready for repeated incremental operations 

#### Syntax

[`C#`]

```
public int InitKey(
	byte[] key,
	Aead.Algorithm alg
)
```

[`VB.NET`]

```
Public Function InitKey ( _
	key As Byte(), _
	alg As Aead.Algorithm _
) As Integer
```

#### Parameters

key

:   Key of exact length for given algorithm (16 or 32 bytes).

alg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

AEAD algorithm to use

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

Must be followed by SetNonce(). Can be called at any time to cancel any previous incremental settings.

#### Example

[`C#`]

```
Aead o = Aead.Instance();
o.InitKey(key, alg);
o.SetNonce(nonce);
//...
o.Dispose();
```

#### See Also

VB6/C equivalent: [`AEAD_InitKey`](#AEAD_InitKey)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Instance"></a>Aead.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Aead Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Aead
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Mac"></a>Aead.Mac Method

 Compute Message Authentication Code (tag) over input data 

#### Syntax

[`C#`]

```
public static byte[] Mac(
	byte[] key,
	byte[] nonce,
	byte[] aad,
	Aead.Algorithm alg
)
```

[`VB.NET`]

```
Public Shared Function Mac ( _
	key As Byte(), _
	nonce As Byte(), _
	aad As Byte(), _
	alg As Aead.Algorithm _
) As Byte()
```

#### Parameters

key

:   Key of exact length for given algorithm (16 or 32 bytes).

nonce

:   Nonce of exact length for given algorithm (currently always 12 bytes)

aad

:   Data to be authenticated

alg

:   Type: [Aead.Algorithm](#T_Aead_Algorithm)  

AEAD algorithm to use

#### Return Value

Tag value in byte array, or empty array on error

#### Remarks

Use General.ErrorCode to find the code of the last error. This is equivalent to Aead.Encrypt with a zero-length plaintext input.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_SetNonce"></a>Aead.SetNonce Method

 Set the nonce (in incremental mode) 

#### Syntax

[`C#`]

```
public int SetNonce(
	byte[] nonce
)
```

[`VB.NET`]

```
Public Function SetNonce ( _
	nonce As Byte() _
) As Integer
```

#### Parameters

nonce

:   Nonce of exact length for given algorithm (currently always 12 bytes)

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

May be followed by zero or more calls to AddAAD() and then either StartEncrypt() or StartDecrypt().

#### See Also

VB6/C equivalent: [`AEAD_SetNonce`](#AEAD_SetNonce)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_StartDecrypt"></a>Aead.StartDecrypt Method

 Start authenticated decryption (in incremental mode) 

#### Syntax

[`C#`]

```
public int StartDecrypt(
	byte[] tagToCheck
)
```

[`VB.NET`]

```
Public Function StartDecrypt ( _
	tagToCheck As Byte() _
) As Integer
```

#### Parameters

tagToCheck

:   Tag value to be authenticated

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

May be followed by zero or more calls to Update() to decrypt data in chunks. Must eventually be followed by FinishDecrypt(). **Caution:** do not trust decrypted data until final authentication.

#### See Also

VB6/C equivalent: [`AEAD_StartDecrypt`](#AEAD_StartDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_StartEncrypt"></a>Aead.StartEncrypt Method

 Start authenticated encryption (in incremental mode) 

#### Syntax

[`C#`]

```
public int StartEncrypt()
```

[`VB.NET`]

```
Public Function StartEncrypt As Integer
```

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

May be followed by zero or more calls to Update() to encrypt data in chunks. Must eventually be followed by FinishEncrypt().

#### See Also

VB6/C equivalent: [`AEAD_StartEncrypt`](#AEAD_StartEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_Update"></a>Aead.Update Method

 Encrypts or decrypts a chunk of input (in incremental mode) 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] input
)
```

[`VB.NET`]

```
Public Function Update ( _
	input As Byte() _
) As Byte()
```

#### Parameters

input

:   Data to be encrypted or decrypted

#### Return Value

Encrypted or decrypted data in array of exactly the same length as input; or an empty array on error

#### Remarks

This function may be repeated to add data in chunks. The input data is encrypted or decrypted depending on the start mode set by a preceding call to StartEncrypt() or StartDecrypt(), respectively. It must eventually be followed by either FinishEncrypt() or FinishDecrypt(), which must match the start mode.

#### See Also

VB6/C equivalent: [`AEAD_Update`](#AEAD_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Decrypt_ByteByteModeByte"></a>Aes128.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_BytesMode`](#AES128_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Decrypt_StringStringModeString"></a>Aes128.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_HexMode`](#AES128_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Decrypt_StringStringModeStringEncodingBase"></a>Aes128.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_B64Mode`](#AES128_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Dispose"></a>Aes128.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`AES128_Final`](#AES128_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Encrypt_ByteByteModeByte"></a>Aes128.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_BytesMode`](#AES128_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Encrypt_StringStringModeString"></a>Aes128.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_HexMode`](#AES128_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Encrypt_StringStringModeStringEncodingBase"></a>Aes128.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_B64Mode`](#AES128_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileDecrypt_StringStringByteModeByte"></a>Aes128.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES128_File`](#AES128_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Aes128.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES128_FileExt`](#AES128_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileDecrypt_StringStringStringModeString"></a>Aes128.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES128_FileHex`](#AES128_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileEncrypt_StringStringByteModeByte"></a>Aes128.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES128_File`](#AES128_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Aes128.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES128_FileExt`](#AES128_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_FileEncrypt_StringStringStringModeString"></a>Aes128.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES128_FileHex`](#AES128_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_InitDecrypt_ByteModeByte"></a>Aes128.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES128_Init`](#AES128_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_InitDecrypt_StringModeString"></a>Aes128.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES128_InitHex`](#AES128_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_InitEncrypt_ByteModeByte"></a>Aes128.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 16 bytes (128 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES128_Init`](#AES128_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_InitEncrypt_StringModeString"></a>Aes128.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES128_InitHex`](#AES128_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Instance"></a>Aes128.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Aes128 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Aes128
```

#### Return Value

Single instance to class

#### Remarks

*CAUTION:* Instances of Aes128, Aes192 and Aes256 are not independent in the same thread.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Pad_Byte"></a>Aes128.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Pad_String"></a>Aes128.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Unpad_Byte"></a>Aes128.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Unpad_String"></a>Aes128.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Update_Byte"></a>Aes128.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_Update`](#AES128_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_Update_String"></a>Aes128.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES128_UpdateHex`](#AES128_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Decrypt_ByteByteModeByte"></a>Aes192.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_BytesMode`](#AES192_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Decrypt_StringStringModeString"></a>Aes192.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_HexMode`](#AES192_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Decrypt_StringStringModeStringEncodingBase"></a>Aes192.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_B64Mode`](#AES192_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Dispose"></a>Aes192.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`AES192_Final`](#AES192_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Encrypt_ByteByteModeByte"></a>Aes192.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_BytesMode`](#AES192_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Encrypt_StringStringModeString"></a>Aes192.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_HexMode`](#AES192_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Encrypt_StringStringModeStringEncodingBase"></a>Aes192.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_B64Mode`](#AES192_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileDecrypt_StringStringByteModeByte"></a>Aes192.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES192_File`](#AES192_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Aes192.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES192_FileExt`](#AES192_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileDecrypt_StringStringStringModeString"></a>Aes192.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES192_FileHex`](#AES192_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileEncrypt_StringStringByteModeByte"></a>Aes192.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES192_File`](#AES192_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Aes192.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES192_FileExt`](#AES192_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_FileEncrypt_StringStringStringModeString"></a>Aes192.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES192_FileHex`](#AES192_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_InitDecrypt_ByteModeByte"></a>Aes192.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES192_Init`](#AES192_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_InitDecrypt_StringModeString"></a>Aes192.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES192_InitHex`](#AES192_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_InitEncrypt_ByteModeByte"></a>Aes192.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES192_Init`](#AES192_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_InitEncrypt_StringModeString"></a>Aes192.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES192_InitHex`](#AES192_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Instance"></a>Aes192.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Aes192 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Aes192
```

#### Return Value

Single instance to class

#### Remarks

*CAUTION:* Instances of Aes128, Aes192 and Aes256 are not independent in the same thread.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Pad_Byte"></a>Aes192.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Pad_String"></a>Aes192.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Unpad_Byte"></a>Aes192.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Unpad_String"></a>Aes192.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Update_Byte"></a>Aes192.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_Update`](#AES192_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_Update_String"></a>Aes192.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES192_UpdateHex`](#AES192_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Decrypt_ByteByteModeByte"></a>Aes256.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_BytesMode`](#AES256_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Decrypt_StringStringModeString"></a>Aes256.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_HexMode`](#AES256_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Decrypt_StringStringModeStringEncodingBase"></a>Aes256.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_B64Mode`](#AES256_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Dispose"></a>Aes256.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`AES256_Final`](#AES256_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Encrypt_ByteByteModeByte"></a>Aes256.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_BytesMode`](#AES256_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Encrypt_StringStringModeString"></a>Aes256.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 16 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_HexMode`](#AES256_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Encrypt_StringStringModeStringEncodingBase"></a>Aes256.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 16 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_B64Mode`](#AES256_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileDecrypt_StringStringByteModeByte"></a>Aes256.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES256_File`](#AES256_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Aes256.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES256_FileExt`](#AES256_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileDecrypt_StringStringStringModeString"></a>Aes256.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES256_FileHex`](#AES256_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileEncrypt_StringStringByteModeByte"></a>Aes256.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES256_File`](#AES256_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Aes256.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`AES256_FileExt`](#AES256_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_FileEncrypt_StringStringStringModeString"></a>Aes256.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`AES256_FileHex`](#AES256_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_InitDecrypt_ByteModeByte"></a>Aes256.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES256_Init`](#AES256_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_InitDecrypt_StringModeString"></a>Aes256.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES256_InitHex`](#AES256_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_InitEncrypt_ByteModeByte"></a>Aes256.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 32 bytes (256 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 16 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES256_Init`](#AES256_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_InitEncrypt_StringModeString"></a>Aes256.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`AES256_InitHex`](#AES256_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Instance"></a>Aes256.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Aes256 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Aes256
```

#### Return Value

Single instance to class

#### Remarks

*CAUTION:* Instances of Aes128, Aes192 and Aes256 are not independent in the same thread.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Pad_Byte"></a>Aes256.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Pad_String"></a>Aes256.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Unpad_Byte"></a>Aes256.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Unpad_String"></a>Aes256.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Update_Byte"></a>Aes256.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_Update`](#AES256_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_Update_String"></a>Aes256.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (16 bytes)

#### See Also

VB6/C equivalent: [`AES256_UpdateHex`](#AES256_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Decrypt_ByteByteModeByte"></a>Blowfish.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_BytesMode`](#BLF_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Decrypt_StringStringModeString"></a>Blowfish.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_HexMode`](#BLF_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Decrypt_StringStringModeStringEncodingBase"></a>Blowfish.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_B64Mode`](#BLF_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Dispose"></a>Blowfish.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`BLF_Final`](#BLF_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Encrypt_ByteByteModeByte"></a>Blowfish.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_BytesMode`](#BLF_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Encrypt_StringStringModeString"></a>Blowfish.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_HexMode`](#BLF_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Encrypt_StringStringModeStringEncodingBase"></a>Blowfish.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_B64Mode`](#BLF_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileDecrypt_StringStringByteModeByte"></a>Blowfish.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`BLF_File`](#BLF_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Blowfish.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`BLF_FileExt`](#BLF_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileDecrypt_StringStringStringModeString"></a>Blowfish.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`BLF_FileHex`](#BLF_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileEncrypt_StringStringByteModeByte"></a>Blowfish.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`BLF_File`](#BLF_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Blowfish.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`BLF_FileExt`](#BLF_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_FileEncrypt_StringStringStringModeString"></a>Blowfish.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`BLF_FileHex`](#BLF_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_InitDecrypt_ByteModeByte"></a>Blowfish.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`BLF_Init`](#BLF_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_InitDecrypt_StringModeString"></a>Blowfish.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`BLF_InitHex`](#BLF_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_InitEncrypt_ByteModeByte"></a>Blowfish.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of length between 1 and 56 bytes (448 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`BLF_Init`](#BLF_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_InitEncrypt_StringModeString"></a>Blowfish.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`BLF_InitHex`](#BLF_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Instance"></a>Blowfish.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Blowfish Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Blowfish
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Pad_Byte"></a>Blowfish.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Pad_String"></a>Blowfish.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Unpad_Byte"></a>Blowfish.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Unpad_String"></a>Blowfish.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Update_Byte"></a>Blowfish.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_Update`](#BLF_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_Update_String"></a>Blowfish.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`BLF_UpdateHex`](#BLF_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_BlockBytes"></a>Cipher.BlockBytes Method

 Return the block size in bytes for a given cipher algorithm 

#### Syntax

[`C#`]

```
public static int BlockBytes(
	CipherAlgorithm alg
)
```

[`VB.NET`]

```
Public Shared Function BlockBytes ( _
	alg As CipherAlgorithm _
) As Integer
```

#### Parameters

alg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

#### Return Value

Block size in bytes

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Decrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts"></a>Cipher.Decrypt Method (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)

 Decrypt data in a byte array using the specified block cipher algorithm, mode and padding. 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As Byte()
```

#### Parameters

input

:   Input data to be decrypted

key

:   Key of exact length for block cipher algorithm

iv

:   Initialization Vector (IV) of exactly the block size or null for ECB mode, if not provided in input.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options (optional). Use Cipher.Opts.PrefixIV to expect the IV to be prepended at the start of the input.

#### Return Value

Decrypted plaintext in byte array or empty array on error

#### Remarks

Default padding is Pkcs5 for ECB and CBC mode and NoPad for all other modes. It is an error if the specified padding is not found after decryption.

#### See Also

VB6/C equivalent: [`CIPHER_DecryptBytes`](#CIPHER_DecryptBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Decrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts"></a>Cipher.Decrypt Method (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)

 Decrypt hex-encoded data using specified block cipher algorithm, mode and padding. 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	string ivHex,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	ivHex As String, _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exact key length

ivHex

:   Hex-encoded IV representing exact block length or "" for ECB mode

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher Algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options (optional). Use Cipher.Opts.PrefixIV to prepend the IV to the output.

#### Return Value

Decrypted plaintex in hex-encoded string or empty string on error

#### Remarks

Input data may be any even number of hex characters, but not zero. Default padding is Pkcs5 for ECB and CBC mode and NoPad for all other modes.

#### See Also

VB6/C equivalent: [`CIPHER_DecryptHex`](#CIPHER_DecryptHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Dispose"></a>Cipher.Dispose Method

 Dispose of this object and clear any stored data. 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`CIPHER_Final`](#CIPHER_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Encrypt_ByteByteByteCipherAlgorithmModePaddingCipher_Opts"></a>Cipher.Encrypt Method (Byte[], Byte[], Byte[], CipherAlgorithm, Mode, Padding, Cipher.Opts)

 Encrypt data in a byte array using the specified block cipher algorithm, mode and padding. 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As Byte()
```

#### Parameters

input

:   Input data to be encrypted

key

:   Key of exact length for block cipher algorithm

iv

:   Initialization Vector (IV) of exactly the block size or null for ECB mode, if not provided in input.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options (optional). Use Cipher.Opts.PrefixIV to prepend the IV to the output.

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

Default padding is Pkcs5 for ECB and CBC mode and NoPad for all other modes.

#### See Also

VB6/C equivalent: [`CIPHER_EncryptBytes`](#CIPHER_EncryptBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Encrypt_StringStringStringCipherAlgorithmModePaddingCipher_Opts"></a>Cipher.Encrypt Method (String, String, String, CipherAlgorithm, Mode, Padding, Cipher.Opts)

 Encrypt hex-encoded data using specified block cipher algorithm, mode and padding. 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	string ivHex,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	ivHex As String, _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exact key length

ivHex

:   Hex-encoded IV representing exact block length or "" for ECB mode

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher Algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options (optional). Use Cipher.Opts.PrefixIV to prepend the IV to the output.

#### Return Value

Encrypted ciphertext in hex-encoded string or empty string on error

#### Remarks

Input data may be any even number of hex characters, but not zero. Default padding is Pkcs5 for ECB and CBC mode and NoPad for all other modes.

#### See Also

VB6/C equivalent: [`CIPHER_EncryptHex`](#CIPHER_EncryptHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_FileDecrypt"></a>Cipher.FileDecrypt Method

 Decrypt a file with block cipher 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of of exact length for block cipher algorithm

iv

:   Initialization Vector (IV) of exactly the block size or null for ECB mode

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher Algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use (ECB and CBC modes only)

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options

#### Return Value

0 if successful or nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`CIPHER_FileDecrypt`](#CIPHER_FileDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_FileEncrypt"></a>Cipher.FileEncrypt Method

 Encrypt a file with block cipher 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode,
	Padding pad,
	Cipher.Opts opts
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode, _
	pad As Padding, _
	opts As Cipher.Opts _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of of exact length for block cipher algorithm

iv

:   Initialization Vector (IV) of exactly the block size or null for ECB mode

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher Algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

pad

:   Type: [Padding](#T_Padding)  

Padding method to use (ECB and CBC modes only)

opts

:   Type: [Cipher.Opts](#T_Cipher_Opts)  

Advanced options

#### Return Value

0 if successful or nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`CIPHER_FileEncrypt`](#CIPHER_FileEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_InitDecrypt_ByteByteCipherAlgorithmMode"></a>Cipher.InitDecrypt Method (Byte[], Byte[], CipherAlgorithm, Mode)

 Initializes with key, iv, algorithm and mode ready to start decrypting with repeated update operations. 

#### Syntax

[`C#`]

```
public bool InitDecrypt(
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode _
) As Boolean
```

#### Parameters

key

:   Key of exact length for block cipher algorithm.

iv

:   Initialization Vector (IV) of exactly the block size or null/Nothing for ECB mode.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

#### Return Value

True if successful, False if failed.

#### See Also

VB6/C equivalent: [`CIPHER_Init`](#CIPHER_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_InitDecrypt_StringStringCipherAlgorithmMode"></a>Cipher.InitDecrypt Method (String, String, CipherAlgorithm, Mode)

 Initializes with hex-encoded key, iv, algorithm and mode ready to start decrypting with repeated update operations. 

#### Syntax

[`C#`]

```
public bool InitDecrypt(
	string keyHex,
	string ivHex,
	CipherAlgorithm cipherAlg,
	Mode mode
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	ivHex As String, _
	cipherAlg As CipherAlgorithm, _
	mode As Mode _
) As Boolean
```

#### Parameters

keyHex

:   Hex-encoded key of exact length for block cipher algorithm.

ivHex

:   Hex-encoded Initialization Vector (IV) of exactly the block size or "" for ECB mode.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

#### Return Value

True if successful, False if failed.

#### See Also

VB6/C equivalent: [`CIPHER_InitHex`](#CIPHER_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_InitEncrypt_ByteByteCipherAlgorithmMode"></a>Cipher.InitEncrypt Method (Byte[], Byte[], CipherAlgorithm, Mode)

 Initializes with key, iv, algorithm and mode ready to start encrypting with repeated update operations. 

#### Syntax

[`C#`]

```
public bool InitEncrypt(
	byte[] key,
	byte[] iv,
	CipherAlgorithm cipherAlg,
	Mode mode
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	iv As Byte(), _
	cipherAlg As CipherAlgorithm, _
	mode As Mode _
) As Boolean
```

#### Parameters

key

:   Key of exact length for block cipher algorithm.

iv

:   Initialization Vector (IV) of exactly the block size or null/Nothing for ECB mode.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

#### Return Value

True if successful, False if failed.

#### See Also

VB6/C equivalent: [`CIPHER_Init`](#CIPHER_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_InitEncrypt_StringStringCipherAlgorithmMode"></a>Cipher.InitEncrypt Method (String, String, CipherAlgorithm, Mode)

 Initializes with hex-encoded key, iv, algorithm and mode ready to start encrypting with repeated update operations. 

#### Syntax

[`C#`]

```
public bool InitEncrypt(
	string keyHex,
	string ivHex,
	CipherAlgorithm cipherAlg,
	Mode mode
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	ivHex As String, _
	cipherAlg As CipherAlgorithm, _
	mode As Mode _
) As Boolean
```

#### Parameters

keyHex

:   Hex-encoded key of exact length for block cipher algorithm.

ivHex

:   Hex-encoded Initialization Vector (IV) of exactly the block size or "" for ECB mode.

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

#### Return Value

True if successful, False if failed.

#### See Also

VB6/C equivalent: [`CIPHER_InitHex`](#CIPHER_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Instance"></a>Cipher.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Cipher Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Cipher
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_KeyBytes"></a>Cipher.KeyBytes Method

 Return the key size in bytes for a given cipher algorithm 

#### Syntax

[`C#`]

```
public static int KeyBytes(
	CipherAlgorithm alg
)
```

[`VB.NET`]

```
Public Shared Function KeyBytes ( _
	alg As CipherAlgorithm _
) As Integer
```

#### Parameters

alg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Cipher algorithm

#### Return Value

Key size in bytes

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_KeyUnwrap"></a>Cipher.KeyUnwrap Method

 Unwraps (decrypts) key material with a key-encryption key 

#### Syntax

[`C#`]

```
public static byte[] KeyUnwrap(
	byte[] data,
	byte[] kek,
	CipherAlgorithm cipherAlg
)
```

[`VB.NET`]

```
Public Shared Function KeyUnwrap ( _
	data As Byte(), _
	kek As Byte(), _
	cipherAlg As CipherAlgorithm _
) As Byte()
```

#### Parameters

data

:   Wrapped key

kek

:   Key encryption key

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher to use for wrapping

#### Return Value

Unwrapped key material (or empty array on error)

#### See Also

VB6/C equivalent: [`CIPHER_KeyUnwrap`](#CIPHER_KeyUnwrap)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_KeyWrap"></a>Cipher.KeyWrap Method

 Wraps (encrypts) key material with a key-encryption key 

#### Syntax

[`C#`]

```
public static byte[] KeyWrap(
	byte[] data,
	byte[] kek,
	CipherAlgorithm cipherAlg
)
```

[`VB.NET`]

```
Public Shared Function KeyWrap ( _
	data As Byte(), _
	kek As Byte(), _
	cipherAlg As CipherAlgorithm _
) As Byte()
```

#### Parameters

data

:   Key material to be wrapped

kek

:   Key encryption key

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher to use for wrapping

#### Return Value

Wrapped key (or empty array on error)

#### See Also

VB6/C equivalent: [`CIPHER_KeyWrap`](#CIPHER_KeyWrap)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Pad_ByteCipherAlgorithmPadding"></a>Cipher.Pad Method (Byte[], CipherAlgorithm, Padding)

 Pad byte array for block cipher. 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] input,
	CipherAlgorithm cipherAlg,
	Padding pad
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	input As Byte(), _
	cipherAlg As CipherAlgorithm, _
	pad As Padding _
) As Byte()
```

#### Parameters

input

:   data to be padded

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher being used

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

#### Return Value

Padded data in byte array

#### See Also

VB6/C equivalent: [`PAD_BytesBlock`](#PAD_BytesBlock)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Pad_StringCipherAlgorithmPadding"></a>Cipher.Pad Method (String, CipherAlgorithm, Padding)

 Pads hex-encoded string for block cipher. 

#### Syntax

[`C#`]

```
public static string Pad(
	string inputHex,
	CipherAlgorithm cipherAlg,
	Padding pad
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	inputHex As String, _
	cipherAlg As CipherAlgorithm, _
	pad As Padding _
) As String
```

#### Parameters

inputHex

:   hex-encoded data to be padded

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher being used

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

#### Return Value

Padded data in hex-encoded string

#### See Also

VB6/C equivalent: [`PAD_HexBlock`](#PAD_HexBlock)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Unpad_ByteCipherAlgorithmPadding"></a>Cipher.Unpad Method (Byte[], CipherAlgorithm, Padding)

 Remove padding from an encryption block. 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] input,
	CipherAlgorithm cipherAlg,
	Padding pad
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	input As Byte(), _
	cipherAlg As CipherAlgorithm, _
	pad As Padding _
) As Byte()
```

#### Parameters

input

:   padded data

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher being used

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

#### Return Value

Unpadded data in byte array.

#### Remarks

Unless pad is NoPad, the unpadded output is *always* shorter than the padded input. An error is indicated by returning the *original* data.

#### See Also

VB6/C equivalent: [`PAD_UnpadBytes`](#PAD_UnpadBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Unpad_StringCipherAlgorithmPadding"></a>Cipher.Unpad Method (String, CipherAlgorithm, Padding)

 Remove padding from a hex-encoded encryption block. 

#### Syntax

[`C#`]

```
public static string Unpad(
	string inputHex,
	CipherAlgorithm cipherAlg,
	Padding pad
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	inputHex As String, _
	cipherAlg As CipherAlgorithm, _
	pad As Padding _
) As String
```

#### Parameters

inputHex

:   hex-encoded padded data

cipherAlg

:   Type: [CipherAlgorithm](#T_CipherAlgorithm)  

Block cipher being used

pad

:   Type: [Padding](#T_Padding)  

Padding method to use

#### Return Value

Unpadded data in hex-encoded string.

#### Remarks

Unless pad is NoPad, the unpadded output is *always* shorter than the padded input. An error is indicated by returning the *original* data.

#### See Also

VB6/C equivalent: [`PAD_UnpadHex`](#PAD_UnpadHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Update_Byte"></a>Cipher.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction. 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   Input data in byte array.

#### Return Value

Transformed data in byte array.

#### See Also

VB6/C equivalent: [`CIPHER_Update`](#CIPHER_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_Update_String"></a>Cipher.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string dataHex
)
```

[`VB.NET`]

```
Public Function Update ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   Hex-encoded input data

#### Return Value

Hex-encoded data

#### Remarks

For all modes, the length of the decoded input bytes **must** be an exact multiple of the cipher block length (8 or 16 bytes).

#### See Also

VB6/C equivalent: [`CIPHER_UpdateHex`](#CIPHER_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Bytes"></a>CipherStream.Bytes Method

 Enciphers data in array of bytes using specified stream cipher. 

#### Syntax

[`C#`]

```
public static byte[] Bytes(
	byte[] input,
	byte[] key,
	byte[] iv,
	int counter,
	CipherStream.Algorithm streamAlg
)
```

[`VB.NET`]

```
Public Shared Function Bytes ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	counter As Integer, _
	streamAlg As CipherStream.Algorithm _
) As Byte()
```

#### Parameters

input

:   Input data to be encrypted

key

:   Key

iv

:   Initialization Vector (IV, nonce) or null for Arcfour

counter

:   Counter value for ChaCha20 only, otherwise ignored. Use 0 for default.

streamAlg

:   Type: [CipherStream.Algorithm](#T_CipherStream_Algorithm)  

Stream cipher algorithm

#### Return Value

Ciphertext in byte array, or empty array on error

#### Remarks

* **Arcfour:** any length key; specify null for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.

#### See Also

VB6/C equivalent: [`CIPHER_StreamBytes`](#CIPHER_StreamBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Dispose"></a>CipherStream.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`CIPHER_StreamFinal`](#CIPHER_StreamFinal)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_File"></a>CipherStream.File Method

 Enciphers data in a file using specified stream cipher. 

#### Syntax

[`C#`]

```
public static int File(
	string fileOut,
	string fileIn,
	byte[] key,
	byte[] iv,
	int counter,
	CipherStream.Algorithm streamAlg
)
```

[`VB.NET`]

```
Public Shared Function File ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	iv As Byte(), _
	counter As Integer, _
	streamAlg As CipherStream.Algorithm _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key

iv

:   Initialization Vector (IV, nonce) or null for Arcfour

counter

:   Counter value for ChaCha20 only, otherwise ignored. Use 0 for default.

streamAlg

:   Type: [CipherStream.Algorithm](#T_CipherStream_Algorithm)  

Stream cipher algorithm

#### Return Value

0 if successful or nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same 

* **Arcfour:** any length key; specify null for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.

#### See Also

VB6/C equivalent: [`CIPHER_StreamFile`](#CIPHER_StreamFile)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Hex"></a>CipherStream.Hex Method

 Enciphers data in a hex-encoded string using specified stream cipher. 

#### Syntax

[`C#`]

```
public static string Hex(
	string inputHex,
	string keyHex,
	string ivHex,
	int counter,
	CipherStream.Algorithm streamAlg
)
```

[`VB.NET`]

```
Public Shared Function Hex ( _
	inputHex As String, _
	keyHex As String, _
	ivHex As String, _
	counter As Integer, _
	streamAlg As CipherStream.Algorithm _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key

ivHex

:   Hex-encoded Initialization Vector (IV, nonce) or "" for Arcfour

counter

:   Counter value for ChaCha20 only, otherwise ignored. Use 0 for default.

streamAlg

:   Type: [CipherStream.Algorithm](#T_CipherStream_Algorithm)  

Stream cipher algorithm

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

* **Arcfour:** any length key; specify null for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.

#### See Also

VB6/C equivalent: [`CIPHER_StreamHex`](#CIPHER_StreamHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Init"></a>CipherStream.Init Method

 Initializes the context ready for repeated operations of CipherStream.Update

#### Syntax

[`C#`]

```
public int Init(
	byte[] key,
	byte[] iv,
	int counter,
	CipherStream.Algorithm streamAlg
)
```

[`VB.NET`]

```
Public Function Init ( _
	key As Byte(), _
	iv As Byte(), _
	counter As Integer, _
	streamAlg As CipherStream.Algorithm _
) As Integer
```

#### Parameters

key

:   Key

iv

:   Initialization Vector (IV, nonce) or null for Arcfour

counter

:   Counter value for ChaCha20 only, otherwise ignored. Use 0 for default.

streamAlg

:   Type: [CipherStream.Algorithm](#T_CipherStream_Algorithm)  

Stream cipher algorithm

#### Return Value

0 if successful or nonzero [error code](#errorcodes)

#### Remarks

* **Arcfour:** any length key; specify null for IV.
* **Salsa20:** key must be exactly 16 or 32 bytes and IV exactly 8 bytes long.
* **ChaCha20:** key must be exactly 16 or 32 bytes and IV exactly 8, 12, or 16 bytes long. Counter is ignored if IV is 16 bytes.

#### See Also

VB6/C equivalent: [`CIPHER_StreamInit`](#CIPHER_StreamInit)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Instance"></a>CipherStream.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static CipherStream Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As CipherStream
```

#### Return Value

Single instance to class

#### Remarks

*CAUTION:* Instances of different algorithms are not independent in the same thread.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_Update"></a>CipherStream.Update Method

 Encrypts input using current context 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] input
)
```

[`VB.NET`]

```
Public Function Update ( _
	input As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data to be encrypted

#### Return Value

Encrypted data in array of exactly the same length as input; or an empty array on error

#### Remarks

Check CipherStream.ErrCode for error details

#### See Also

VB6/C equivalent: [`CIPHER_StreamUpdate`](#CIPHER_StreamUpdate)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_Base64Filter"></a>Cnv.Base64Filter Method

 Filters non-base64 characters from a string 

#### Syntax

[`C#`]

```
public static string Base64Filter(
	string s
)
```

[`VB.NET`]

```
Public Shared Function Base64Filter ( _
	s As String _
) As String
```

#### Parameters

s

:   String to be filtered

#### Return Value

Filtered string

#### Remarks

Valid base64 characters are [0-9A-Za-z+/=]

#### See Also

VB6/C equivalent: [`CNV_B64Filter`](#CNV_B64Filter)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_Base64FromHex"></a>Cnv.Base64FromHex Method

 Converts hexadecimal-encoded data into base64-encoded data 

#### Syntax

[`C#`]

```
public static string Base64FromHex(
	string s
)
```

[`VB.NET`]

```
Public Shared Function Base64FromHex ( _
	s As String _
) As String
```

#### Parameters

s

:   Hex-encoded data

#### Return Value

Base64-encoded data

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_FromBase64"></a>Cnv.FromBase64 Method

 Converts a base64-encoded string to an equivalent array of 8-bit unsigned integers. 

#### Syntax

[`C#`]

```
public static byte[] FromBase64(
	string s
)
```

[`VB.NET`]

```
Public Shared Function FromBase64 ( _
	s As String _
) As Byte()
```

#### Parameters

s

:   Base64-encoded data

#### Return Value

Data as array of bytes

#### See Also

VB6/C equivalent: [`CNV_BytesFromB64Str`](#CNV_BytesFromB64Str)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_FromHex"></a>Cnv.FromHex Method

 Converts a hexadecimal-encoded string to an equivalent array of 8-bit unsigned integers. 

#### Syntax

[`C#`]

```
public static byte[] FromHex(
	string s
)
```

[`VB.NET`]

```
Public Shared Function FromHex ( _
	s As String _
) As Byte()
```

#### Parameters

s

:   Hex-encoded data

#### Return Value

Data as array of bytes

#### See Also

VB6/C equivalent: [`CNV_BytesFromHexStr`](#CNV_BytesFromHexStr)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_HexFilter"></a>Cnv.HexFilter Method

 Filters non-hexadecimal characters from a string 

#### Syntax

[`C#`]

```
public static string HexFilter(
	string s
)
```

[`VB.NET`]

```
Public Shared Function HexFilter ( _
	s As String _
) As String
```

#### Parameters

s

:   String to be filtered

#### Return Value

Filtered string

#### Remarks

Valid hex characters are [0-9A-Fa-f]

#### See Also

VB6/C equivalent: [`CNV_HexFilter`](#CNV_HexFilter)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_HexFromBase64"></a>Cnv.HexFromBase64 Method

 Converts base64-encoded data into hexadecimal-encoded data 

#### Syntax

[`C#`]

```
public static string HexFromBase64(
	string s
)
```

[`VB.NET`]

```
Public Shared Function HexFromBase64 ( _
	s As String _
) As String
```

#### Parameters

s

:   Base64-encoded data

#### Return Value

Hex-encoded data

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_ShortPathName"></a>Cnv.ShortPathName Method

 Retrieve the Windows short path form of the specified path. 

#### Syntax

[`C#`]

```
public static string ShortPathName(
	string pathName
)
```

[`VB.NET`]

```
Public Shared Function ShortPathName ( _
	pathName As String _
) As String
```

#### Parameters

pathName

:   File path name.

#### Return Value

Windows short path name of file or the empty string if file does not exist.

#### Remarks

Windows platforms only. The file path must exist. The short path name is guaranteed to be ASCII.

#### See Also

VB6/C equivalent: [`CNV_ShortPathName`](#CNV_ShortPathName)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_StringFromBase64"></a>Cnv.StringFromBase64 Method

 Converts a base64-encoded string into a text string 

#### Syntax

[`C#`]

```
public static string StringFromBase64(
	string s
)
```

[`VB.NET`]

```
Public Shared Function StringFromBase64 ( _
	s As String _
) As String
```

#### Parameters

s

:   Base64-encoded data

#### Return Value

String value

#### Remarks

Uses the 'Default' encoding for the system's current ANSI code page

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_StringFromHex"></a>Cnv.StringFromHex Method

 Converts a hexadecimal-encoded string into a text string 

#### Syntax

[`C#`]

```
public static string StringFromHex(
	string s
)
```

[`VB.NET`]

```
Public Shared Function StringFromHex ( _
	s As String _
) As String
```

#### Parameters

s

:   Hex-encoded data

#### Return Value

String value

#### Remarks

Uses the 'Default' encoding for the system's current ANSI code page

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_ToBase64_Byte"></a>Cnv.ToBase64 Method (Byte[])

 Converts 8-bit binary data to equivalent base64-encoded string format 

#### Syntax

[`C#`]

```
public static string ToBase64(
	byte[] binaryData
)
```

[`VB.NET`]

```
Public Shared Function ToBase64 ( _
	binaryData As Byte() _
) As String
```

#### Parameters

binaryData

:   binary data

#### Return Value

Base64-encoded string

#### See Also

VB6/C equivalent: [`CNV_B64StrFromBytes`](#CNV_B64StrFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_ToBase64_String"></a>Cnv.ToBase64 Method (String)

 Converts a string of ANSI characters to equivalent base64-encoded string format 

#### Syntax

[`C#`]

```
public static string ToBase64(
	string s
)
```

[`VB.NET`]

```
Public Shared Function ToBase64 ( _
	s As String _
) As String
```

#### Parameters

s

:   String of data to be encoded

#### Return Value

Base64-encoded data

#### Remarks

Uses the 'Default' encoding for the system's current ANSI code page

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_ToHex_Byte"></a>Cnv.ToHex Method (Byte[])

 Converts 8-bit binary data to equivalent hexadecimal string format 

#### Syntax

[`C#`]

```
public static string ToHex(
	byte[] binaryData
)
```

[`VB.NET`]

```
Public Shared Function ToHex ( _
	binaryData As Byte() _
) As String
```

#### Parameters

binaryData

:   binary data

#### Return Value

Hex-encoded string

#### See Also

VB6/C equivalent: [`CNV_HexStrFromBytes`](#CNV_HexStrFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cnv_ToHex_String"></a>Cnv.ToHex Method (String)

 Converts a string of ANSI characters to equivalent hexadecimal string format 

#### Syntax

[`C#`]

```
public static string ToHex(
	string s
)
```

[`VB.NET`]

```
Public Shared Function ToHex ( _
	s As String _
) As String
```

#### Parameters

s

:   String of data to be encoded

#### Return Value

Hex-encoded data

#### Remarks

Uses the 'Default' encoding for the system's current ANSI code page

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Compr_Compress"></a>Compr.Compress Method

 Compress data using compression algorithm. 

#### Syntax

[`C#`]

```
public static byte[] Compress(
	byte[] data,
	ComprAlgorithm comprAlg
)
```

[`VB.NET`]

```
Public Shared Function Compress ( _
	data As Byte(), _
	comprAlg As ComprAlgorithm _
) As Byte()
```

#### Parameters

data

:   Data to be compressed.

comprAlg

:   Type: [ComprAlgorithm](#T_ComprAlgorithm)  

Compression algorithm.

#### Return Value

Compressed data, or an empty array on error.

#### See Also

VB6/C equivalent: [`COMPR_Compress`](#COMPR_Compress)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Compr_Uncompress"></a>Compr.Uncompress Method

 Uncompress data using compression algorithm. 

#### Syntax

[`C#`]

```
public static byte[] Uncompress(
	byte[] data,
	ComprAlgorithm comprAlg
)
```

[`VB.NET`]

```
Public Shared Function Uncompress ( _
	data As Byte(), _
	comprAlg As ComprAlgorithm _
) As Byte()
```

#### Parameters

data

:   Compressed data to be uncompressed.

comprAlg

:   Type: [ComprAlgorithm](#T_ComprAlgorithm)  

Compression algorithm.

#### Return Value

Uncompressed data, or an empty array on error.

#### Remarks

An empty array may also be returned in the trivial case that the original data was the empty array itself.

#### See Also

VB6/C equivalent: [`COMPR_Uncompress`](#COMPR_Uncompress)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Crc_Data_Byte"></a>Crc.Data Method (Byte[])

 Computes CRC-32 checksum for data 

#### Syntax

[`C#`]

```
public static int Data(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Data ( _
	data As Byte() _
) As Integer
```

#### Parameters

data

:   input data

#### Return Value

Value of CRC-32 checksum

#### See Also

VB6/C equivalent: [`CRC_Bytes`](#CRC_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Crc_Data_String"></a>Crc.Data Method (String)

 Computes CRC-32 checksum for a string 

#### Syntax

[`C#`]

```
public static int Data(
	string Str
)
```

[`VB.NET`]

```
Public Shared Function Data ( _
	Str As String _
) As Integer
```

#### Parameters

Str

:   input data

#### Return Value

Value of CRC-32 checksum

#### See Also

VB6/C equivalent: [`CRC_String`](#CRC_String)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Crc_File"></a>Crc.File Method

 Computes CRC-32 checksum for a file 

#### Syntax

[`C#`]

```
public static int File(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function File ( _
	fileName As String _
) As Integer
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Value of CRC-32 checksum

#### Remarks

If return value is zero, the file could not be found or read

#### See Also

VB6/C equivalent: [`CRC_File`](#CRC_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_CheckKey_Byte"></a>Des.CheckKey Method (Byte[])

 Verifies that no part of the key is a weak or semi-weak DES key. 

#### Syntax

[`C#`]

```
public static int CheckKey(
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function CheckKey ( _
	key As Byte() _
) As Integer
```

#### Parameters

key

:   Key to check

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_CheckKey`](#DES_CheckKey)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_CheckKey_String"></a>Des.CheckKey Method (String)

 Verifies that no part of the key is a weak or semi-weak DES key. 

#### Syntax

[`C#`]

```
public static int CheckKey(
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function CheckKey ( _
	keyHex As String _
) As Integer
```

#### Parameters

keyHex

:   Hex-encoded key to check

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_CheckKeyHex`](#DES_CheckKeyHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Decrypt_ByteByteModeByte"></a>Des.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_BytesMode`](#DES_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Decrypt_StringStringModeString"></a>Des.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_HexMode`](#DES_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Decrypt_StringStringModeStringEncodingBase"></a>Des.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_B64Mode`](#DES_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Dispose"></a>Des.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`DES_Final`](#DES_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Encrypt_ByteByteModeByte"></a>Des.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_BytesMode`](#DES_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Encrypt_StringStringModeString"></a>Des.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_HexMode`](#DES_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Encrypt_StringStringModeStringEncodingBase"></a>Des.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_B64Mode`](#DES_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileDecrypt_StringStringByteModeByte"></a>Des.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`DES_File`](#DES_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Des.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`DES_FileExt`](#DES_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileDecrypt_StringStringStringModeString"></a>Des.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`DES_FileHex`](#DES_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileEncrypt_StringStringByteModeByte"></a>Des.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`DES_File`](#DES_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Des.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`DES_FileExt`](#DES_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_FileEncrypt_StringStringStringModeString"></a>Des.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`DES_FileHex`](#DES_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_InitDecrypt_ByteModeByte"></a>Des.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_Init`](#DES_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_InitDecrypt_StringModeString"></a>Des.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_InitHex`](#DES_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_InitEncrypt_ByteModeByte"></a>Des.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 8 bytes (64 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_Init`](#DES_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_InitEncrypt_StringModeString"></a>Des.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_InitHex`](#DES_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Instance"></a>Des.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Des Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Des
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Pad_Byte"></a>Des.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Pad_String"></a>Des.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Unpad_Byte"></a>Des.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Unpad_String"></a>Des.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Update_Byte"></a>Des.Update Method (Byte[])

 Transforms byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_Update`](#DES_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_Update_String"></a>Des.Update Method (String)

 Transforms hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`DES_UpdateHex`](#DES_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_Decrypt"></a>Gcm.Decrypt Method

 Decrypt input using AES-GCM in one-off operation 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	byte[] iv,
	byte[] aad,
	byte[] tag
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aad As Byte(), _
	tag As Byte() _
) As Byte()
```

#### Parameters

input

:   Cipher text input data

key

:   Key: must be exactly 16, 24 or 32 bytes long.

iv

:   Initialization vector.

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

tag

:   Tag value (required)

#### Return Value

Decrypted plaintext in byte array, or empty array on error

#### Remarks

Use General.ErrorCode to find the code of the last error.

#### See Also

VB6/C equivalent: [`GCM_Decrypt`](#GCM_Decrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_Dispose"></a>Gcm.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`GCM_FinishKey`](#GCM_FinishKey)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_Encrypt"></a>Gcm.Encrypt Method

 Encrypt input using AES-GCM in one-off operation 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	out byte[] tag,
	byte[] input,
	byte[] key,
	byte[] iv,
	byte[] aad
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	<OutAttribute> ByRef tag As Byte(), _
	input As Byte(), _
	key As Byte(), _
	iv As Byte(), _
	aad As Byte() _
) As Byte()
```

#### Parameters

tag

:   To receive the output authentication tag value. Always returned exactly 16 bytes long. You may truncate as desired. This is a by-reference parameter. There is no need to initialize (but the VB compiler may complain).

input

:   Plain text input data

key

:   Key: must be exactly 16, 24 or 32 bytes long.

iv

:   Initialization vector: can be any length but 12 bytes is recommended.

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

#### Return Value

Encrypted ciphertext in byte array, or empty array on error

#### Remarks

If you just require a GMAC value, use Gcm.Gmac Use General.ErrorCode to find the code of the last error.

#### See Also

VB6/C equivalent: [`GCM_Encrypt`](#GCM_Encrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_Gmac"></a>Gcm.Gmac Method

 Compute GMAC using AES-GCM in one-off operation 

#### Syntax

[`C#`]

```
public static byte[] Gmac(
	byte[] key,
	byte[] iv,
	byte[] msg
)
```

[`VB.NET`]

```
Public Shared Function Gmac ( _
	key As Byte(), _
	iv As Byte(), _
	msg As Byte() _
) As Byte()
```

#### Parameters

key

:   Key: must be exactly 16, 24 or 32 bytes long.

iv

:   Initialization vector

msg

:   Message data

#### Return Value

GMAC value in 16-byte array, or empty array on error

#### Remarks

Use General.ErrorCode to find the code of the last error.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_InitKey"></a>Gcm.InitKey Method

 Initializes the context with the key ready for repeated operations of Gcm.NextEncrypt, Gcm.NextDecrypt, or Gcm.NextGmac. 

#### Syntax

[`C#`]

```
public int InitKey(
	byte[] key
)
```

[`VB.NET`]

```
Public Function InitKey ( _
	key As Byte() _
) As Integer
```

#### Parameters

key

:   Key: must be exactly 16, 24 or 32 bytes long.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

Once a key has been set up, Gcm.NextEncrypt, Gcm.NextDecrypt and Gcm.NextGmac can be used independently.

#### Example

[`C#`]

```
Gcm o = Instance();
o.InitKey(key);
byte[] tag = new byte[16];
byte[] ct = o.NextEncrypt(tag, pt, iv, aad);
//...
o.Dispose();
```

#### See Also

VB6/C equivalent: [`GCM_InitKey`](#GCM_InitKey)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_Instance"></a>Gcm.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Gcm Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Gcm
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_NextDecrypt"></a>Gcm.NextDecrypt Method

 Carries out the GCM decryption operation using the key set up by an earlier call to Gcm.InitKey. 

#### Syntax

[`C#`]

```
public byte[] NextDecrypt(
	byte[] input,
	byte[] iv,
	byte[] aad,
	byte[] tag
)
```

[`VB.NET`]

```
Public Function NextDecrypt ( _
	input As Byte(), _
	iv As Byte(), _
	aad As Byte(), _
	tag As Byte() _
) As Byte()
```

#### Parameters

input

:   Cipher text input data

iv

:   Initialization vector.

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

tag

:   Tag value (required)

#### Return Value

Decrypted plaintext in byte array, or empty array on error

#### See Also

VB6/C equivalent: [`GCM_NextDecrypt`](#GCM_NextDecrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_NextEncrypt"></a>Gcm.NextEncrypt Method

 Carries out the GCM encryption operation using the key set up by an earlier call to Gcm.InitKey. 

#### Syntax

[`C#`]

```
public byte[] NextEncrypt(
	out byte[] tag,
	byte[] input,
	byte[] iv,
	byte[] aad
)
```

[`VB.NET`]

```
Public Function NextEncrypt ( _
	<OutAttribute> ByRef tag As Byte(), _
	input As Byte(), _
	iv As Byte(), _
	aad As Byte() _
) As Byte()
```

#### Parameters

tag

:   Tag value, always returned exactly 16 bytes long. You may truncate as desired.

input

:   Plain text input data

iv

:   Initialization vector: can be any length but 12 bytes is recommended.

aad

:   Additional authentication data (optional). Pass null/Nothing to ignore.

#### Return Value

Encrypted ciphertext in byte array, or empty array on error

#### See Also

VB6/C equivalent: [`GCM_NextEncrypt`](#GCM_NextEncrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_NextGmac"></a>Gcm.NextGmac Method

 Carries out the GMAC operation using the key set up by an earlier call to Gcm.InitKey. 

#### Syntax

[`C#`]

```
public byte[] NextGmac(
	byte[] iv,
	byte[] msg
)
```

[`VB.NET`]

```
Public Function NextGmac ( _
	iv As Byte(), _
	msg As Byte() _
) As Byte()
```

#### Parameters

iv

:   Initialization vector.

msg

:   Message data.

#### Return Value

GMAC value in byte array, or empty array on error

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_CompileTime"></a>General.CompileTime Method

 Gets date and time the CryptoSys DLL module was last compiled 

#### Syntax

[`C#`]

```
public static string CompileTime()
```

[`VB.NET`]

```
Public Shared Function CompileTime As String
```

#### Return Value

Date and time string

#### See Also

VB6/C equivalent: [`API_CompileTime`](#API_CompileTime)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_ErrorCode"></a>General.ErrorCode Method

 Returns the [error code](#errorcodes) of the error that occurred when calling the last function 

#### Syntax

[`C#`]

```
public static int ErrorCode()
```

[`VB.NET`]

```
Public Shared Function ErrorCode As Integer
```

#### Return Value

Error code

#### Remarks

Not all functions set this value.

#### See Also

VB6/C equivalent: [`API_ErrorCode`](#API_ErrorCode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_ErrorLookup"></a>General.ErrorLookup Method

 Looks up [error code](#errorcodes) 

#### Syntax

[`C#`]

```
public static string ErrorLookup(
	int errCode
)
```

[`VB.NET`]

```
Public Shared Function ErrorLookup ( _
	errCode As Integer _
) As String
```

#### Parameters

errCode

:   Code number

#### Return Value

Corresponding error message

#### See Also

VB6/C equivalent: [`API_ErrorLookup`](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_FormatErrorMessage"></a>General.FormatErrorMessage Method

 Return an error message string for the last error. 

#### Syntax

[`C#`]

```
public static string FormatErrorMessage(
	int errCode
)
```

[`VB.NET`]

```
Public Shared Function FormatErrorMessage ( _
	errCode As Integer _
) As String
```

#### Parameters

errCode

:   Error code returned by last call (*optional*)

#### Return Value

Error message as a string Error ({errCode}): {errorlookup}[: {lasterror}]

#### See Also

VB6/C equivalent: [`API_ErrorLookup`](#API_ErrorLookup)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_IsWin64"></a>General.IsWin64 Method

 Returns flag indicating the platform of the core DLL. 

#### Syntax

[`C#`]

```
public static int IsWin64()
```

[`VB.NET`]

```
Public Shared Function IsWin64 As Integer
```

#### Return Value

1 if platform is Win64 (X64) or 0 if Win32

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_LicenceType"></a>General.LicenceType Method

 Gets licence type. 

#### Syntax

[`C#`]

```
public static char LicenceType()
```

[`VB.NET`]

```
Public Shared Function LicenceType As Char
```

#### Return Value

D=Developer T=Trial

#### See Also

VB6/C equivalent: [`API_LicenceType`](#API_LicenceType)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_ModuleInfo"></a>General.ModuleInfo Method

 Get additional information about the core DLL module. 

#### Syntax

[`C#`]

```
public static string ModuleInfo()
```

[`VB.NET`]

```
Public Shared Function ModuleInfo As String
```

#### Return Value

[Missing <returns> documentation for M:CryptoSysAPI.General.ModuleInfo]

#### See Also

VB6/C equivalent: [`API_ModuleInfo`](#API_ModuleInfo)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_ModuleName"></a>General.ModuleName Method

 Gets full path name of core CryptoSys DLL module 

#### Syntax

[`C#`]

```
public static string ModuleName()
```

[`VB.NET`]

```
Public Shared Function ModuleName As String
```

#### Return Value

File name

#### See Also

VB6/C equivalent: [`API_ModuleName`](#API_ModuleName)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_NetVersion"></a>General.NetVersion Method

 Return the version of this .NET module. 

#### Syntax

[`C#`]

```
public static string NetVersion()
```

[`VB.NET`]

```
Public Shared Function NetVersion As String
```

#### Return Value

Version string, e.g. "03.05.00"

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_Platform"></a>General.Platform Method

 Return the platform the core DLL was compiled for. 

#### Syntax

[`C#`]

```
public static string Platform()
```

[`VB.NET`]

```
Public Shared Function Platform As String
```

#### Return Value

"Win32" or "X64"

#### See Also

VB6/C equivalent: [`API_Platform`](#API_Platform)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_PowerUpTests"></a>General.PowerUpTests Method

 Performs FIPS-140-2 start-up tests 

#### Syntax

[`C#`]

```
public static int PowerUpTests()
```

[`VB.NET`]

```
Public Shared Function PowerUpTests As Integer
```

#### Return Value

Zero on success

#### See Also

VB6/C equivalent: [`API_PowerUpTests`](#API_PowerUpTests)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_General_Version"></a>General.Version Method

 Returns version number of core CryptoSys DLL. 

#### Syntax

[`C#`]

```
public static int Version()
```

[`VB.NET`]

```
Public Shared Function Version As Integer
```

#### Return Value

Version number in form Major * 10000 + Minor * 100 + Release

#### Remarks

For example, version 5.2.1 returns 50201

#### See Also

VB6/C equivalent: [`API_Version`](#API_Version)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_AddData_Byte"></a>Hash.AddData Method (Byte[])

 Adds a chunk of data in a byte array to be digested by the Hash object. 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`HASH_AddBytes`](#HASH_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_AddData_String"></a>Hash.AddData Method (String)

 Adds a chunk of data in a string to be digested by the Hash object. 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`HASH_AddBytes`](#HASH_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_BytesFromBytes"></a>Hash.BytesFromBytes Method

 Computes hash value in byte format of byte input 

#### Syntax

[`C#`]

```
public static byte[] BytesFromBytes(
	byte[] message,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function BytesFromBytes ( _
	message As Byte(), _
	hashAlg As HashAlgorithm _
) As Byte()
```

#### Parameters

message

:   Message data in byte format

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used

#### Return Value

Message digest in byte format

#### See Also

VB6/C equivalent: [`HASH_Bytes`](#HASH_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_BytesFromFile"></a>Hash.BytesFromFile Method

 Computes hash value in byte format of a binary file 

#### Syntax

[`C#`]

```
public static byte[] BytesFromFile(
	string fileName,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function BytesFromFile ( _
	fileName As String, _
	hashAlg As HashAlgorithm _
) As Byte()
```

#### Parameters

fileName

:   Name of file containing message data

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used (ASCON-HASH not supported in file mode)

#### Return Value

Message digest in byte format

#### See Also

VB6/C equivalent: [`HASH_File`](#HASH_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_Dispose"></a>Hash.Dispose Method

 Dispose of this object and clear any stored data. 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_Final"></a>Hash.Final Method

 Computes final message digest for the Hash object. 

#### Syntax

[`C#`]

```
public byte[] Final()
```

[`VB.NET`]

```
Public Function Final As Byte()
```

#### Return Value

Digest value in a byte array.

#### Remarks

This operation delivers the final result of Add operations since the Hash.Init() operation. Once called, the Hash object is invalid.

#### See Also

VB6/C equivalent: [`HASH_Final`](#HASH_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromBits"></a>Hash.HexFromBits Method

 Computes hash value in hex format from bit-oriented input 

#### Syntax

[`C#`]

```
public static string HexFromBits(
	byte[] data,
	int dataBitLen,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromBits ( _
	data As Byte(), _
	dataBitLen As Integer, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

data

:   Bit-oriented message data in byte array

dataBitLen

:   Number of bits in data to digest

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used (SHA-1, SHA-2, SHA-3 only)

#### Return Value

Message digest in hex-encoded format

#### Remarks

Only the SHA families of hash functions (SHA-1, SHA-2, SHA-3) are supported in bit-oriented mode

#### See Also

VB6/C equivalent: [`HASH_HexFromBits`](#HASH_HexFromBits)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromBytes"></a>Hash.HexFromBytes Method

 Computes hash value in hex format of byte input 

#### Syntax

[`C#`]

```
public static string HexFromBytes(
	byte[] message,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromBytes ( _
	message As Byte(), _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

message

:   Message data in byte format

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used

#### Return Value

Message digest in hex-encoded format

#### See Also

VB6/C equivalent: [`HASH_HexFromBytes`](#HASH_HexFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromFile"></a>Hash.HexFromFile Method

 Computes hash value in hex format of a binary file 

#### Syntax

[`C#`]

```
public static string HexFromFile(
	string fileName,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromFile ( _
	fileName As String, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

fileName

:   Name of file containing message data

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used (ASCON-HASH not supported in file mode)

#### Return Value

Message digest in hex-encoded format

#### See Also

VB6/C equivalent: [`HASH_HexFromFile`](#HASH_HexFromFile)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromHex"></a>Hash.HexFromHex Method

 Computes hash value in hex format of hex-encoded input 

#### Syntax

[`C#`]

```
public static string HexFromHex(
	string messageHex,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromHex ( _
	messageHex As String, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

messageHex

:   Message data in hex-encoded format

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used

#### Return Value

Message digest in hex-encoded format

#### See Also

VB6/C equivalent: [`HASH_HexFromHex`](#HASH_HexFromHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromString"></a>Hash.HexFromString Method

 Computes hash value in hex format of string input 

#### Syntax

[`C#`]

```
public static string HexFromString(
	string message,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromString ( _
	message As String, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

message

:   Message data string

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used

#### Return Value

Message digest in hex-encoded format

#### See Also

VB6/C equivalent: [`HASH_HexFromBytes`](#HASH_HexFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_HexFromTextFile"></a>Hash.HexFromTextFile Method

 Computes hash value in hex format of a text file, treating CR-LF pairs as a single LF 

#### Syntax

[`C#`]

```
public static string HexFromTextFile(
	string fileName,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromTextFile ( _
	fileName As String, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

fileName

:   Name of file containing message data

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used (ASCON-HASH not supported in file mode)

#### Return Value

Message digest in hex format

#### Remarks

Use for passing message digest of file between Unix and Windows systems.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_Init"></a>Hash.Init Method

 Initialises the Hash object ready for repeated incremental operations. 

#### Syntax

[`C#`]

```
public bool Init(
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Function Init ( _
	hashAlg As HashAlgorithm _
) As Boolean
```

#### Parameters

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to be used (SHA-1, SHA-2, SHA-3 only)

#### Return Value

True if successful, False if failed

#### Remarks

Only the SHA families of hash functions (SHA-1, SHA-2, SHA-3) are supported in object mode.

#### See Also

VB6/C equivalent: [`HASH_Init`](#HASH_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_Instance"></a>Hash.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Hash Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Hash
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_LengthInBytes"></a>Hash.LengthInBytes Method

 Returns the number of bytes in the message digest for the given hash algorithm. 

#### Syntax

[`C#`]

```
public static int LengthInBytes(
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function LengthInBytes ( _
	hashAlg As HashAlgorithm _
) As Integer
```

#### Parameters

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm

#### Return Value

The length in bytes of the message digest output.

#### See Also

VB6/C equivalent: [`HASH_DigestLength`](#HASH_DigestLength)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_Reset"></a>Hash.Reset Method

 Resets the context of the Hash object. 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes).

#### See Also

VB6/C equivalent: [`HASH_Reset`](#HASH_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_AddData_Byte"></a>Mac.AddData Method (Byte[])

 Adds a chunk of data in a byte array to be authenticated by the Mac object. 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`MAC_AddBytes`](#MAC_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_AddData_String"></a>Mac.AddData Method (String)

 Adds a chunk of data in a string to be authenticated by the Mac object. 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`MAC_AddBytes`](#MAC_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_BytesFromBytes"></a>Mac.BytesFromBytes Method

 Computes MAC value in byte format from byte input 

#### Syntax

[`C#`]

```
public static byte[] BytesFromBytes(
	byte[] message,
	byte[] key,
	MacAlgorithm macAlg
)
```

[`VB.NET`]

```
Public Shared Function BytesFromBytes ( _
	message As Byte(), _
	key As Byte(), _
	macAlg As MacAlgorithm _
) As Byte()
```

#### Parameters

message

:   Message to be signed in byte format

key

:   Key in byte format

macAlg

:   Type: [MacAlgorithm](#T_MacAlgorithm)  

MAC algorithm to be used

#### Return Value

MAC in byte format

#### See Also

VB6/C equivalent: [`MAC_Bytes`](#MAC_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_Dispose"></a>Mac.Dispose Method

 Dispose of this object and clear any stored data. 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_Final"></a>Mac.Final Method

 Computes final MAC value for the Mac object. 

#### Syntax

[`C#`]

```
public byte[] Final()
```

[`VB.NET`]

```
Public Function Final As Byte()
```

#### Return Value

MAC value in a byte array.

#### Remarks

This operation delivers the final result of Add operations since the Mac.Init() operation. Once called, the Mac object is invalid.

#### See Also

VB6/C equivalent: [`MAC_Final`](#MAC_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_HexFromBytes"></a>Mac.HexFromBytes Method

 Computes MAC value in hex-encoded format from byte input 

#### Syntax

[`C#`]

```
public static string HexFromBytes(
	byte[] message,
	byte[] key,
	MacAlgorithm macAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromBytes ( _
	message As Byte(), _
	key As Byte(), _
	macAlg As MacAlgorithm _
) As String
```

#### Parameters

message

:   Message to be signed in byte format

key

:   Key in byte format

macAlg

:   Type: [MacAlgorithm](#T_MacAlgorithm)  

MAC algorithm to be used

#### Return Value

MAC in hex-encoded format

#### See Also

VB6/C equivalent: [`MAC_HexFromBytes`](#MAC_HexFromBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_HexFromHex"></a>Mac.HexFromHex Method

 Computes MAC value in hex-encoded format from hex-encoded input 

#### Syntax

[`C#`]

```
public static string HexFromHex(
	string messageHex,
	string keyHex,
	MacAlgorithm macAlg
)
```

[`VB.NET`]

```
Public Shared Function HexFromHex ( _
	messageHex As String, _
	keyHex As String, _
	macAlg As MacAlgorithm _
) As String
```

#### Parameters

messageHex

:   Message to be signed in hex-encoded format

keyHex

:   Key in hex-encoded format

macAlg

:   Type: [MacAlgorithm](#T_MacAlgorithm)  

MAC algorithm to be used

#### Return Value

MAC in hex-encoded format

#### See Also

VB6/C equivalent: [`MAC_HexFromHex`](#MAC_HexFromHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_Init"></a>Mac.Init Method

 Initialises the Mac object ready for repeated incremental operations. 

#### Syntax

[`C#`]

```
public bool Init(
	byte[] key,
	MacAlgorithm macAlg
)
```

[`VB.NET`]

```
Public Function Init ( _
	key As Byte(), _
	macAlg As MacAlgorithm _
) As Boolean
```

#### Parameters

key

:   Key

macAlg

:   Type: [MacAlgorithm](#T_MacAlgorithm)  

HMAC algorithm to be used.

#### Return Value

True if successful, False if failed.

#### Remarks

Only the HMAC-SHA-1 and HMAC-SHA-2 families of MAC algorithms are currently supported in object mode.

#### See Also

VB6/C equivalent: [`MAC_Init`](#MAC_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_Instance"></a>Mac.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Mac Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Mac
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_Reset"></a>Mac.Reset Method

 Resets the context of the Mac object. 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes).

#### See Also

VB6/C equivalent: [`MAC_Reset`](#MAC_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_AddData_Byte"></a>Md5.AddData Method (Byte[])

 Adds an array of 8-bit bytes to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`MD5_AddBytes`](#MD5_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_AddData_String"></a>Md5.AddData Method (String)

 Adds a string of Ansi characters to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   String of Ansi characters

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`MD5_AddString`](#MD5_AddString)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_BytesHash"></a>Md5.BytesHash Method

 Creates message digest as array of bytes from message in byte array 

#### Syntax

[`C#`]

```
public static byte[] BytesHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function BytesHash ( _
	message As Byte() _
) As Byte()
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in array of bytes

#### See Also

VB6/C equivalent: [`MD5_BytesHash`](#MD5_BytesHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Dispose"></a>Md5.Dispose Method

 Dispose of this object and clear any stored data 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_FileHexHash"></a>Md5.FileHexHash Method

 Creates hash digest of a binary file 

#### Syntax

[`C#`]

```
public static string FileHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### See Also

VB6/C equivalent: [`MD5_FileHexHash`](#MD5_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_FileTextHexHash"></a>Md5.FileTextHexHash Method

 Creates hash digest of a "text" file treating CR-LF pairs as a single newline char 

#### Syntax

[`C#`]

```
public static string FileTextHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileTextHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### Remarks

Use when comparing text data on a Unix system

#### See Also

VB6/C equivalent: [`MD5_FileHexHash`](#MD5_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_HexDigest"></a>Md5.HexDigest Method

 Computes final message digest in hex format 

#### Syntax

[`C#`]

```
public string HexDigest()
```

[`VB.NET`]

```
Public Function HexDigest As String
```

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`MD5_HexDigest`](#MD5_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_HexHash_Byte"></a>Md5.HexHash Method (Byte[])

 Creates message digest in hex format from message in byte array 

#### Syntax

[`C#`]

```
public static string HexHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As Byte() _
) As String
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`MD5_BytesHexHash`](#MD5_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_HexHash_String"></a>Md5.HexHash Method (String)

 Creates message digest in hex format from message in Ansi string 

#### Syntax

[`C#`]

```
public static string HexHash(
	string message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As String _
) As String
```

#### Parameters

message

:   Message text to be digested

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`MD5_StringHexHash`](#MD5_StringHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Hmac_ByteByte"></a>Md5.Hmac Method (Byte[], Byte[])

 Computes the keyed hash digest of binary data using HMAC algorithm 

#### Syntax

[`C#`]

```
public static string Hmac(
	byte[] data,
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	data As Byte(), _
	key As Byte() _
) As String
```

#### Parameters

data

:   Data in array of bytes

key

:   Key in array of bytes

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`MD5_Hmac`](#MD5_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Hmac_StringString"></a>Md5.Hmac Method (String, String)

 Computes the keyed hash digest using HMAC algorithm passing data as hex strings 

#### Syntax

[`C#`]

```
public static string Hmac(
	string dataHex,
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	dataHex As String, _
	keyHex As String _
) As String
```

#### Parameters

dataHex

:   Data in hex format

keyHex

:   Key in hex format

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`MD5_HmacHex`](#MD5_HmacHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Init"></a>Md5.Init Method

 Initializes the context 

#### Syntax

[`C#`]

```
public bool Init()
```

[`VB.NET`]

```
Public Function Init As Boolean
```

#### Return Value

True if successful, False if failed

#### See Also

VB6/C equivalent: [`MD5_Init`](#MD5_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Instance"></a>Md5.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Md5 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Md5
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_Reset"></a>Md5.Reset Method

 Resets the context 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`MD5_Reset`](#MD5_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pbe_Kdf2_Int32ByteByteInt32HashAlgorithm"></a>Pbe.Kdf2 Method (Int32, Byte[], Byte[], Int32, HashAlgorithm)

 Derives a key of any length from a password using the PBKDF2 algorithm using specified HMAC algorithm 

#### Syntax

[`C#`]

```
public static byte[] Kdf2(
	int dkLen,
	byte[] pwdBytes,
	byte[] salt,
	int count,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function Kdf2 ( _
	dkLen As Integer, _
	pwdBytes As Byte(), _
	salt As Byte(), _
	count As Integer, _
	hashAlg As HashAlgorithm _
) As Byte()
```

#### Parameters

dkLen

:   Required length of key in bytes

pwdBytes

:   Password encoded in byte format

salt

:   Salt in byte format

count

:   Iteration count

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to use in HMAC PRF (optional, default=SHA-1)

#### Return Value

Key in byte[] format

#### See Also

VB6/C equivalent: [`PBE_Kdf2`](#PBE_Kdf2)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pbe_Kdf2_Int32StringStringInt32HashAlgorithm"></a>Pbe.Kdf2 Method (Int32, String, String, Int32, HashAlgorithm)

 Derives a key in hex format of any length from a password with the salt in hex format using specified HMAC algorithm 

#### Syntax

[`C#`]

```
public static string Kdf2(
	int dkLen,
	string pwdStr,
	string saltHex,
	int count,
	HashAlgorithm hashAlg
)
```

[`VB.NET`]

```
Public Shared Function Kdf2 ( _
	dkLen As Integer, _
	pwdStr As String, _
	saltHex As String, _
	count As Integer, _
	hashAlg As HashAlgorithm _
) As String
```

#### Parameters

dkLen

:   Required length of key in bytes

pwdStr

:   Password

saltHex

:   Salt in hex format

count

:   Iteration count

hashAlg

:   Type: [HashAlgorithm](#T_HashAlgorithm)  

Hash algorithm to use in HMAC PRF (optional, default=SHA-1)

#### Return Value

Key in hex format

#### Remarks

Password pwdStr is normal text, not hexadecimal

#### Example

[`C#`]

```
string keyHex = Pbe.Kdf2(24, "password", "78578e5a5d63cb06", 2048);
// BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643
```

#### See Also

VB6/C equivalent: [`PBE_Kdf2Hex`](#PBE_Kdf2Hex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pbe_Scrypt_Int32ByteByteInt32Int32Int32"></a>Pbe.Scrypt Method (Int32, Byte[], Byte[], Int32, Int32, Int32)

 Derives a key of any length from a password using the SCRYPT algorithm. 

#### Syntax

[`C#`]

```
public static byte[] Scrypt(
	int dkLen,
	byte[] pwdBytes,
	byte[] salt,
	int N,
	int r,
	int p
)
```

[`VB.NET`]

```
Public Shared Function Scrypt ( _
	dkLen As Integer, _
	pwdBytes As Byte(), _
	salt As Byte(), _
	N As Integer, _
	r As Integer, _
	p As Integer _
) As Byte()
```

#### Parameters

dkLen

:   Required length of key in bytes

pwdBytes

:   Password encoded in byte format

salt

:   Salt in byte format

N

:   CPU/Memory cost parameter, a number greater than one and a power of 2.

r

:   Block size r

p

:   Parallelization parameter p

#### Return Value

Key in byte[] format

#### See Also

VB6/C equivalent: [`PBE_Scrypt`](#PBE_Scrypt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pbe_Scrypt_Int32StringStringInt32Int32Int32"></a>Pbe.Scrypt Method (Int32, String, String, Int32, Int32, Int32)

 Derives a key in hex format from a password with the salt in hex format 

#### Syntax

[`C#`]

```
public static string Scrypt(
	int dkLen,
	string pwdStr,
	string saltHex,
	int N,
	int r,
	int p
)
```

[`VB.NET`]

```
Public Shared Function Scrypt ( _
	dkLen As Integer, _
	pwdStr As String, _
	saltHex As String, _
	N As Integer, _
	r As Integer, _
	p As Integer _
) As String
```

#### Parameters

dkLen

:   Required length of key in bytes

pwdStr

:   Password (normal text)

saltHex

:   Salt in hex format

N

:   CPU/Memory cost parameter, a number greater than one and a power of 2.

r

:   Block size r

p

:   Parallelization parameter p

#### Return Value

Key in hex format

#### Remarks

Password pwdStr is normal text, not hexadecimal

#### Example

[`C#`]

```
string keyHex = Pbe.Scrypt(64, "password", "4E61436C", 1024, 8, 16);
```

#### See Also

VB6/C equivalent: [`PBE_ScryptHex`](#PBE_ScryptHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pc1_Encrypt_ByteByte"></a>Pc1.Encrypt Method (Byte[], Byte[])

 Encrypt byte array input using RC4-compatible algorithm 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte() _
) As Byte()
```

#### Parameters

input

:   input byte array, any length

key

:   key byte array, any length

#### Return Value

byte array

#### Remarks

Superseded by Cipher.StreamBytes()

#### See Also

VB6/C equivalent: [`PC1_Bytes`](#PC1_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pc1_Encrypt_StringString"></a>Pc1.Encrypt Method (String, String)

 Encrypt hex-encoded input using RC4-compatible algorithm 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String _
) As String
```

#### Parameters

inputHex

:   hex-encoded input, any length

keyHex

:   hex-encoded key, any length

#### Return Value

hex-encoded string

#### Remarks

Superseded by Cipher.StreamHex()

#### See Also

VB6/C equivalent: [`PC1_Hex`](#PC1_Hex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Pc1_File"></a>Pc1.File Method

 Encrypt a file using RC4-compatible algorithm 

#### Syntax

[`C#`]

```
public static int File(
	string fileOut,
	string fileIn,
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function File ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Full pathname of output file to be created. Must be different from fileIn

fileIn

:   Full pathname of input file

key

:   Key byte array, any length

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

Superseded by Cipher.StreamFile()

#### See Also

VB6/C equivalent: [`PC1_File`](#PC1_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Prf_Bytes"></a>Prf.Bytes Method

 Generate output bytes using a pseudorandom function (PRF). 

#### Syntax

[`C#`]

```
public static byte[] Bytes(
	int numBytes,
	byte[] message,
	byte[] key,
	string customStr,
	PrfAlgorithm prfAlg
)
```

[`VB.NET`]

```
Public Shared Function Bytes ( _
	numBytes As Integer, _
	message As Byte(), _
	key As Byte(), _
	customStr As String, _
	prfAlg As PrfAlgorithm _
) As Byte()
```

#### Parameters

numBytes

:   Required number of output bytes.

message

:   Input message data.

key

:   Key.

customStr

:   Customization string (optional).

prfAlg

:   Type: [PrfAlgorithm](#T_PrfAlgorithm)  

PRF algorithm.

#### Return Value

Output data in byte array.

#### See Also

VB6/C equivalent: [`PRF_Bytes`](#PRF_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_BytesWithPrompt_Int32Rng_Strength"></a>Rng.BytesWithPrompt Method (Int32, Rng.Strength)

 Generates an array of random bytes with a prompt for keyboard input 

#### Syntax

[`C#`]

```
public static byte[] BytesWithPrompt(
	int numBytes,
	Rng.Strength strength
)
```

[`VB.NET`]

```
Public Shared Function BytesWithPrompt ( _
	numBytes As Integer, _
	strength As Rng.Strength _
) As Byte()
```

#### Parameters

numBytes

:   Required number of random bytes

strength

:   Type: [Rng.Strength](#T_Rng_Strength)  

Required security strength (default=112 bits)

#### Return Value

Array of random bytes

#### See Also

VB6/C equivalent: [`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_BytesWithPrompt_Int32StringRng_Strength"></a>Rng.BytesWithPrompt Method (Int32, String, Rng.Strength)

 Generates an array of random bytes with a prompt for keyboard input 

#### Syntax

[`C#`]

```
public static byte[] BytesWithPrompt(
	int numBytes,
	string prompt,
	Rng.Strength strength
)
```

[`VB.NET`]

```
Public Shared Function BytesWithPrompt ( _
	numBytes As Integer, _
	prompt As String, _
	strength As Rng.Strength _
) As Byte()
```

#### Parameters

numBytes

:   Required number of random bytes

prompt

:   Alternative prompt. Set as an empty string "" for the default prompt.

strength

:   Type: [Rng.Strength](#T_Rng_Strength)  

Required security strength

#### Return Value

Array of random bytes

#### See Also

VB6/C equivalent: [`RNG_BytesWithPrompt`](#RNG_BytesWithPrompt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_HexWithPrompt_Int32"></a>Rng.HexWithPrompt Method (Int32)

 Generates random bytes in hex format with a prompt for keyboard input 

#### Syntax

[`C#`]

```
public static string HexWithPrompt(
	int numBytes
)
```

[`VB.NET`]

```
Public Shared Function HexWithPrompt ( _
	numBytes As Integer _
) As String
```

#### Parameters

numBytes

:   Required number of random bytes

#### Return Value

Random bytes in hex format

#### See Also

VB6/C equivalent: [`RNG_HexWithPrompt`](#RNG_HexWithPrompt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_HexWithPrompt_Int32StringRng_Strength"></a>Rng.HexWithPrompt Method (Int32, String, Rng.Strength)

 Generates random bytes in hex format with a prompt for keyboard input 

#### Syntax

[`C#`]

```
public static string HexWithPrompt(
	int numBytes,
	string prompt,
	Rng.Strength strength
)
```

[`VB.NET`]

```
Public Shared Function HexWithPrompt ( _
	numBytes As Integer, _
	prompt As String, _
	strength As Rng.Strength _
) As String
```

#### Parameters

numBytes

:   Required number of random bytes

prompt

:   Alternative prompt. Set as an empty string "" for the default prompt.

strength

:   Type: [Rng.Strength](#T_Rng_Strength)  

Required security strength

#### Return Value

Random bytes in hex format

#### See Also

VB6/C equivalent: [`RNG_HexWithPrompt`](#RNG_HexWithPrompt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_Initialize"></a>Rng.Initialize Method

 Initialize the RNG generator with a seed file. 

#### Syntax

[`C#`]

```
public static bool Initialize(
	string seedFile
)
```

[`VB.NET`]

```
Public Shared Function Initialize ( _
	seedFile As String _
) As Boolean
```

#### Parameters

seedFile

:   Full path name of seed file

#### Return Value

true if successful; false if fails

#### Remarks

A seed file maintains the entropy state between sessions. It is automatically updated by this procedure. If the seed file does not exist, it will be created (with any available entropy).

#### See Also

VB6/C equivalent: [`RNG_Initialize`](#RNG_Initialize)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_InitializeEx"></a>Rng.InitializeEx Method

 Query and initialize the RNG generator using Intel(R) DRNG, if available. 

#### Syntax

[`C#`]

```
public static int InitializeEx(
	Rng.Options opts
)
```

[`VB.NET`]

```
Public Shared Function InitializeEx ( _
	opts As Rng.Options _
) As Integer
```

#### Parameters

opts

:   Type: [Rng.Options](#T_Rng_Options)  

Specify Rng.Options.NoIntelDrng to explicitly *turn off* support.

#### Return Value

Support status for Intel(R) DRNG. If available, then a positive value (1,2,3); else a negative [error code](#errorcodes).

#### See Also

VB6/C equivalent: [`RNG_Initialize`](#RNG_Initialize)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_KeyBytes_Int32Byte"></a>Rng.KeyBytes Method (Int32, Byte[])

 Generates a random key with user-supplied entropy 

#### Syntax

[`C#`]

```
public static byte[] KeyBytes(
	int numBytes,
	byte[] arrSeed
)
```

[`VB.NET`]

```
Public Shared Function KeyBytes ( _
	numBytes As Integer, _
	arrSeed As Byte() _
) As Byte()
```

#### Parameters

numBytes

:   Required number of random bytes

arrSeed

:   User-supplied entropy in byte format

#### Return Value

Array of random bytes

#### See Also

VB6/C equivalent: [`RNG_KeyBytes`](#RNG_KeyBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_KeyBytes_Int32String"></a>Rng.KeyBytes Method (Int32, String)

 Generates a random key 

#### Syntax

[`C#`]

```
public static byte[] KeyBytes(
	int numBytes,
	string seedStr
)
```

[`VB.NET`]

```
Public Shared Function KeyBytes ( _
	numBytes As Integer, _
	seedStr As String _
) As Byte()
```

#### Parameters

numBytes

:   Required number of random bytes

seedStr

:   User-supplied entropy in string format. Set as an empty string "" to ignore.

#### Return Value

Array of random bytes

#### See Also

VB6/C equivalent: [`RNG_KeyBytes`](#RNG_KeyBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_KeyHex_Int32Byte"></a>Rng.KeyHex Method (Int32, Byte[])

 Generates a random key in hex format with user-supplied entropy 

#### Syntax

[`C#`]

```
public static string KeyHex(
	int numBytes,
	byte[] arrSeed
)
```

[`VB.NET`]

```
Public Shared Function KeyHex ( _
	numBytes As Integer, _
	arrSeed As Byte() _
) As String
```

#### Parameters

numBytes

:   Required number of random bytes

arrSeed

:   User-supplied entropy in byte format

#### Return Value

Random bytes in hex format

#### See Also

VB6/C equivalent: [`RNG_KeyHex`](#RNG_KeyHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_KeyHex_Int32String"></a>Rng.KeyHex Method (Int32, String)

 Generates a random key in hex format 

#### Syntax

[`C#`]

```
public static string KeyHex(
	int numBytes,
	string seedStr
)
```

[`VB.NET`]

```
Public Shared Function KeyHex ( _
	numBytes As Integer, _
	seedStr As String _
) As String
```

#### Parameters

numBytes

:   Required number of random bytes

seedStr

:   User-supplied entropy in string format. Set as an empty string "" to ignore.

#### Return Value

Random bytes in hex format

#### See Also

VB6/C equivalent: [`RNG_KeyHex`](#RNG_KeyHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_MakeSeedFile_StringRng_Strength"></a>Rng.MakeSeedFile Method (String, Rng.Strength)

 Create a new seed file suitable for use with Rng.Initialize 

#### Syntax

[`C#`]

```
public static bool MakeSeedFile(
	string seedFile,
	Rng.Strength strength
)
```

[`VB.NET`]

```
Public Shared Function MakeSeedFile ( _
	seedFile As String, _
	strength As Rng.Strength _
) As Boolean
```

#### Parameters

seedFile

:   Name of seed file to be created

strength

:   Type: [Rng.Strength](#T_Rng_Strength)  

Required security strength (default=112 bits)

#### Return Value

true if successful; false if fails

#### Remarks

Any existing file of the same name will be overwritten without warning.

#### See Also

VB6/C equivalent: [`RNG_MakeSeedFile`](#RNG_MakeSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_MakeSeedFile_StringStringRng_Strength"></a>Rng.MakeSeedFile Method (String, String, Rng.Strength)

 Create a new seed file suitable for use with Rng.Initialize 

#### Syntax

[`C#`]

```
public static bool MakeSeedFile(
	string seedFile,
	string prompt,
	Rng.Strength strength
)
```

[`VB.NET`]

```
Public Shared Function MakeSeedFile ( _
	seedFile As String, _
	prompt As String, _
	strength As Rng.Strength _
) As Boolean
```

#### Parameters

seedFile

:   Name of seed file to be created

prompt

:   Prompt for dialog

strength

:   Type: [Rng.Strength](#T_Rng_Strength)  

Required security strength

#### Return Value

true if successful; false if fails

#### Remarks

Any existing file of the same name will be overwritten without warning.

#### See Also

VB6/C equivalent: [`RNG_MakeSeedFile`](#RNG_MakeSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_NonceBytes"></a>Rng.NonceBytes Method

 Generates a random nonce 

#### Syntax

[`C#`]

```
public static byte[] NonceBytes(
	int numBytes
)
```

[`VB.NET`]

```
Public Shared Function NonceBytes ( _
	numBytes As Integer _
) As Byte()
```

#### Parameters

numBytes

:   Number of bytes required

#### Return Value

Array of bytes

#### See Also

VB6/C equivalent: [`RNG_NonceData`](#RNG_NonceData)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_NonceHex"></a>Rng.NonceHex Method

 Generates a random nonce in hex format 

#### Syntax

[`C#`]

```
public static string NonceHex(
	int numBytes
)
```

[`VB.NET`]

```
Public Shared Function NonceHex ( _
	numBytes As Integer _
) As String
```

#### Parameters

numBytes

:   Number of bytes required

#### Return Value

Nonce in hex format

#### See Also

VB6/C equivalent: [`RNG_NonceDataHex`](#RNG_NonceDataHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_Number"></a>Rng.Number Method

 Generates a random integer in a given range 

#### Syntax

[`C#`]

```
public static int Number(
	int lower,
	int upper
)
```

[`VB.NET`]

```
Public Shared Function Number ( _
	lower As Integer, _
	upper As Integer _
) As Integer
```

#### Parameters

lower

:   lower value of range

upper

:   upper value of range

#### Return Value

Random integer

#### See Also

VB6/C equivalent: [`RNG_Number`](#RNG_Number)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_Octet"></a>Rng.Octet Method

 Generates a single random octet (byte) 

#### Syntax

[`C#`]

```
public static byte Octet()
```

[`VB.NET`]

```
Public Shared Function Octet As Byte
```

#### Return Value

Single byte value randomly chosen between 0 and 255

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_Test"></a>Rng.Test Method

 Carries out a NIST SP800-90 health check and FIPS140-2 statistical tests on the random number generator 

#### Syntax

[`C#`]

```
public static bool Test(
	string resultFile
)
```

[`VB.NET`]

```
Public Shared Function Test ( _
	resultFile As String _
) As Boolean
```

#### Parameters

resultFile

:   Name of results file to be created, or null/Nothing not to create a results file.

#### Return Value

true if successful; false if fails.

#### Remarks

Any existing file of the same name will be overwritten without warning.

#### See Also

VB6/C equivalent: [`RNG_Test`](#RNG_Test)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_TestDrbgvs"></a>Rng.TestDrbgvs Method

 Tests the random number generator for conformance to NIST SP 800-90A using the relevant test specified in the Deterministic Random Bit Generator Validation System (DRBGVS). 

#### Syntax

[`C#`]

```
public static string TestDrbgvs(
	int returnedBitsLen,
	string entropyInput,
	string nonce,
	string personalizationString,
	string additionalInput1,
	string entropyReseed,
	string additionalInputReseed,
	string additionalInput2
)
```

[`VB.NET`]

```
Public Shared Function TestDrbgvs ( _
	returnedBitsLen As Integer, _
	entropyInput As String, _
	nonce As String, _
	personalizationString As String, _
	additionalInput1 As String, _
	entropyReseed As String, _
	additionalInputReseed As String, _
	additionalInput2 As String _
) As String
```

#### Parameters

returnedBitsLen

:   Number of bits to be returned from each call to the generate function in the test

entropyInput

:   the EntropyInput value in hex format

nonce

:   the Nonce value in hex format

personalizationString

:   the PersonalizationString value in hex format

additionalInput1

:   the first AdditionalInput value in hex format

entropyReseed

:   the EntropyReseed value in hex format

additionalInputReseed

:   the AdditionalInputReseed value in hex format

additionalInput2

:   the second AdditionalInput value in hex format

#### Return Value

the ReturnedBits as a string in hexadecimal format

#### Remarks

The test procedure, the input values and the expected output are described in the DRBGVS document. The relevant DRBG mechanism is HMAC_DRBG SHA-512 without prediction resistance. Use the empty string "" to pass a zero-length input. All hex strings must have an even number of characters.

#### See Also

VB6/C equivalent: [`RNG_TestDRBGVS`](#RNG_TestDRBGVS)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Rng_UpdateSeedFile"></a>Rng.UpdateSeedFile Method

 Updates the RNG seed file 

#### Syntax

[`C#`]

```
public static bool UpdateSeedFile(
	string seedFile
)
```

[`VB.NET`]

```
Public Shared Function UpdateSeedFile ( _
	seedFile As String _
) As Boolean
```

#### Parameters

seedFile

:   Full path name of seed file

#### Return Value

true if successful; false if fails

#### Remarks

Any existing file of the same name will be overwritten without warning.

#### See Also

VB6/C equivalent: [`RNG_UpdateSeedFile`](#RNG_UpdateSeedFile)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_AddData_Byte"></a>Sha1.AddData Method (Byte[])

 Adds an array of 8-bit bytes to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA1_AddBytes`](#SHA1_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_AddData_String"></a>Sha1.AddData Method (String)

 Adds a string of Ansi characters to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   String of Ansi characters

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA1_AddString`](#SHA1_AddString)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_BytesHash"></a>Sha1.BytesHash Method

 Creates message digest as array of bytes from message in byte array 

#### Syntax

[`C#`]

```
public static byte[] BytesHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function BytesHash ( _
	message As Byte() _
) As Byte()
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in array of bytes

#### See Also

VB6/C equivalent: [`SHA1_BytesHash`](#SHA1_BytesHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Dispose"></a>Sha1.Dispose Method

 Dispose of this object and clear any stored data 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_FileHexHash"></a>Sha1.FileHexHash Method

 Creates hash digest of a binary file 

#### Syntax

[`C#`]

```
public static string FileHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_FileHexHash`](#SHA1_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_FileTextHexHash"></a>Sha1.FileTextHexHash Method

 Creates hash digest of a "text" file treating CR-LF pairs as a single newline char 

#### Syntax

[`C#`]

```
public static string FileTextHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileTextHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### Remarks

Use when comparing text data on a Unix system

#### See Also

VB6/C equivalent: [`SHA1_FileHexHash`](#SHA1_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_HexDigest"></a>Sha1.HexDigest Method

 Computes final message digest in hex format 

#### Syntax

[`C#`]

```
public string HexDigest()
```

[`VB.NET`]

```
Public Function HexDigest As String
```

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_HexDigest`](#SHA1_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_HexHash_Byte"></a>Sha1.HexHash Method (Byte[])

 Creates message digest in hex format from message in byte array 

#### Syntax

[`C#`]

```
public static string HexHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As Byte() _
) As String
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_BytesHexHash`](#SHA1_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_HexHash_String"></a>Sha1.HexHash Method (String)

 Creates message digest in hex format from message in Ansi string 

#### Syntax

[`C#`]

```
public static string HexHash(
	string message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As String _
) As String
```

#### Parameters

message

:   Message text to be digested

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_StringHexHash`](#SHA1_StringHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Hmac_ByteByte"></a>Sha1.Hmac Method (Byte[], Byte[])

 Computes the keyed hash digest of binary data using HMAC algorithm 

#### Syntax

[`C#`]

```
public static string Hmac(
	byte[] data,
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	data As Byte(), _
	key As Byte() _
) As String
```

#### Parameters

data

:   Data in array of bytes

key

:   Key in array of bytes

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_Hmac`](#SHA1_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Hmac_StringString"></a>Sha1.Hmac Method (String, String)

 Computes the keyed hash digest using HMAC algorithm passing data as hex strings 

#### Syntax

[`C#`]

```
public static string Hmac(
	string dataHex,
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	dataHex As String, _
	keyHex As String _
) As String
```

#### Parameters

dataHex

:   Data in hex format

keyHex

:   Key in hex format

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA1_HmacHex`](#SHA1_HmacHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Init"></a>Sha1.Init Method

 Initializes the context 

#### Syntax

[`C#`]

```
public bool Init()
```

[`VB.NET`]

```
Public Function Init As Boolean
```

#### Return Value

True if successful, False if failed

#### See Also

VB6/C equivalent: [`SHA1_Init`](#SHA1_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Instance"></a>Sha1.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Sha1 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Sha1
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_Reset"></a>Sha1.Reset Method

 Resets the context 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA1_Reset`](#SHA1_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_AddData_Byte"></a>Sha256.AddData Method (Byte[])

 Adds an array of 8-bit bytes to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA2_AddBytes`](#SHA2_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_AddData_String"></a>Sha256.AddData Method (String)

 Adds a string of Ansi characters to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   String of Ansi characters

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA2_AddString`](#SHA2_AddString)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_BytesHash"></a>Sha256.BytesHash Method

 Creates message digest as array of bytes from message in byte array 

#### Syntax

[`C#`]

```
public static byte[] BytesHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function BytesHash ( _
	message As Byte() _
) As Byte()
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in array of bytes

#### See Also

VB6/C equivalent: [`SHA2_BytesHash`](#SHA2_BytesHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Dispose"></a>Sha256.Dispose Method

 Dispose of this object and clear any stored data 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_FileHexHash"></a>Sha256.FileHexHash Method

 Creates hash digest of a binary file 

#### Syntax

[`C#`]

```
public static string FileHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### See Also

VB6/C equivalent: [`SHA2_FileHexHash`](#SHA2_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_FileTextHexHash"></a>Sha256.FileTextHexHash Method

 Creates hash digest of a "text" file treating CR-LF pairs as a single newline char 

#### Syntax

[`C#`]

```
public static string FileTextHexHash(
	string fileName
)
```

[`VB.NET`]

```
Public Shared Function FileTextHexHash ( _
	fileName As String _
) As String
```

#### Parameters

fileName

:   Name of input file

#### Return Value

Message digest in hex format

#### Remarks

Use when comparing text data on a Unix system

#### See Also

VB6/C equivalent: [`SHA2_FileHexHash`](#SHA2_FileHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_HexDigest"></a>Sha256.HexDigest Method

 Computes final message digest in hex format 

#### Syntax

[`C#`]

```
public string HexDigest()
```

[`VB.NET`]

```
Public Function HexDigest As String
```

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA2_HexDigest`](#SHA2_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_HexHash_Byte"></a>Sha256.HexHash Method (Byte[])

 Creates message digest in hex format from message in byte array 

#### Syntax

[`C#`]

```
public static string HexHash(
	byte[] message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As Byte() _
) As String
```

#### Parameters

message

:   Message data to be digested

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA2_BytesHexHash`](#SHA2_BytesHexHash)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_HexHash_String"></a>Sha256.HexHash Method (String)

 Creates message digest in hex format from message in Ansi string 

#### Syntax

[`C#`]

```
public static string HexHash(
	string message
)
```

[`VB.NET`]

```
Public Shared Function HexHash ( _
	message As String _
) As String
```

#### Parameters

message

:   Message text to be digested

#### Return Value

Digest in hex format

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Hmac_ByteByte"></a>Sha256.Hmac Method (Byte[], Byte[])

 Computes the keyed hash digest of binary data using HMAC algorithm 

#### Syntax

[`C#`]

```
public static string Hmac(
	byte[] data,
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	data As Byte(), _
	key As Byte() _
) As String
```

#### Parameters

data

:   Data in array of bytes

key

:   Key in array of bytes

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA2_Hmac`](#SHA2_Hmac)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Hmac_StringString"></a>Sha256.Hmac Method (String, String)

 Computes the keyed hash digest using HMAC algorithm passing data as hex strings 

#### Syntax

[`C#`]

```
public static string Hmac(
	string dataHex,
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function Hmac ( _
	dataHex As String, _
	keyHex As String _
) As String
```

#### Parameters

dataHex

:   Data in hex format

keyHex

:   Key in hex format

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA2_HmacHex`](#SHA2_HmacHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Init"></a>Sha256.Init Method

 Initializes the context 

#### Syntax

[`C#`]

```
public bool Init()
```

[`VB.NET`]

```
Public Function Init As Boolean
```

#### Return Value

True if successful, False if failed

#### See Also

VB6/C equivalent: [`SHA2_Init`](#SHA2_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Instance"></a>Sha256.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Sha256 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Sha256
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_Reset"></a>Sha256.Reset Method

 Resets the context 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA2_Reset`](#SHA2_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_AddData_Byte"></a>Sha3.AddData Method (Byte[])

 Adds an array of 8-bit bytes to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	byte[] b
)
```

[`VB.NET`]

```
Public Function AddData ( _
	b As Byte() _
) As Integer
```

#### Parameters

b

:   Data to add

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA3_AddBytes`](#SHA3_AddBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_AddData_String"></a>Sha3.AddData Method (String)

 Adds a string of Ansi characters to the digest 

#### Syntax

[`C#`]

```
public int AddData(
	string s
)
```

[`VB.NET`]

```
Public Function AddData ( _
	s As String _
) As Integer
```

#### Parameters

s

:   String of Ansi characters

#### Return Value

0 on success or nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA3_AddString`](#SHA3_AddString)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_Dispose"></a>Sha3.Dispose Method

 Dispose of this object and clear any stored data 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_HexDigest"></a>Sha3.HexDigest Method

 Computes final message digest in hex format 

#### Syntax

[`C#`]

```
public string HexDigest()
```

[`VB.NET`]

```
Public Function HexDigest As String
```

#### Return Value

Digest in hex format

#### See Also

VB6/C equivalent: [`SHA3_HexDigest`](#SHA3_HexDigest)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_Init"></a>Sha3.Init Method

 Initialises the object ready to receive data to digest 

#### Syntax

[`C#`]

```
public bool Init(
	int hashBitLen
)
```

[`VB.NET`]

```
Public Function Init ( _
	hashBitLen As Integer _
) As Boolean
```

#### Parameters

hashBitLen

:   Size of SHA-3 algorithm in bits. Must be one of {224, 256, 384, 512}.

#### Return Value

True if successful, False if failed

#### See Also

VB6/C equivalent: [`SHA3_Init`](#SHA3_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_Instance"></a>Sha3.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Sha3 Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Sha3
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_Reset"></a>Sha3.Reset Method

 Resets the context 

#### Syntax

[`C#`]

```
public int Reset()
```

[`VB.NET`]

```
Public Function Reset As Integer
```

#### Return Value

0 on success or a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`SHA3_Reset`](#SHA3_Reset)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_CheckKey_Byte"></a>Tdea.CheckKey Method (Byte[])

 Verifies that no part of the key is a weak or semi-weak TDEA key. 

#### Syntax

[`C#`]

```
public static int CheckKey(
	byte[] key
)
```

[`VB.NET`]

```
Public Shared Function CheckKey ( _
	key As Byte() _
) As Integer
```

#### Parameters

key

:   Key to check

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_CheckKey`](#DES_CheckKey)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_CheckKey_String"></a>Tdea.CheckKey Method (String)

 Verifies that no part of the key is a weak or semi-weak TDEA key. 

#### Syntax

[`C#`]

```
public static int CheckKey(
	string keyHex
)
```

[`VB.NET`]

```
Public Shared Function CheckKey ( _
	keyHex As String _
) As Integer
```

#### Parameters

keyHex

:   Hex-encoded key to check

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`DES_CheckKeyHex`](#DES_CheckKeyHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Decrypt_ByteByteModeByte"></a>Tdea.Decrypt Method (Byte[], Byte[], Mode, Byte[])

 Decrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Decrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Decrypted data in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_BytesMode`](#TDEA_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Decrypt_StringStringModeString"></a>Tdea.Decrypt Method (String, String, Mode, String)

 Decrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Decrypted data in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_HexMode`](#TDEA_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Decrypt_StringStringModeStringEncodingBase"></a>Tdea.Decrypt Method (String, String, Mode, String, EncodingBase)

 Decrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Decrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Decrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Decrypted data in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_B64Mode`](#TDEA_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Dispose"></a>Tdea.Dispose Method

 Dispose of this object and clear any key schedules 

#### Syntax

[`C#`]

```
public void Dispose()
```

[`VB.NET`]

```
Public Sub Dispose
```

#### See Also

VB6/C equivalent: [`TDEA_Final`](#TDEA_Final)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Encrypt_ByteByteModeByte"></a>Tdea.Encrypt Method (Byte[], Byte[], Mode, Byte[])

 Encrypt data in byte array 

#### Syntax

[`C#`]

```
public static byte[] Encrypt(
	byte[] input,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	input As Byte(), _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Byte()
```

#### Parameters

input

:   Input data

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Ciphertext in byte array or empty array on error

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_BytesMode`](#TDEA_BytesMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Encrypt_StringStringModeString"></a>Tdea.Encrypt Method (String, String, Mode, String)

 Encrypt hex-encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputHex,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputHex As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As String
```

#### Parameters

inputHex

:   Hex-encoded input data

keyHex

:   Hex-encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV representing exactly 8 bytes or "" for ECB mode

#### Return Value

Ciphertext in hex-encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_HexMode`](#TDEA_HexMode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Encrypt_StringStringModeStringEncodingBase"></a>Tdea.Encrypt Method (String, String, Mode, String, EncodingBase)

 Encrypt encoded data string 

#### Syntax

[`C#`]

```
public static string Encrypt(
	string inputStr,
	string keyStr,
	Mode mode,
	string ivStr,
	EncodingBase encodingBase
)
```

[`VB.NET`]

```
Public Shared Function Encrypt ( _
	inputStr As String, _
	keyStr As String, _
	mode As Mode, _
	ivStr As String, _
	encodingBase As EncodingBase _
) As String
```

#### Parameters

inputStr

:   Encoded input data

keyStr

:   Encoded key representing exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivStr

:   Encoded IV representing exactly 8 bytes or "" for ECB mode

encodingBase

:   Type: [EncodingBase](#T_EncodingBase)  

Type of encoding used

#### Return Value

Ciphertext in encoded string or empty string on error

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_B64Mode`](#TDEA_B64Mode)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileDecrypt_StringStringByteModeByte"></a>Tdea.FileDecrypt Method (String, String, Byte[], Mode, Byte[])

 Decrypt a file 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`TDEA_File`](#TDEA_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileDecrypt_StringStringByteModeByteCipherFileOption"></a>Tdea.FileDecrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Decrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes. Use null/Nothing for ECB mode or when using CipherFileOption.PrefixIV option

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`TDEA_FileExt`](#TDEA_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileDecrypt_StringStringStringModeString"></a>Tdea.FileDecrypt Method (String, String, String, Mode, String)

 Decrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileDecrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileDecrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`TDEA_FileHex`](#TDEA_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileEncrypt_StringStringByteModeByte"></a>Tdea.FileEncrypt Method (String, String, Byte[], Mode, Byte[])

 Encrypt a file 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`TDEA_File`](#TDEA_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileEncrypt_StringStringByteModeByteCipherFileOption"></a>Tdea.FileEncrypt Method (String, String, Byte[], Mode, Byte[], CipherFileOption)

 Encrypt a file with advanced options 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	byte[] key,
	Mode mode,
	byte[] iv,
	CipherFileOption advOptions
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	key As Byte(), _
	mode As Mode, _
	iv As Byte(), _
	advOptions As CipherFileOption _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

advOptions

:   Type: [CipherFileOption](#T_CipherFileOption)  

Advanced options. See CipherFileOption.

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same

#### See Also

VB6/C equivalent: [`TDEA_FileExt`](#TDEA_FileExt)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_FileEncrypt_StringStringStringModeString"></a>Tdea.FileEncrypt Method (String, String, String, Mode, String)

 Encrypt a file passing key and IV as hex strings 

#### Syntax

[`C#`]

```
public static int FileEncrypt(
	string fileOut,
	string fileIn,
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Shared Function FileEncrypt ( _
	fileOut As String, _
	fileIn As String, _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

fileOut

:   Name of output file to be created or overwritten

fileIn

:   Name of input file

keyHex

:   Hex-encoded key of exact length

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

ivHex

:   Hex-encoded IV or "" for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### Remarks

fileOut and fileIn must **not** be the same. The output file is in binary format.

#### See Also

VB6/C equivalent: [`TDEA_FileHex`](#TDEA_FileHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_InitDecrypt_ByteModeByte"></a>Tdea.InitDecrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`TDEA_Init`](#TDEA_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_InitDecrypt_StringModeString"></a>Tdea.InitDecrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start decrypting 

#### Syntax

[`C#`]

```
public int InitDecrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitDecrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`TDEA_InitHex`](#TDEA_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_InitEncrypt_ByteModeByte"></a>Tdea.InitEncrypt Method (Byte[], Mode, Byte[])

 Initializes with key, mode and IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	byte[] key,
	Mode mode,
	byte[] iv
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	key As Byte(), _
	mode As Mode, _
	iv As Byte() _
) As Integer
```

#### Parameters

key

:   Key of exactly 24 bytes (192 bits)

mode

:   Type: [Mode](#T_Mode)  

Cipher Mode

iv

:   IV of exactly 8 bytes or null/Nothing for ECB mode

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`TDEA_Init`](#TDEA_Init)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_InitEncrypt_StringModeString"></a>Tdea.InitEncrypt Method (String, Mode, String)

 Initializes with hex key, mode and hex IV ready to start encrypting 

#### Syntax

[`C#`]

```
public int InitEncrypt(
	string keyHex,
	Mode mode,
	string ivHex
)
```

[`VB.NET`]

```
Public Function InitEncrypt ( _
	keyHex As String, _
	mode As Mode, _
	ivHex As String _
) As Integer
```

#### Parameters

keyHex

:   Key in hex-encoded format

mode

:   Type: [Mode](#T_Mode)  

Cipher mode

ivHex

:   IV in hex-encoded format

#### Return Value

Zero (0) if successful; otherwise it returns a nonzero [error code](#errorcodes)

#### See Also

VB6/C equivalent: [`TDEA_InitHex`](#TDEA_InitHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Instance"></a>Tdea.Instance Method

 Create the one and only instance 

#### Syntax

[`C#`]

```
public static Tdea Instance()
```

[`VB.NET`]

```
Public Shared Function Instance As Tdea
```

#### Return Value

Single instance to class

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Pad_Byte"></a>Tdea.Pad Method (Byte[])

 Pads byte array to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static byte[] Pad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   data to be padded

#### Return Value

padded data in byte array

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Pad_String"></a>Tdea.Pad Method (String)

 Pads hex-encoded string to correct length for ECB and CBC encryption 

#### Syntax

[`C#`]

```
public static string Pad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Pad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded data to be padded

#### Return Value

padded data in hex-encoded string

#### Remarks

Uses PKCS#5/#7/CMS method of padding

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Unpad_Byte"></a>Tdea.Unpad Method (Byte[])

 Removes the padding from an encryption block 

#### Syntax

[`C#`]

```
public static byte[] Unpad(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   padded data

#### Return Value

Unpadded data in byte array or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Unpad_String"></a>Tdea.Unpad Method (String)

 Removes the padding from a hex-encoded encryption block 

#### Syntax

[`C#`]

```
public static string Unpad(
	string dataHex
)
```

[`VB.NET`]

```
Public Shared Function Unpad ( _
	dataHex As String _
) As String
```

#### Parameters

dataHex

:   hex-encoded padded data

#### Return Value

Unpadded data in hex-encoded string or unchanged data on error

#### Remarks

Padding is expected according to the convention in PKCS#5/#7/CMS. An error is indicated by returning the *original* data which will always be longer than the expected unpadded result.

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Update_Byte"></a>Tdea.Update Method (Byte[])

 Transform byte input data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public byte[] Update(
	byte[] data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   input data in byte array

#### Return Value

transformed data in byte array

#### Remarks

For ECB and CBC modes, input data length **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_Update`](#TDEA_Update)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_Update_String"></a>Tdea.Update Method (String)

 Transform hex string data with previously initialized key, mode and direction 

#### Syntax

[`C#`]

```
public string Update(
	string data
)
```

[`VB.NET`]

```
Public Function Update ( _
	data As String _
) As String
```

#### Parameters

data

:   hex-encoded input data

#### Return Value

hex-encoded data

#### Remarks

For ECB and CBC modes, the length of the decoded input bytes **must** be an exact multiple of the block length (8 bytes)

#### See Also

VB6/C equivalent: [`TDEA_UpdateHex`](#TDEA_UpdateHex)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Wipe_Data"></a>Wipe.Data Method

 Zeroises data in memory 

#### Syntax

[`C#`]

```
public static bool Data(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Data ( _
	data As Byte() _
) As Boolean
```

#### Parameters

data

:   data to be wiped

#### Return Value

**true** if successful; **false** if fails

#### See Also

VB6/C equivalent: [`WIPE_Data`](#WIPE_Data)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Wipe_File"></a>Wipe.File Method

 Securely wipe and delete a file. 

#### Syntax

[`C#`]

```
public static bool File(
	string fileName,
	Wipe.Options opts
)
```

[`VB.NET`]

```
Public Shared Function File ( _
	fileName As String, _
	opts As Wipe.Options _
) As Boolean
```

#### Parameters

fileName

:   Name of file to be wiped

opts

:   Type: [Wipe.Options](#T_Wipe_Options)  

Options (optional) Default is DOD 7-pass.

#### Return Value

true if successful; false if fails

#### See Also

VB6/C equivalent: [`WIPE_File`](#WIPE_File)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Wipe_String"></a>Wipe.String Method

 Zeroises a StringBuilder 

#### Syntax

[`C#`]

```
public static bool String(
	StringBuilder sb
)
```

[`VB.NET`]

```
Public Shared Function String ( _
	sb As StringBuilder _
) As Boolean
```

#### Parameters

sb

:   StringBuilder to be wiped

#### Return Value

**true** if successful; **false** if fails

#### Remarks

NB You can't wipe an ordinary string as they are immutable in C#, so store any sensitive string data in a StringBuilder.

#### See Also

VB6/C equivalent: [`WIPE_Data`](#WIPE_Data)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Xof_Bytes"></a>Xof.Bytes Method

 Generate bytes using an extendable-output function (XOF). 

#### Syntax

[`C#`]

```
public static byte[] Bytes(
	int numBytes,
	byte[] message,
	XofAlgorithm xofAlg
)
```

[`VB.NET`]

```
Public Shared Function Bytes ( _
	numBytes As Integer, _
	message As Byte(), _
	xofAlg As XofAlgorithm _
) As Byte()
```

#### Parameters

numBytes

:   Required number of output bytes.

message

:   Input message data.

xofAlg

:   Type: [XofAlgorithm](#T_XofAlgorithm)  

XOF algorithm.

#### Return Value

Output data in byte array.

#### See Also

VB6/C equivalent: [`XOF_Bytes`](#XOF_Bytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Zlib_Deflate"></a>Zlib.Deflate Method

 Compress data using the ZLIB deflate algorithm 

#### Syntax

[`C#`]

```
public static byte[] Deflate(
	byte[] dataToComp
)
```

[`VB.NET`]

```
Public Shared Function Deflate ( _
	dataToComp As Byte() _
) As Byte()
```

#### Parameters

dataToComp

:   Data to be compressed

#### Return Value

Compressed data

#### See Also

VB6/C equivalent: [`ZLIB_Deflate`](#ZLIB_Deflate)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Zlib_Inflate_Byte"></a>Zlib.Inflate Method (Byte[])

 Inflate compressed data using the ZLIB algorithm. 

#### Syntax

[`C#`]

```
public static byte[] Inflate(
	byte[] data
)
```

[`VB.NET`]

```
Public Shared Function Inflate ( _
	data As Byte() _
) As Byte()
```

#### Parameters

data

:   Compressed data to be uncompressed.

#### Return Value

Uncompressed data, or an empty array on error.

#### Remarks

An empty array may also be returned if the original data was the empty array itself.

#### See Also

VB6/C equivalent: [`ZLIB_Inflate`](#ZLIB_Inflate)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Zlib_Inflate_ByteInt32"></a>Zlib.Inflate Method (Byte[], Int32)

 Inflate compressed data using the ZLIB algorithm [superseded]. 

#### Syntax

[`C#`]

```
public static byte[] Inflate(
	byte[] data,
	int lenUncompressed
)
```

[`VB.NET`]

```
Public Shared Function Inflate ( _
	data As Byte(), _
	lenUncompressed As Integer _
) As Byte()
```

#### Parameters

data

:   Data to be uncompressed

lenUncompressed

:   Length of uncompressed data

#### Return Value

Uncompressed data

#### Remarks

Superseded by Zlib.Inflate(Byte[])

#### See Also

VB6/C equivalent: [`ZLIB_Inflate`](#ZLIB_Inflate)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aead_ErrCodeProperty"></a>Aead.ErrCode Property

 Last [error code](#errorcodes) (object-related only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes128_ErrCodeProperty"></a>Aes128.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`AES128_InitError`](#AES128_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes192_ErrCodeProperty"></a>Aes192.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`AES192_InitError`](#AES192_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Aes256_ErrCodeProperty"></a>Aes256.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`AES256_InitError`](#AES256_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Blowfish_ErrCodeProperty"></a>Blowfish.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`BLF_InitError`](#BLF_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Cipher_ErrCodeProperty"></a>Cipher.ErrCode Property

 Last [error code](#errorcodes) (for Init, Update and Final object methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_CipherStream_ErrCodeProperty"></a>CipherStream.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Des_ErrCodeProperty"></a>Des.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`DES_InitError`](#DES_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Gcm_ErrCodeProperty"></a>Gcm.ErrCode Property

 Last [error code](#errorcodes) (object-related only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Hash_ErrCodeProperty"></a>Hash.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and Final object methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Mac_ErrCodeProperty"></a>Mac.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and Final object methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Md5_ErrCodeProperty"></a>Md5.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and HexDigest methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha1_ErrCodeProperty"></a>Sha1.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and HexDigest methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha256_ErrCodeProperty"></a>Sha256.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and HexDigest methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_ErrCodeProperty"></a>Sha3.ErrCode Property

 Last [error code](#errorcodes) (for Init, AddData and HexDigest methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Sha3_LengthInBytesProperty"></a>Sha3.LengthInBytes Property

 Length in bytes of hash output (i.e. length in bits / 8) 

#### Syntax

[`C#`]

```
public int LengthInBytes { get; }
```

[`VB.NET`]

```
Public ReadOnly Property LengthInBytes As Integer
```

#### See Also

VB6/C equivalent: [`SHA3_LengthInBytes`](#SHA3_LengthInBytes)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="M_Tdea_ErrCodeProperty"></a>Tdea.ErrCode Property

 Last [error code](#errorcodes) (for Init and Update methods only) 

#### Syntax

[`C#`]

```
public int ErrCode { get; }
```

[`VB.NET`]

```
Public ReadOnly Property ErrCode As Integer
```

#### See Also

VB6/C equivalent: [`TDEA_InitError`](#TDEA_InitError)

[[Contents](#topofpage)] [[Index](#index)]

---

<a id="dotnetenumerations"></a>Enumerations in .NET
---------------------------------------------------

* [Aead.Algorithm Enumeration](#T_Aead_Algorithm)
* [Aead.Opts Enumeration](#T_Aead_Opts)
* [Cipher.Opts Enumeration](#T_Cipher_Opts)
* [CipherAlgorithm Enumeration](#T_CipherAlgorithm)
* [CipherFileOption Enumeration](#T_CipherFileOption)
* [CipherStream.Algorithm Enumeration](#T_CipherStream_Algorithm)
* [ComprAlgorithm Enumeration](#T_ComprAlgorithm)
* [EncodingBase Enumeration](#T_EncodingBase)
* [HashAlgorithm Enumeration](#T_HashAlgorithm)
* [MacAlgorithm Enumeration](#T_MacAlgorithm)
* [Mode Enumeration](#T_Mode)
* [Padding Enumeration](#T_Padding)
* [PrfAlgorithm Enumeration](#T_PrfAlgorithm)
* [Rng.Options Enumeration](#T_Rng_Options)
* [Rng.Strength Enumeration](#T_Rng_Strength)
* [Wipe.Options Enumeration](#T_Wipe_Options)
* [XofAlgorithm Enumeration](#T_XofAlgorithm)

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Aead_Algorithm"></a>Aead.Algorithm Enumeration

 AEAD algorithm 

#### Syntax

[`C#`]

```
public enum Algorithm
```

[`VB.NET`]

```
Public Enumeration Algorithm
```

#### Members

|  | Member name | Description |
|  | Aes_128_Gcm | AEAD_AES_128_GCM authenticated encryption algorithm (RFC 5116) |
|  | Aes_256_Gcm | AEAD_AES_256_GCM authenticated encryption algorithm (RFC 5116) |
|  | Chacha20_Poly1305 | AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 7539) |
|  | Ascon_128 | ASCON-128 authenticated encryption (Aead.[En/De]cryptWithTag only) |
|  | Ascon_128A | ASCON-128a authenticated encryption (Aead.[En/De]cryptWithTag only) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Aead_Opts"></a>Aead.Opts Enumeration

 Advanced options 

#### Syntax

[`C#`]

```
[FlagsAttribute]
public enum Opts
```

[`VB.NET`]

```
<FlagsAttribute> _
Public Enumeration Opts
```

#### Members

|  | Member name | Description |
|  | Default | Default options |
|  | PrefixIV | Prefix (prepend) the IV (nonce) before the ciphertext in the output |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_CipherAlgorithm"></a>CipherAlgorithm Enumeration

 Block Cipher Algorithm 

#### Syntax

[`C#`]

```
public enum CipherAlgorithm
```

[`VB.NET`]

```
Public Enumeration CipherAlgorithm
```

#### Members

|  | Member name | Description |
|  | Tdea | Triple DES (TDEA, 3DES, des-ede3) |
|  | Aes128 | AES-128 |
|  | Aes192 | AES-192 |
|  | Aes256 | AES-256 |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_CipherFileOption"></a>CipherFileOption Enumeration

 Advanced options for file cipher operations 

#### Syntax

[`C#`]

```
[FlagsAttribute]
public enum CipherFileOption
```

[`VB.NET`]

```
<FlagsAttribute> _
Public Enumeration CipherFileOption
```

#### Members

|  | Member name | Description |
|  | Default | Default option |
|  | PrefixIV | Prefix the IV before ciphertext in the output file (ignored for ECB mode) |
|  | LeavePadding | Leave any padding in place when decrypting (ECB and CBC modes only; ignored if encrypting) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_CipherStream_Algorithm"></a>CipherStream.Algorithm Enumeration

 Stream cipher algorithm 

#### Syntax

[`C#`]

```
public enum Algorithm
```

[`VB.NET`]

```
Public Enumeration Algorithm
```

#### Members

|  | Member name | Description |
|  | Arcfour | ARCFOUR (RC4) algorithm |
|  | Salsa20 | Salsa20 algorithm |
|  | Chacha20 | ChaCha20 algorithm |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Cipher_Opts"></a>Cipher.Opts Enumeration

 Advanced options 

#### Syntax

[`C#`]

```
[FlagsAttribute]
public enum Opts
```

[`VB.NET`]

```
<FlagsAttribute> _
Public Enumeration Opts
```

#### Members

|  | Member name | Description |
|  | Default | Default options |
|  | PrefixIV | Prefix (prepend) the IV before the ciphertext in the output file (ignored for ECB mode) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_ComprAlgorithm"></a>ComprAlgorithm Enumeration

 Compression algorithm. 

#### Syntax

[`C#`]

```
public enum ComprAlgorithm
```

[`VB.NET`]

```
Public Enumeration ComprAlgorithm
```

#### Members

|  | Member name | Description |
|  | Zlib | zlib as per RFC 1950 |
|  | Zstd | zstd as per RFC 8878 |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_EncodingBase"></a>EncodingBase Enumeration

 Base for encoding methods 

#### Syntax

[`C#`]

```
public enum EncodingBase
```

[`VB.NET`]

```
Public Enumeration EncodingBase
```

#### Members

|  | Member name | Description |
|  | Base64 | Base64 encoding |
|  | Base16 | Base16 encoding (i.e. hexadecimal) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_HashAlgorithm"></a>HashAlgorithm Enumeration

 Message Digest Hash Algorithm 

#### Syntax

[`C#`]

```
public enum HashAlgorithm
```

[`VB.NET`]

```
Public Enumeration HashAlgorithm
```

#### Members

|  | Member name | Description |
|  | Sha1 | SHA-1 (as per FIPS PUB 180-2) |
|  | Md5 | MD5 (as per RFC 1321) |
|  | Md2 | MD2 (as per RFC 1319) |
|  | Ripemd160 | RIPEMD-160 |
|  | Sha224 | SHA-224 (as per FIPS PUB 180-4) |
|  | Sha256 | SHA-256 (as per FIPS PUB 180-4) |
|  | Sha384 | SHA-384 (as per FIPS PUB 180-4) |
|  | Sha512 | SHA-512 (as per FIPS PUB 180-4) |
|  | Sha3_224 | SHA-3-224 (as per FIPS PUB 202) |
|  | Sha3_256 | SHA-3-256 (as per FIPS PUB 202) |
|  | Sha3_384 | SHA-3-384 (as per FIPS PUB 202) |
|  | Sha3_512 | SHA-3-256 (as per FIPS PUB 202) |
|  | Ascon_Hash | ASCON-HASH (byte/hex functions only) |
|  | Ascon_HashA | ASCON-HASHA (byte/hex functions only) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_MacAlgorithm"></a>MacAlgorithm Enumeration

 Message Authentication Code (MAC) Algorithm 

#### Syntax

[`C#`]

```
public enum MacAlgorithm
```

[`VB.NET`]

```
Public Enumeration MacAlgorithm
```

#### Members

|  | Member name | Description |
|  | HmacSha1 | HMAC-SHA-1 |
|  | HmacMd5 | HMAC-MD5 |
|  | HmacRipemd160 | HMAC-RIPEMD160 |
|  | HmacSha224 | HMAC-SHA-224 |
|  | HmacSha256 | HMAC-SHA-256 |
|  | HmacSha384 | HMAC-SHA-384 |
|  | HmacSha512 | HMAC-SHA-512 |
|  | HmacSha3_224 | HMAC-SHA-3-224 |
|  | HmacSha3_256 | HMAC-SHA-3-256 |
|  | HmacSha3_384 | HMAC-SHA-3-384 |
|  | HmacSha3_512 | HMAC-SHA-3-512 |
|  | CmacTdea | CMAC-TDEA (CMAC-DES-EDE) |
|  | CmacAes128 | CMAC-AES-128 |
|  | CmacAes192 | CMAC-AES-192 |
|  | CmacAes256 | CMAC-AES-256 |
|  | Poly1305 | Poly1305 |
|  | Kmac128 | KMAC128 with a fixed-length output of 256 bits (32 bytes) |
|  | Kmac256 | KMAC256 with a fixed-length output of 512 bits (64 bytes) |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Mode"></a>Mode Enumeration

 Cipher Mode 

#### Syntax

[`C#`]

```
public enum Mode
```

[`VB.NET`]

```
Public Enumeration Mode
```

#### Members

|  | Member name | Description |
|  | ECB | Electronic Code Book mode |
|  | CBC | Cipher Block Chaining mode |
|  | OFB | Output Feedback mode |
|  | CFB | Cipher Feedback mode |
|  | CTR | Counter mode |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Padding"></a>Padding Enumeration

 Block Cipher Padding 

#### Syntax

[`C#`]

```
public enum Padding
```

[`VB.NET`]

```
Public Enumeration Padding
```

#### Members

|  | Member name | Description |
|  | Default | Use default padding |
|  | NoPad | No padding is added |
|  | Pkcs5 | The padding scheme described in PKCS#5 |
|  | OneAndZeroes | Pads with 0x80 followed by as many zero bytes necessary to fill the block |
|  | AnsiX923 | The padding scheme described in ANSI X9.23 |
|  | W3CPadding | The padding scheme described in W3C https://www.w3.org/TR/xmlenc-core1/#sec-Padding |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_PrfAlgorithm"></a>PrfAlgorithm Enumeration

 Pseudorandom function (PRF) algorithm. 

#### Syntax

[`C#`]

```
public enum PrfAlgorithm
```

[`VB.NET`]

```
Public Enumeration PrfAlgorithm
```

#### Members

|  | Member name | Description |
|  | Kmac128 | KMAC128 as per NIST SP 800-185 |
|  | Kmac256 | KMAC256 as per NIST SP 800-185 |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Rng_Options"></a>Rng.Options Enumeration

 Rng options 

#### Syntax

[`C#`]

```
public enum Options
```

[`VB.NET`]

```
Public Enumeration Options
```

#### Members

|  | Member name | Description |
|  | Default | Default option |
|  | NoIntelDrng | Turn off support for INTEL(R) DRNG for the current session. |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Rng_Strength"></a>Rng.Strength Enumeration

 Required security strength for user-prompted entropy 

#### Syntax

[`C#`]

```
public enum Strength
```

[`VB.NET`]

```
Public Enumeration Strength
```

#### Members

|  | Member name | Description |
|  | Default | Default option |
|  | Bits_112 | 112 bits of security (default) |
|  | Bits_128 | 128 bits of security |
|  | Bits_192 | 192 bits of security |
|  | Bits_256 | 256 bits of security |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_Wipe_Options"></a>Wipe.Options Enumeration

 Wipe options. 

#### Syntax

[`C#`]

```
public enum Options
```

[`VB.NET`]

```
Public Enumeration Options
```

#### Members

|  | Member name | Description |
|  | Default | Default options (DOD 7-pass) |
|  | Dod7Pass | DOD 7-pass (default) |
|  | Simple | Overwrite with single pass of zero bytes (quicker but less secure). |

[[Contents](#topofpage)] [[Index](#index)]

---

### <a id="T_XofAlgorithm"></a>XofAlgorithm Enumeration

 Extendable-output function (XOF) algorithm. 

#### Syntax

[`C#`]

```
public enum XofAlgorithm
```

[`VB.NET`]

```
Public Enumeration XofAlgorithm
```

#### Members

|  | Member name | Description |
|  | Shake128 | SHAKE128 as per FIPS PUB 202 |
|  | Shake256 | SHAKE256 as per FIPS PUB 202 |
|  | Mgf1_Sha1 | MGF1-SHA-1 (as per PKCS#1) |
|  | Mgf1_Sha256 | MGF1-SHA-256 (as per PKCS#1) |
|  | Mgf1_Sha512 | MGF1-SHA-512 (as per PKCS#1) |
|  | Ascon_Xof | ASCON-XOF extendable output function |
|  | Ascon_XofA | ASCON-XOFA extendable output function |

[[Contents](#topofpage)] [[Index](#index)]

---

<a id="errorcodes"></a>Error Codes
----------------------------------

Errors may be returned as a positive or negative number depending on the calling function.
For example, `BAD_KEY_ERROR` may be returned as -36 or +36.
To find the error message corresponding to a numerical error code use the
[`API_ErrorLookup`](#API_ErrorLookup) function or the [General.ErrorLookup](#M_General_ErrorLookup) Method.

[*Changed in v5.1*] 
Note that the error code numbering has been rationalised in v5.1 to match error codes in our other products.
See the table of [Changes in error codes in version 5.1](#changesinerrorcodes) below.

If you have hardcoded error code values in your code to catch a particular error, you will need to change it.

```

0 = OK, success, no error (SUCCESS_NO_ERROR)
1 = Cannot open input file (OPEN_ERROR)
2 = Cannot create output file (CREATE_ERROR)
3 = File read error (READ_ERROR)
4 = File write error (WRITE_ERROR)
5 = Not enough memory (MEMORY_ERROR)
6 = Parameter is wrong or missing (BAD_PARAM_ERROR)
7 = Data is in wrong format (BAD_FORMAT_ERROR)
8 = Invalid data (INVALID_DATA_ERROR)
9 = Unexpected end of file found (EOF_ERROR)
11 = Parameter out of range (RANGE_ERROR)
12 = Duplicate data or filename (DUP_ERROR)
14 = Unexpected NULL value (NULL_ERROR)
15 = Decryption error (DECRYPT_ERROR)
17 = Invalid option (BAD_FLAG_ERROR)
18 = Failed to wipe data (WIPE_ERROR)
19 = Item is not supported (NOT_SUPPORTED_ERROR)
23 = Failed a test e.g. known answer test (TEST_FAILED_ERROR)
26 = Data not a valid length (BAD_LENGTH_ERROR)
30 = Not enough room in output buffer (SHORT_BUF_ERROR)
31 = Zlib compression error (ZLIB_COMPR_ERROR)
33 = Invalid key length (BAD_KEY_LEN_ERROR)
34 = Invalid block length (BAD_BLK_LEN_ERROR)
35 = Invalid mode (BAD_MODE_ERROR)
36 = Invalid key (BAD_KEY_ERROR)
37 = Invalid initialization vector (BAD_IV_ERROR)
38 = Invalid IV length (BAD_IV_LEN_ERROR)
40 = Authentication failed (AUTH_FAIL_ERROR)
41 = Function called out of sequence (MISUSE_ERROR)
52 = Weak key (WEAK_KEY_ERROR)
64 = Invalid context handle (INVALID_HANDLE_ERROR)
201 = PRNG: Cannot open input file (PRNG_ERR_FILE_OPEN)
202 = PRNG: Cannot create output file (PRNG_ERR_FILE_CREATE)
203 = PRNG: File read error (PRNG_ERR_FILE_READ)
204 = PRNG: File write error (PRNG_ERR_FILE_WRITE)
205 = PRNG: File locking error (PRNG_ERR_FILE_LOCK)
210 = PRNG: Uninstantiation failed (PRNG_ERR_UNINST)
211 = PRNG: Requested length is too large (PRNG_ERR_TOOBIG)
212 = PRNG: Function failed (PRNG_ERR_FAILURE)
213 = PRNG: Invalid input parameter (PRNG_ERR_BADPARAM)
214 = PRNG: Function is not available (PRNG_ERR_NOTAVAIL)
299 = PRNG: Catastrophic failure (PRNG_ERR_CATASTROPHIC)
9745 = Something not expected to happen has happened (INTERNAL_ERROR)
9999 = Miscellaneous error (MISC_ERROR)

```

[[Contents](#topofpage)] [[Index](#index)]

### <a id="changesinerrorcodes"></a>Changes in error codes in version 5.1

The error code numbering was changed in version 5.1 as follows:

| Error | Old pre-v5.1 | New v5.1+ |
| --- | --- | --- |
| `BAD_LENGTH_ERROR` | 9 | 26 |
| `SHORT_BUF_ERROR` | 17 | 30 |
| `DECRYPT_ERROR` | 18 | 15 |
| `NULL_ERROR` | 39 | 14 |
| `BAD_KEY_ERROR` | 48 | 36 |
| `BAD_IV_ERROR` | 51 | 37 |
| `BAD_PARAM_ERROR` | 106 | 6 |
| `BAD_FORMAT_ERROR` | 107 | 7 |
| `EOF_ERROR` | 109 | 9 |
| `INVALID_DATA_ERROR` | 116 | 8 |
| `BAD_FLAG_ERROR` | 117 | 17 |
| `WIPE_ERROR` | 118 | 18 |
| `TEST_FAILED_ERROR` | 123 | 23 |
| `TOO_SHORT_ERROR` | 125 | - |
| `DUP_ERROR` | 126 | 12 |
| `MEMORY_ERROR` | 1024 | 5 |
| `BAD_IV_LEN_ERROR` | - | 38 |
| `AUTH_FAIL_ERROR` | - | 40 |
| `MISUSE_ERROR` | - | 41 |
| `INTERNAL_ERROR` | - | 9745 |

In particular, note that `DECRYPT_ERROR` has changed in value from 18 to 15,
or has been replaced by `AUTH_FAIL_ERROR` (40) to show an authentication failure in the (now-superseded) GCM functions.

[[Contents](#topofpage)] [[Index](#index)]

<a id="Acks"></a>Acknowledgements
---------------------------------

The source code used in
CryptoSys API
is original code written by David Ireland except for the following:

* The DES algorithm includes code by Richard Outerbridge
placed in the public domain August 1992.
* The Blowfish algorithm includes code published by Bruce Schneier in
*Applied Cryptography* 1996 [[SCHN96](#SCHN96)].
* The AES algorithm includes code placed
in the public domain by Vincent Rijmen, Antoon Bosselaers and Paulo Barreto
in December 2000.
* The SHA-1 algorithm includes code derived from 100% public domain code
by Steve Reid <steve@edmweb.com> with modifications based on
work by Peter Gutmann
as posted to sci.crypt in message <30ajo5$oe8@ccu2.auckland.ac.nz>.
* The HMAC algorithm includes code from RFC 2104 *HMAC: Keyed-Hashing for Message
Authentication* [[HMAC](#HMAC)].
* The ZLIB data compression utilities use source code with permission from the
*'zlib' general purpose compression library*
version 1.2.3 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler.
* The Zstandard data compression utilities use source code from
*Zstandard v1.5.0* [https://facebook.github.io/zstd/](https://facebook.github.io/zstd/ "External link")
under a 
[BSD License](https://github.com/facebook/zstd/blob/v1.5.0/LICENSE "External link"),
Copyright (c) 2016-present, Facebook, Inc.
* The code to prompt for keyboard entropy and wipe files is derived from code published in 
the *Secure Programming Cookbook* by John Viega and Matt Messier [[VIEG03](#VIEG03)].
* Some code to produce incidental pseudorandom numbers (*not* the core secure Random Number Generator) uses source code from "TinyMT32 Pseudo Random Number Generator (PRNG)" 
Copyright (c) 2011, 2013 Mutsuo Saito, Makoto Matsumoto, Hiroshima University and The University of Tokyo
under a BSD-3-Clause [license](https://github.com/MersenneTwister-Lab/TinyMT/blob/master/LICENSE.txt "External link").
* The code for RIPEMD-160 is adapted from software 
written by Antoon Bosselaers, available at <http://www.esat.kuleuven.be/~cosicart/ps/AB-9601/> [[RMD](#RMD)].
* The code for Salsa20 and ChaCha20 uses code derived from public domain code by D.J. Bernstein,
	<http://cr.yp.to/djb.html>.

* The code for Poly1305 uses code adapted from public domain software 
by Andrew Moon, <https://github.com/floodyberry/poly1305-donna>.
* The code for SHA-3 and its family uses code derived from public domain code by Ronny Van Keer, May 2012,
	<http://keccak.noekeon.org/>.

* The code for ASCON-128 and ASCON-HASH uses code from the Ascon v1.2 submission to NIST, May 2021,
issued under a CC0 1.0 Universal license,
	<https://ascon.iaik.tugraz.at/index.html>.

* The code to call Intel DRNG functions uses source code Copyright (C) 2014, Intel Corporation with [conditions](https://cryptosys.net/docs/intel_drng_license.txt "External link").
* The MD5 algorithm includes code derived from the *RSA Data Security, Inc. MD5 Message-Digest Algorithm*
[[RFC1321](#RFC1321)]
which is covered by the following copyright:

    > Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.

    > License to copy and use this software is granted provided that it is identified as the 
        > ``RSA Data Security, Inc. MD5 Message-Digest Algorithm'' in all material mentioning or 
        > referencing this software or this function.

    > License is also granted to make and use derivative works provided that such works are 
        > identified as ``derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm'' 
        > in all material mentioning or referencing the derived work.

    > RSA Data Security, Inc. makes no representations concerning either the merchantability 
        > of this software or the suitability of this software for any particular purpose. 
        > It is provided ``as is'' without express or implied warranty of any kind.

    > These notices must be retained in any copies of any part of this documentation and/or software.

* Ditto for MD2 [[RFC1319](#RFC1319)].

Thanks to the guys at NullSoft for their [Nullsoft Scriptable Install System](http://nsis.sourceforge.net/Main_Page "External link").

[[Contents](#topofpage)] [[Index](#index)]

<a id="index"></a>Index
-----------------------

| ['Hello world' programs](#helloworld) [.NET Classes and Methods](#dotnetmethods) [.NET Help File](#dotnethelp) [A caution about insecure default algorithms](#cautionwithdefaults) [Acknowledgements](#Acks) [ActiveX Classes and Methods](#activexmethods) [ActiveX Interface](#activexinterface) [Advanced Encryption Standard (AES) functions](#AESbyCat) [Aead Class](#mx_Aead) [AEAD functions](#AEADbyCat) [Aes128 Class](#mx_Aes128) [Aes192 Class](#mx_Aes192) [Aes256 Class](#mx_Aes256) [An interface for Authenticated Encryption with Associated Data (AEAD)](#aeadinterface) [ANSI C users must add one to this value...](#cusersaddone) [Authenticated Encryption with Additional Data (AEAD)](#aeadalgorithms) [Background Basics](#Background) [Block cipher algorithms](#blockcipher) [Block cipher functions](#CIPHERbyCat) [Block Cipher Modes and Initialization Vectors](#blockciphermodes) [Blowfish Class](#mx_Blowfish) [Blowfish functions](#BLFbyCat) [C++ (STL) Functions](#cppfunctions) [Cautions for C/C++ Users](#cautionsforcusers) [Changes in earlier versions](#changesearlier) [Changes in error codes in version 5.1](#changesinerrorcodes) [Changes in this version](#changesinthis) [Cipher Class](#mx_Cipher) [CipherStream Class](#mx_CipherStream) [Cnv Class](#mx_Cnv) [Combining bitwise options](#bitwiseoptions) [Common problems when encrypting](#commonproblems) [Compiling with C](#compilingwithc) [Compliance](#Compliance) [Compr Class](#mx_Compr) [Compression functions](#COMPRbyCat) [Conventions in this document](#Conventions) [Conversion functions](#CNVbyCat) [Converting strings to bytes and vice versa](#stringstobytes) [Converting VB6 to `VB.NET`](#vb6tovbnet) [Copyright Notice](#Copyright) [Correct sequence for AEAD incremental functions](#aeadsequence) [Crc Class](#mx_Crc) [Cross-reference between Functions and .NET Methods](#xrefdotnet) [Cyclic Redundancy Check functions](#CRCbyCat) [Data Compression in Cryptography](#compression) [Data Encryption Standard (DES) functions](#DESbyCat) | [Deprecated Functions](#deprecatedfunctions) [Des Class](#mx_Des) [Detecting Win32 or X64 platform](#detectingplatform) [Document Revision History](#revisions) [Empty byte arrays](#emptybytearrays) [Enumerations in .NET](#dotnetenumerations) [Error Codes](#errorcodes) [Extendable-output functions (XOF)](#XOFbyCat) [Extensions to block cipher functions for files](#extensionsforfiles) [Filenames with 'International' characters](#filenamesinternational) [Gcm Class](#mx_Gcm) [GCM functions](#GCMbyCat) [General Class](#mx_General) [General functions](#GENbyCat) [General Programming Issues](#generalprogramming) [Getting Started](#gettingstarted) [Hash Class](#mx_Hash) [Hexadecimal versus Bytes](#hexvsbytes) [Index](#index) [Installation](#installation) [Intel(R) DRNG support](#inteldrng) [Introduction](#Introduction) [KMAC: KECCAK Message Authentication Code](#kmac) [List of .Net Methods](#methodlist) [List of Functions](#functionlist) [Mac Class](#mx_Mac) [Md5 Class](#mx_Md5) [MD5 Hash Algorithm functions](#MD5byCat) [Message authentication code (MAC) functions](#macfunctions) [Message Authentication Code functions](#MACbyCat) [Message Digest Hash functions](#HASHbyCat) [Notes on SHA-3](#sha3notes) [Notes on VBA wrapper functions](#notesonvbawrapperfunctions) [One-way message digest (hash) functions](#hashfunctions) [Optional Registry Settings](#registrysettings) [Other Issues For VB6/VBA Users](#vb6vbaotherissues) [Padding](#padding) [Padding functions](#PADbyCat) [Padding schemes for block ciphers](#paddingschemes) [Passing a reference to an empty byte array in VB6/VBA](#passemptybytearray) [Password-based encryption functions](#PBEbyCat) [Pbe Class](#mx_Pbe) [Pc1 Class](#mx_Pc1) [PC1 Stream Cipher functions](#PC1byCat) [Pre-dimensioning for VB](#predimensioning) [Prf Class](#mx_Prf) [Pseudorandom functions (PRF)](#PRFbyCat) | [References](#refs) [Return Values](#ReturnValues) [Rng Class](#mx_Rng) [RNG Mechanisms](#rngmechanisms) [Secure Hash Algorithm (SHA-1) functions](#SHA1byCat) [Secure Hash Algorithm (SHA-256) functions](#SHA2byCat) [Secure Hash Algorithm (SHA-3) functions](#SHA3byCat) [Secure Random Number Generator](#rnginfo) [Secure Random Number Generator (RNG) functions](#RNGbyCat) [Security Issues](#SecurityIssues) [Self-Tests](#selftests) [Sha1 Class](#mx_Sha1) [Sha256 Class](#mx_Sha256) [Sha3 Class](#mx_Sha3) [Specifying the algorithm and mode for generic block cipher functions](#cipheralgmode) [Storing and representing ciphertext](#storingciphertext) [Stream cipher functions](#STREAMbyCat) [Stream ciphers](#streamcipher) [Summary of .NET Classes](#dotnetsummary) [Tdea Class](#mx_Tdea) [Technical Details](#technicaldetails) [Techniques to add known security strength to the RNG process](#rngtechniques) [The cipher suite ASCON](#ciphersuiteascon) [The Poly1305 message authentication algorithm](#poly1305algorithm) [Triple Data Encryption Algorithm (Triple DES) functions](#TDEAbyCat) [Type Conversions](#typeconversions) [User-supplied entropy (seeds)](#rngentropy) [Using with .NET: C# and `VB.NET`](#UsingWithDotNet) [Using with ANSI C](#UsingWithC) [Using With Borland C++](#borlandc) [Using with C++ (STL)](#UsingWithCpp) [Using with Classic Visual Basic and VBA](#UsingWithVB) [Using with COM/ASP](#UsingWithASP) [Valid key and block sizes for block cipher algorithms](#blockciphersizes) [VBA in 64-bit versions of Office](#vbain64bitoffice) [VBA Wrapper Function List](#vbawrapperfunctionlist) [VBA Wrapper Functions](#vbawrapperfunctions) [VBA/C Function Summary](#vb6funcsummary) [Visual Basic or Visual Basic: VB6 vs `VB.NET`](#vb6vsvbdotnet) [What is the CryptoSys API?](#WhatIs) [Win64 (X64) Platform](#win64platform) [Wipe Class](#mx_Wipe) [Wipe functions](#WIPEbyCat) [Xof Class](#mx_Xof) [XOF: eXtendable-Output Function](#xof) [Zero-length byte arrays in VB6/VBA](#zerolengthbytearrays) [Zlib Class](#mx_Zlib) |
| --- | --- | --- |

[[Contents](#topofpage)] [[Index](#index)]

<a id="revisions"></a>Document Revision History
-----------------------------------------------

Version 6.22.1a. Updated September 2025.
  

Version 6.22.1. Updated January 2024.
  

Version 6.22. Updated December 2023.
  

Version 6.21. Updated May 2023.
  

Version 6.20. Updated September 2021 (20th anniversary edition).
  

Version 6.0. Updated March 2021.
  

Version 5.4. Updated March 2020.
  

Version 5.3. Updated September 2018.
  

Version 5.2. Updated August 2016.
  

Version 5.1. Updated July 2015.
  

Version 5.0. Updated April 2015.
  

Version 4.7. Updated September 2013.
  

Version 4.6. Updated November 2012.
  

Version 4.5. Updated January 2011.
  

Version 4.4. Updated August 2010.
  

Version 4.3. Updated December 2009.
  

Version 4.2. Updated March 2009.
  

Version 4.1. Updated July 2008.
  

Version 4.0. Updated September 2007.
  

Version 3.2. Updated July 2006.
  

Version 3.1. Updated January 2006.
  

Version 3. Updated February 2005.
  

Version 2.1. Updated August 2003.
  

Version 2. Major update published February 2003.
  

Version 1. First published September 2001 by DI Management Services Pty Limited.

---

Copyright © 2001-25 D.I. Management Services Pty Limited t/a CryptoSys ABN 78 083 210 584, Australia.
All rights reserved.  

<[https://di-mgt.com.au](https://di-mgt.com.au/ "External link")>
<[https://cryptosys.net](https://cryptosys.net/ "External link")>

---

