MTE Fixed Length Add-On Code Examples
Purpose
The objective of an MTE fixed length "Examples" is to provide short examples of how to use the MTE fixed length Encoder and MTE Decoder.
The Fixed Length Add-On is a replacement for the core encoder that ensures all messages are encoded to a fixed length. If the input is too long, it will be truncated to the fixed length. If the input is shorter than the fixed length, random padding bytes will be added to the end of the input to the fixed length size. See code decoder samples for decoding examples.
The Fixed length add-on must be used if using the sequencing verifier with MTE and wish to decode asynchronously or recover from missing MTE packets. For more information, please see the official MTE developer guides.
MTE Fixed Length (FLEN) Encoder
Create MTE FLEN Encoder
The MTE FLEN Encoder will be created using default options. The default options will set preferred security options recommended by Eclypses. Custom options should only be used in special circumstances and after reading and understanding how to select the best options for a given situation. More information about how to select these options can be found in the official MTE Developer Guides.
Create Default Encoder
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
/* Status. */
mte_status status;
/* Licensing. */
const char* company;
const char* license;
/* Suppress unused args. */
(void)argc;
(void)argv;
/* Initialize MTE. */
if (!mte_init(NULL, NULL))
{
fputs("MTE init error.", stderr);
return -1;
}
/* Initialize MTE license. If a license code is not required (e.g., trial
mode), this can be skipped. This demo attempts to load the license info
from the environment if required. */
if (!mte_license_init("YOUR_COMPANY", "YOUR_LICENSE"))
{
company = getenv("MTE_COMPANY");
license = getenv("MTE_LICENSE");
if (company == NULL || license == NULL ||
!mte_license_init(company, license))
{
fprintf(stderr, "License init error (%s): %s\n",
mte_base_status_name(mte_status_license_error),
mte_base_status_description(mte_status_license_error));
return mte_status_license_error;
}
}
/* Get the input data. */
printf("Enter the data to encode> ");
fflush(stdout);
(void)!fgets(input, sizeof(input), stdin);
input[strlen(input) - 1] = '\0';
input_bytes = (MTE_SIZE_T)strlen(input);
/* Get the personalization string. */
printf("Enter the personalization> ");
fflush(stdout);
(void)!fgets(personal, sizeof(personal), stdin);
personal[strlen(personal) - 1] = '\0';
mte_drbg_inst_info i_info = { &ei_cb, NULL, &n_cb, NULL, personal, 0 };
i_info.ps_bytes = (MTE_SIZE_T)strlen(personal);
/* Create the encoder. */
MTE_HANDLE encoder;
mte_flen_enc_init_info e_info = MTE_FLEN_ENC_INIT_INFO_INIT(
MTE_DRBG_ENUM, MTE_TOKBYTES, MTE_VERIFIERS_ENUM, 8, NULL, NULL);
mte_enc_args e_args = MTE_ENC_ARGS_INIT(NULL, 0, NULL, &t_cb, NULL);
encoder = MTE_ALLOCA(mte_flen_enc_state_bytes(&e_info));
status = mte_flen_enc_state_init(encoder, &e_info);
if (status != mte_status_success)
{
fprintf(stderr, "Encoder init error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
status = mte_flen_enc_instantiate(encoder, &i_info);
if (status != mte_status_success)
{
fprintf(stderr, "Encoder instantiate error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
The entropy and nonce callbacks.
static mte_status ei_cb(void* context, mte_drbg_ei_info* info)
{
MTE_SIZE_T input_bytes;
(void)context;
/* Get the entropy. */
printf("Enter %u-%lu bytes of entropy> ",
(unsigned)info->min_length,
(unsigned long)info->max_length);
fflush(stdout);
(void)!fgets(ei_buff, sizeof(ei_buff), stdin);
input_bytes = (MTE_SIZE_T)(strlen(ei_buff) - 1);
/* If the entropy is less than the minimum required, we must return an
error. */
if (input_bytes < info->min_length)
{
return mte_status_drbg_catastrophic;
}
else if (input_bytes > info->bytes)
{
/* If the entropy is longer than the provided buffer, point at our buffer
instead. */
info->buff = (MTE_UINT8_T*)ei_buff;
}
else
{
/* Otherwise copy the entropy to the provided buffer. */
memcpy(info->buff, ei_buff, input_bytes);
}
/* Set the actual entropy length. */
info->bytes = input_bytes;
/* We got it successfully. */
return mte_status_success;
}
static void n_cb(void* context, mte_drbg_nonce_info* info)
{
MTE_SIZE8_T i;
MTE_UINT64_T u64;
char line[80];
(void)context;
/* Get the nonce. */
printf("Enter the nonce (decimal digits only)> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
u64 = strtoul(line, NULL, 10);
/* Copy the nonce in little-endian format to the nonce buffer. */
for (i = 0; i < info->max_length && i < sizeof(u64); ++i)
{
info->buff[i] = (MTE_UINT8_T)(u64 >> (i * 8));
}
/* If the minimum length is greater than the size of the nonce we got, fill
up to that length with zeros. */
for (; i < info->min_length; ++i)
{
info->buff[i] = 0;
}
/* Set the actual nonce length. */
info->bytes = i;
}
// Create the callbacks to get entropy, nonce, and timestamp from stdin.
Cbs cbs;
static const size_t fixedBytes = 8;
// Create the encoder.
MteFlenEnc encoder(fixedBytes);
encoder.setEntropyCallback(&cbs);
encoder.setNonceCallback(&cbs);
encoder.setTimestampCallback(&cbs);
status = encoder.instantiate(personal);
if (status != mte_status_success)
{
std::cerr << "Encoder instantiate error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
The entropy and nonce callbacks.
mte_status Cbs::entropyCallback(mte_drbg_ei_info& info)
{
// Display a prompt.
std::cout << "Enter "
<< static_cast<size_t>(info.min_length) << '-' << info.max_length
<< " bytes of entropy> " << std::flush;
// Get a line of input.
std::string line;
std::cin >> line;
// If the input was less than the minimum required, we must return an error.
if (line.size() < info.min_length)
{
return mte_status_drbg_catastrophic;
}
// Set the actual entropy length. It cannot exceed the maximum required.
size_t buffBytes = info.bytes;
info.bytes = std::min(static_cast<MTE_SIZE_T>(line.size()), info.max_length);
// If the length is greater than the length of the provided buffer, we have
// to create our own buffer instead.
if (info.bytes > buffBytes)
{
delete [] myEntropy;
myEntropy = new uint8_t[info.bytes];
info.buff = myEntropy;
}
// Copy the entropy to the buffer and we got it successfully.
memcpy(info.buff, line.data(), info.bytes);
return mte_status_success;
}
void Cbs::nonceCallback(mte_drbg_nonce_info& info)
{
// Display a prompt.
std::cout << "Enter the nonce (decimal digits only)> " << std::flush;
// Get the nonce and ignore the rest of the line.
MTE_UINT64_T u64;
std::cin >> u64;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Copy the nonce in little-endian format to the nonce buffer.
size_t i;
for (i = 0; i < info.max_length && i < sizeof(u64); ++i)
{
info.buff[i] = static_cast<MTE_UINT8_T>(u64 >> (i * 8));
}
// If the minimum length is greater than the size of the nonce we got, fill
// up to that length with zeros.
for (; i < info.min_length; ++i)
{
info.buff[i] = 0;
}
// Set the actual nonce length.
info.bytes = static_cast<MTE_SIZE8_T>(i);
}
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
int fixedBytes = 20;
// Create MTE Core Encoder with defaults
MteFlenEnc flenEncoder = new MteFlenEnc(fixedBytes);
// Need entropy, nonce and personalization string
// *** IMPORTANT NOTE ***
// Entropy is critical to security and should be created and
// handled like encryption keys. To permit decoding of encoded
// value, Encoder and Decoder must use identical Entropy, Nonce and
// Personalization String as well as Options . See Developer Guides for more information.
//-----------------------------------------------------------------
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
string personalizationString = "MySecretPersonalizationStringGoesHere";
long nonce = 12345678;
// Check how long of entropy we need.
// This example fills entropy with at string of zeros
// this should NOT be used in a production environment
int entropyMinBytes = flenEncoder.GetDrbgsEntropyMinBytes(flenEncoder.GetDrbg());
string entropy = (entropyMinBytes > 0)
? new String('0', entropyMinBytes)
: string.Empty;
// Set Encoder entropy and nonce
flenEncoder.SetEntropy(Encoding.UTF8.GetBytes(entropy));
flenEncoder.SetNonce(nonce);
// Initialize MTE Encoder
MteStatus encoderStatus = flenEncoder.Instantiate(personalizationString);
if(encoderStatus !=MteStatus.mte_status_success)
{
// MTE cannot continue so handle failure appropriately
// Below is an Example
throw new ApplicationException($"Failed to initialize the MTE Encoder engine." +
$"Status: {flenEncoder.GetStatusName(encoderStatus)} / " +
$"{flenEncoder.GetStatusDescription(encoderStatus)}");
}
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
int fixedBytes = 20;
// Create the MTE Encoder
MteFlenEnc flenEncoder = new MteFlenEnc(fixedBytes);
// Need entropy, nonce and personalization string
// *** IMPORTANT NOTE ***
// Entropy is critical to security and should be created and
// handled like encryption keys. To permit decoding of encoded
// value, Encoder and Decoder must use identical Entropy, Nonce and
// Personalization String as well as Options . See Developer Guides for more information.
//-----------------------------------------------------------------
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
String personalizationString = "MySecretPersonalizationStringGoesHere";
long nonce = 12345678;
// Check how long of entropy we need.
// This example fills entropy with at string of zeros
// this should NOT be used in a production environment
int entropyMinBytes = MteBase.getDrbgsEntropyMinBytes(flenEncoder.getDrbg());
StringBuffer outputBuffer = new StringBuffer(entropyMinBytes);
for (int i = 0; i < entropyMinBytes; i++){
outputBuffer.append("0");
}
String entropy = outputBuffer.toString();
entropy.replace(' ', '0');
// Set Encoder entropy and nonce
flenEncoder.setEntropy(flenEncoder.getBytes());
flenEncoder.setNonce(nonce);
// Initialize MTE Encoder
MteStatus encoderStatus = flenEncoder.instantiate(personalizationString.getBytes());
if (encoderStatus != MteStatus.mte_status_success)
{
// MTE cannot continue so handle failure appropriately
// Below is an Example
throw new Exception("Failed to initialize the MTE Encoder engine. Status: "
+ flenEncoder.getStatusName(encoderStatus)+ " / "
+ flenEncoder.getStatusDescription(encoderStatus));
}
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
const fixedBytes = 20;
// Create and instantiate MteWasm
const wasm = new MteWasm();
await wasm.instantiate();
// Create MTE Core Encoder with defaults
const flenEncoder = MteFlenEnc.fromDefault(wasm, fixedBytes);
// Need entropy, nonce and personalization string
// *** IMPORTANT NOTE ***
// Entropy is critical to security and should be created and
// handled like encryption keys. To permit decoding of encoded
// value, Encoder and Decoder must use identical Entropy, Nonce and
// Personalization String as well as Options . See Developer Guides for more information.
//-----------------------------------------------------------------
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
const personalizationString = "MySecretPersonalizationStringGoesHere";
const nonce = 12345678;
// Check how long of entropy we need.
// This example fills entropy with at string of zeros
// this should NOT be used in a production environment
const entropyMinBytes = flenEncoder.getDrbgsEntropyMinBytes(
flenEncoder.getDrbg(),
);
const encoderEntropy =
entropyMinBytes > 0 ? "0".repeat(entropyMinBytes) : encoderEntropy;
// Set Encoder entropy and nonce
flenEncoder.setEntropy(encoderEntropy);
flenEncoder.setNonce(nonce);
// Initialize MTE Encoder
const encoderStatus = flenEncoder.instantiate(personalizationString);
if (encoderStatus !== MteStatus.mte_status_success) {
// MTE cannot continue so handle failure appropriately
// Below is an Example
throw new Error(
`Failed to initialize the MTE Encoder engine.` +
`Status: ${flenEncoder.getStatusName(encoderStatus)} / ` +
`${flenEncoder.getStatusDescription(encoderStatus)}`,
);
}
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
let fixedBytes = 8
// Create the encoder.
let encoder = try! MteFlenEnc(fixedBytes)
encoder.setEntropyCallback(cbs)
encoder.setNonceCallback(cbs)
encoder.setTimestampCallback(cbs)
status = encoder.instantiate(personal)
if status != mte_status_success {
print("Encoder instantiate error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
The entropy and nonce callbacks.
class Cbs: MteEntropyCallback, MteNonceCallback, MteTimestampCallback {
func entropyCallback(_ minEntropy: Int,
_ minLength: Int,
_ maxLength: UInt64,
_ entropyInput: inout [UInt8],
_ eiBytes: inout UInt64,
_ entropyLong: inout UnsafeMutableRawPointer?) -> mte_status {
// Display a prompt.
print("Enter \(minLength)-\(maxLength) bytes of entropy> ", terminator: "")
// Get a line of input.
let line = readLine()!
// If the input was less than the minimum required, we must return an error.
if line.utf8.count < minLength {
return mte_status_drbg_catastrophic
}
// Set the actual entropy length. It cannot exceed the maximum required.
let buffBytes = eiBytes
eiBytes = min(UInt64(line.utf8.count), maxLength)
// If the length is greater than the length of the provided buffer, we have
// to create our own buffer instead.
if eiBytes > buffBytes {
// Get the entropy input as an array.
let ei = [UInt8](line.utf8)
// If there is previous raw entropy, deallocate it.
if myEntropyRaw != nil {
myEntropyRaw!.deallocate()
}
// Allocate unsafe memory for the entropy.
myEntropyRaw =
UnsafeMutableRawPointer.allocate(byteCount: ei.count, alignment: 16)
// Copy from the entropy array to the unsafe memory.
ei.withUnsafeBytes { buff in
let raw = myEntropyRaw!.assumingMemoryBound(to: UInt8.self)
let ei = buff.bindMemory(to: UInt8.self)
raw.assign(from: ei.baseAddress!, count: ei.count)
}
// Set the raw pointer to point at the unsafe memory.
entropyLong = myEntropyRaw
}
else {
// Copy the entropy to the buffer.
entropyInput.replaceSubrange(Range(uncheckedBounds: (0, Int(eiBytes))),
with: line.utf8.prefix(Int(eiBytes)))
}
// Success.
return mte_status_success
}
func nonceCallback(_ minLength: Int,
_ maxLength: Int,
_ nonce: inout [UInt8],
_ nBytes: inout Int) {
// Display a prompt.
print("Enter the nonce (decimal digits only)> ", terminator: "")
// Get the nonce and ignore the rest of the line.
let u64 = UInt64(readLine()!)!
// Copy the nonce in little-endian format to the nonce buffer.
let nCopied = min(nonce.count, MemoryLayout.size(ofValue: u64))
for i in 0..<nCopied {
nonce[i] = UInt8(UInt64(u64 >> (i * 8)) & 0xFF)
}
// If the minimum length is greater than the size of the nonce we got, fill
// up to that length with zeros.
if nCopied < minLength {
for i in nCopied..<minLength {
nonce[i] = 0
}
nBytes = minLength
}
else {
nBytes = nCopied
}
}
# The fixed length each MTE packet will be equal.
# To avoid data loss this number must be larger
# than any anticipated input data.
fixed_bytes = 20
# Create MTE FLEN Encoder with defaults.
flen_encoder = MteFlenEnc.fromdefault(fixed_bytes)
# Need entropy, nonce and personalization string
# *** IMPORTANT NOTE ***
# Entropy is critical to security and should be created and
# handled like encryption keys. To permit decoding of encoded
# value, Encoder and Decoder must use identical Entropy, Nonce and
# Personalization String as well as Options. See Developer Guides for more information.
#-----------------------------------------------------------------
# The following personalization string and nonce values are for
# demonstration only and should not be used in a production environment.
personalization_string = "MySecretPersonalizationStringGoesHere"
nonce = 12345678
# Check how long of entropy we need.
# This example fills entropy with at string of zeros.
# This should NOT be used in a production environment.
entropy_min_bytes = MteBase.get_drbgs_entropy_min_bytes(flen_encoder.get_drbg())
entropy = bytes("0" * entropy_min_bytes, 'utf-8')
# Set Encoder entropy and nonce.
flen_encoder.set_entropy(entropy)
flen_encoder.set_nonce(nonce)
# Initialize MTE Encoder.
encoder_status = flen_encoder.instantiate(personalization_string)
if encoder_status != MteStatus.mte_status_success:
# MTE cannot continue so handle failure appropriately.
# Below is an Example.
raise Exception("Failed to initialize the MTE Encoder engine. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
fixedBytes := 20;
// Create Encoder with default options
// In practice, you will create an Encoder this way, create a custom Encoder,
// or create MKE or FLEN Encoder. See developer guide for more information
flenEncoder := mte.NewFlenEncDef(fixedBytes)
defer flenEncoder.Destroy()
// Need entropy, nonce and personalization string
// *** IMPORTANT NOTE ***
// Entropy is critical to security and should be created and
// handled like encryption keys. To permit decoding of encoded
// value, Encoder and Decoder must use identical Entropy, Nonce and
// Personalization String as well as Options . See Developer Guides for more information.
//-----------------------------------------------------------------
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
personalizationString := "MySecretPersonalizationStringGoesHere"
nonce := 12345678
// Check how long of entropy we need.
// This example fills entropy with at string of zeros
// this should NOT be used in a production environment
entropyBytes := mte.GetDrbgsEntropyMinBytes(mteEncoder.GetDrbg())
entropy := make([]byte, entropyBytes)
// Set entropy and nonce
flenEncoder.SetEntropy(entropy)
flenEncoder.SetNonceInt(nonce)
// Instantiate the Encoder.
encoderStatus := flenEncoder.InstantiateStr(personalizationString)
if encoderStatus != mte.Status_mte_status_success {
// Handle an error here -- below is a sample
fmt.Fprintf(os.Stderr, "Encoder instantiate error (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
<?php
// The fixed length each MTE packet will be equal.
// To avoid data loss this number must be larger
// than any anticipated input data.
$fixedBytes = 20;
// Create Encoder with default options
// In practice, you will create an Encoder this way, create a custom Encoder,
// or create MKE or FLEN Encoder. See developer guide for more information
$flenEncoder = new MteFlenEnc($fixedBytes);
// Need entropy, nonce and personalization string
// *** IMPORTANT NOTE ***
// Entropy is critical to security and should be created and
// handled like encryption keys. To permit decoding of encoded
// value, Encoder and Decoder must use identical Entropy, Nonce and
// Personalization String as well as Options . See Developer Guides for more information.
//-----------------------------------------------------------------
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
$personalizationString = "MySecretPersonalizationStringGoesHere";
$nonce = 12345678;
// Check how long of entropy we need.
// This example fills entropy with at string of zeros
// this should NOT be used in a production environment
$entropyBytes = $mkeEncoder->getDrbgEntropyMinBytes(constant($mkeEncoder->getDrbg()));
$entropy = "";
$entropy = str_pad($entropy, $entropyBytes);
// Set entropy and nonce
$flenEncoder->setEntropy($entropy);
$flenEncoder->setNonce($nonce);
// Instantiate the Encoder.
$encoded = $flenEncoder->instantiate($personalizationString);
if (constant($encoded["status"])==mte_status_success) {
// Handle an error here -- below is a sample
echo "Flen Encoder instantiate error: "
.$flenEncoder->getStatusName(constant($encoded["status"])).":"
.$flenEncoder->getStatusDescription(constant($encoded["status"]));
return $flenEncoder->getStatusCode(constant($encoded["status"]));
}
?>
Encoding to a base64 string or byte[]
Use the following methods to encode a string or a byte[]. The samples below display all the options that can be used to encode, only one method needs to be used to encode the data. The developer should select the method that works with the type of data that is used.
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
/* There are different functions available to use depending on program needs.
* The versions with b64 in the function name involve base 64 conversion,
* suitable for protocols requiring a string representation.
* Otherwise the default will use raw bytes.
*/
/* Allocate the buffer for encoding. */
char* encoded = MTE_ALLOCA(mte_flen_enc_buff_bytes_b64(encoder));
/* Encode the message. */
MTE_SET_ENC_IO(e_args, input, input_bytes, encoded);
status = mte_flen_enc_encode_b64(encoder, &e_args);
if (status != mte_status_success)
{
fprintf(stderr, "Encode error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
The timestamp callback.
static MTE_UINT64_T t_cb(void* context)
{
char line[80];
(void)context;
/* Get the timestamp. */
printf("Enter the timestamp (decimal digits only)> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
return strtoul(line, NULL, 10);
}
// There are different functions available to use depending on program needs.
// The versions with b64 in the function name involve base 64 conversion,
// suitable for protocols requiring a string representation.
// Otherwise the default will use raw bytes.
size_t encodedBytes = 0;
// Encode the message.
const void* encoded = encoder.encode(input, inputBytes, encodedBytes, status);
if (status != mte_status_success)
{
std::cerr << "Encode error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
The timestamp callback.
MTE_UINT64_T Cbs::timestampCallback()
{
// Display a prompt.
std::cout << "Enter the timestamp (decimal digits only)> " << std::flush;
// Get the timestamp and ignore the rest of the line.
MTE_UINT64_T u64;
std::cin >> u64;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return u64;
}
// Fixed length must be at least as long as the largest expected input size.
// Padding will be added to the input if necessary so they are always the same size.
// Example values to be encoded.
string inputString = "What I want to be encoded goes here";
byte[] bytesToBeEncoded = Encoding.ASCII.GetBytes(inputString);
// Create MteStatus variable.
MteStatus encoderStatus;
// Below are 4 different examples of how to encode.
// ONLY ONE needs to be used.
// Encode byte[] to a base64 string
string encodedBytesAsString = flenEncoder.EncodeB64(bytesToBeEncoded, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Encode string to a base64 string
string encodedStringAsString = flenEncoder.EncodeB64(inputString, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Encode byte[] to a byte[]
byte[] encodedBytesAsBytes = flenEncoder.Encode(bytesToBeEncoded, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Encode string to a byte[]
byte[] encodedStringAsBytes = flenEncoder.Encode(inputString, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Fixed length must be at least as long as the largest expected input size.
// Padding will be added to the input if necessary so they are always the same size.
// Example values to be encoded.
String inputString = "What I want to be encoded goes here";
byte[] bytesToBeEncoded = inputString.getBytes(StandardCharsets.UTF_16);
// Create MteStatus variable.
MteStatus encoderStatus;
// Below are 4 different examples of how to encode
// ONLY ONE needs to be used.
// Encode byte[] to a base64 string
String encodedBytesAsString = flenEncoder.encodeB64(bytesToBeEncoded, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Encode string to a base64 string
String encodedStringAsString = flenEncoder.encodeB64(inputString, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Encode byte[] to a byte[]
byte[] encodedBytesAsBytes = flenEncoder.encode(bytesToBeEncoded, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Encode string to a byte[]
byte[] encodedStringAsBytes = flenEncoder.encode(inputString, out encoderStatus);
if(encoderStatus != MteStatus.mte_status_success)
{
// Handle encode failure appropriately
// Below is only an example
throw new Exception("Failed to encode. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
Below are 4 different examples of how to encode. ONLY ONE needs to be used.
// Fixed length must be at least as long as the largest expected input size.
// Padding will be added to the input if necessary so they are always the same size.
// Example values to be encoded.
const inputString = "What I want to be encoded goes here";
const encoderResult = flenEncoder.encodeStrB64(inputString);
if (encoderResult.status !== MteStatus.mte_status_success) {
const status = mteBase.getStatusName(encoderResult);
const message = mteBase.getStatusDescription(encoderResult);
throw new Error(`Failed to encode. Status ${status}: ${message}`);
}
// encoderResult.str contains encoded result
// encode string and return as Uint8Array
const inputString = "What I want to be encoded goes here";
const encoderResult = flenEncoder.encoderStr(inputString);
if (encoderResult.status !== MteStatus.mte_status_success) {
const status = mteBase.getStatusName(encoderResult);
const message = mteBase.getStatusDescription(encoderResult);
throw new Error(`Failed to encode. Status ${status}: ${message}`);
}
// encoderResult.arr contains encoded result
// encode Uint8Array and return as b64 string
const inputBytes = new Uint8Array([9, 19, 89]);
const encoderResult = flenEncoder.encodeB64(inputBytes);
if (encoderResult.status !== MteStatus.mte_status_success) {
const status = mteBase.getStatusName(encoderResult);
const message = mteBase.getStatusDescription(encoderResult);
throw new Error(`Failed to encode. Status ${status}: ${message}`);
}
// encoderResult.str contains encoded result
// encode Uint8Array and return as Uint8Array
const inputBytes = new Uint8Array([9, 19, 89]);
const encoderResult = flenEncoder.encode(inputBytes);
if (encoderResult.status !== MteStatus.mte_status_success) {
const status = mteBase.getStatusName(encoderResult);
const message = mteBase.getStatusDescription(encoderResult);
throw new Error(`Failed to encode. Status ${status}: ${message}`);
}
// encoderResult.arr contains encoded result
// There are different functions available to use depending on program needs.
// The versions with b64 in the function name involve base 64 conversion,
// suitable for protocols requiring a string representation.
// Otherwise the default will use raw bytes.
// Encode the message.
let encodedRes = encoder.encode(input)
status = encodedRes.status
if (status != mte_status_success) {
print("Encode error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
The timestamp callback.
func timestampCallback() -> UInt64 {
// Display a prompt.
print("Enter the timestamp (decimal digits only)> ", terminator: "")
// Get the timestamp and ignore the rest of the line.
return UInt64(readLine()!)!
}
# Fixed length must be at least as long as the largest expected input size.
# Padding will be added to the input if necessary so they are always the same size.
# Example values to be encoded.
input_string = "What I want to be encoded goes here"
bytes_to_be_encoded = bytes(input_string,'utf-8')
# Below are 4 different examples of how to encode.
# ONLY ONE needs to be used.
# Encode byte[] to a base64 string.
(encoded_bytes_as_string, encoder_status) = flen_encoder.encode_b64(bytes_to_be_encoded)
if encoder_status != MteStatus.mte_status_success:
# Handle encode failure appropriately.
# Below is only an example.
raise Exception("Failed to encode. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
# Encode string to a base64 string.
(encoded_string_as_string, encoder_status) = flen_encoder.encode_b64(input_string)
if encoder_status != MteStatus.mte_status_success:
# Handle encode failure appropriately.
# Below is only an example.
raise Exception("Failed to encode. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
# Encode byte[] to a byte[].
(encoded_bytes_as_string, encoder_status) = flen_encoder.encode(bytes_to_be_encoded)
if encoder_status != MteStatus.mte_status_success:
# Handle encode failure appropriately.
# Below is only an example.
raise Exception("Failed to encode. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
# Encode string to a byte[].
(encoded_string_as_bytes, encoder_status) = flen_encoder.encode(input_string)
if encoder_status != MteStatus.mte_status_success:
# Handle encode failure appropriately.
# Below is only an example.
raise Exception("Failed to encode. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
// Fixed length must be at least as long as the largest expected input size.
// Padding will be added to the input if necessary so they are always the same size.
// Example values to be encoded.
inputString := "What I want to be encoded goes here"
inputBytes := []byte(inputString)
// Create MteStatus variable.
var encoderStatus mte.Status
// Below are 4 different examples of how to encode
// ONLY ONE needs to be used.
// Encode string to a base64 string
encodedString, encoderStatus := flenEncoder.EncodeStrB64(inputString)
if(encoderStatus != mte.Status_mte_status_success){
// Handle error -- example below
fmt.Fprintf(os.Stderr, "Failed to encode. Status (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
// Encode byte[] to a base64 string
encodedString, encoderStatus := flenEncoder.EncodeB64(inputBytes)
if(encoderStatus != mte.Status_mte_status_success){
// Handle error -- example below
fmt.Fprintf(os.Stderr, "Failed to encode. Status (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
// Encode string to a byte array
encodedBytes, encoderStatus := flenEncoder.EncodeStr(inputString)
if(encoderStatus != mte.Status_mte_status_success){
// Handle error -- example below
fmt.Fprintf(os.Stderr, "Failed to encode. Status (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
// Encode bytes to a byte array
encodedBytes, encoderStatus := flenEncoder.Encode(inputBytes)
if(encoderStatus != mte.Status_mte_status_success){
// Handle error -- example below
fmt.Fprintf(os.Stderr, "Failed to encode. Status (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
<?php
// Example value to be encoded
$inputString = "What I want to be encoded goes here";
// Below are 2 different examples of how to encode
// ONLY ONE needs to be used!!!
?>
<?php
// Encode String to String
$encoded = $flenEncoder->encode($inputString);
// Check the status
if (constant($encoded["status"])!=mte_status_success){
// Handle an error here -- below is a sample
throw new Exception("Failed to encode. Status "
.$flenEncoder->getStatusName(constant($encoded["status"])).":"
.$flenEncoder->getStatusDescription(constant($encoded["status"])));
}
?>
<?php
// Encode string to Base64 String
$base64encoded = $flenEncoder->encodeB64($inputString);
// Check the status
if (constant($base64encoded["status"])!=mte_status_success){
// Handle an error here -- below is a sample
throw new Exception("Failed to encode. Status "
.$flenEncoder->getStatusName(constant($base64encoded["status"])).":"
.$flenEncoder->getStatusDescription(constant($base64encoded["status"])));
}
?>
FLEN Encoder State
The FLEN encoder state can be saved and restored with either byte[] or a base64 string using the following methods. Below are several examples of how to use it, based on your data type you only need to use one of the following examples.
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
Save state.
/* There are different functions available to use depending on program needs.
* The versions with b64 in the function name involve base 64 conversion,
* suitable for protocols requiring a string representation.
* Otherwise the default will use raw bytes.
*/
/* Save the encoder state. */
/* Saved state. */
MTE_UINT8_T* e_saved = MTE_ALLOCA(mte_flen_enc_save_bytes(encoder));
status = mte_flen_enc_state_save(encoder, e_saved);
if (status != mte_status_success)
{
fputs("Encoder state save error.", stderr);
return mte_status_unsupported;
}
Restore state.
/* Restore the encoder state. */
status = mte_flen_enc_state_restore(encoder, e_saved);
if (status != mte_status_success)
{
fprintf(stderr, "Encoder state restore error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
Save state.
// There are different functions available to use depending on program needs.
// The versions with b64 in the function name involve base 64 conversion,
// suitable for protocols requiring a string representation.
// Otherwise the default will use raw bytes.
// Save the encoder state.
size_t eSavedBytes = 0;
const void* esaved = encoder.saveState(eSavedBytes);
if (esaved == NULL)
{
std::cerr << "Encoder state save error." << std::endl;
return mte_status_unsupported;
}
Restore state.
// Restore the encoder state.
status = encoder.restoreState(esaved);
if (status != mte_status_success)
{
std::cerr << "Encoder state restore error." << std::endl;
return status;
}
// Save and restore Encoder state with bytes
// Get byte[] of Encoder state
byte[] encoderByteState = flenEncoder.SaveState();
// Restore Encoder with byte[] state
MteStatus encoderStatus = flenEncoder.RestoreState(encoderByteState);
if(encoderStatus != MteStatus.mte_status_success)
{
// Mte cannot continue, handle restore failure appropriately
// Below is only an example
throw new Exception("Failed to restore Encoder state. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Save and restore Encoder state with string
// Get string of Encoder state
string encoderStrState = flenEncoder.SaveStateB64();
// Restore Encoder with string state
MteStatus encoderStatus = flenEncoder.RestoreStateB64(encoderStrState);
if(encoderStatus != MteStatus.mte_status_success)
{
// Mte cannot continue, handle restore failure appropriately
// Below is only an example
throw new Exception("Failed to restore Encoder state. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Save and restore Encoder state with bytes
// Get byte[] of Encoder state
byte[] encoderByteState = flenEncoder.saveState();
// Restore Encoder with byte[] state
MteStatus encoderStatus = flenEncoder.restoreState(encoderByteState);
if(encoderStatus != MteStatus.mte_status_success)
{
// Mte cannot continue, handle restore failure appropriately
// Below is only an example
throw new Exception("Failed to restore Encoder state. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Restore Encoder with string state
// Get string of Encoder state
string encoderStrState = flenEncoder.saveStateB64();
// Restore Encoder with byte[] state
MteStatus encoderStatus = flenEncoder.restoreStateB64(encoderStrState);
if(encoderStatus != MteStatus.mte_status_success)
{
// Mte cannot continue, handle restore failure appropriately
// Below is only an example
throw new Exception("Failed to restore Encoder state. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Save Encoder state as Uint8Array
const state = flenEncoder.saveState();
// restore Encoder from Uint8Array
const encoderStatus = flenEncoder.restoreState(state);
if (encoderStatus !== MteStatus.mte_status_success) {
// MTE cannot continue, handle restore failure appropriately
// Below is only an example
throw new Error(
`Failed to restore Encoder state.` +
`Status: ${flenEncoder.GetStatusName(encoderStatus)} / ` +
`${flenEncoder.GetStatusDescription(encoderStatus)}`,
);
}
// Save Encoder state as Base64 String
const state = flenEncoder.saveStateB64();
// restore Encoder from Base64 state
const encoderState = flenEncoder.restoreStateB64(state);
if (encoderStatus !== MteStatus.mte_status_success) {
// MTE cannot continue, handle restore failure appropriately
// Below is only an example
throw new Error(
`Failed to restore Encoder state.` +
`Status: ${flenEncoder.GetStatusName(encoderStatus)} / ` +
`${flenEncoder.GetStatusDescription(encoderStatus)}`,
);
}
// There are different functions available to use depending on program needs.
// The versions with b64 in the function name involve base 64 conversion,
// suitable for protocols requiring a string representation.
// Otherwise the default will use raw bytes.
// Save the encoder state.
let esaved = encoder.saveState()
if esaved == nil {
print("Encoder state save error.")
return Int32(mte_status_unsupported.rawValue)
}
# Save and restore Encoder state with bytes.
# Get byte[] of Encoder state.
encoder_byte_state = flen_encoder.save_state()
# Restore Encoder with byte[] state.
encoder_status = flen_encoder.restore_state(encoder_byte_state)
if encoder_status != MteStatus.mte_status_success:
# Mte cannot continue, handle restore failure appropriately
# Below is only an example
raise Exception("Failed to restore Encoder state. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
# Save and restore Encoder state with strin.g
# Get string of Encoder state.
encoder_str_state = flen_encoder.save_state_b64()
# Restore Encoder with string state.
encoder_status = flen_encoder.restore_state_b64(encoder_str_state)
if encoder_status != MteStatus.mte_status_success:
# Mte cannot continue, handle restore failure appropriately
# Below is only an example
raise Exception("Failed to restore Encoder state. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
// Save and restore FLEN Encoder state with bytes
// Get byte[] of Encoder state
encoderByteState := flenEncoder.SaveState()
encoderStatus := flenEncoder.RestoreState(encoderByteState);
if(encoderStatus != mte.Status_mte_status_success){
// Handle Encoder restore state failure appropriately
// Below is only an example
fmt.Fprintf(os.Stderr, "Restore Encoder state error (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
// Save and restore FLEN Encoder state with bytes
// Get byte[] of Encoder state
encoderStrState := flenEncoder.SaveStateB64()
encoderStatus := flenEncoder.RestoreStateB64(encoderStrState);
if(encoderStatus != mte.Status_mte_status_success){
// Handle Encoder restore state failure appropriately
// Below is only an example
fmt.Fprintf(os.Stderr, "Restore Encoder state error (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
<?php
$encoderStrState = $flenEncoder->saveState();
$restoreStatus = $flenEncoder->restoreState($encoderStrState);
if (constant($restoreStatus)!=mte_status_success){
// Handle an error here -- below is a sample
echo "FLEN Encoder restore state error: "
.$flenEncoder->getStatusName(constant($restoreStatus)).":"
.$flenEncoder->getStatusDescription(constant($restoreStatus));
return $flenEncoder->getStatusCode(constant($restoreStatus));
}
?>
<?php
$encoderB64State = $flenEncoder->saveStateB64();
$restoreStatus = $flenEncoder->restoreStateB64($encoderB64State);
if (constant($restoreStatus)!=mte_status_success){
// Handle an error here -- below is a sample
echo "FLEN Encoder restore base64 state error: "
.$flenEncoder->getStatusName(constant($restoreStatus)).":"
.$flenEncoder->getStatusDescription(constant($restoreStatus));
return $flenEncoder->getStatusCode(constant($restoreStatus));
}
?>
Uninstantiate Encoder
Uninstantiate encoder, this will zeroize the DRBG state and returns the status.
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
status = mte_flen_enc_uninstantiate(encoder);
if (status != mte_status_success)
{
fprintf(stderr, "Failed to uninstantiate encoder (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
status = encoder.uninstantiate();
if (status != mte_status_success)
{
std::cerr << "Encoder uninstantiate error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Uninstantiate the Encoder
MteStatus encoderStatus = flenEncoder.Uninstantiate();
if(encoderStatus != MteStatus.mte_status_success)
{
// MTE was not uninstantiated as desired so handle failure appropriately
// Below is only an example
throw new Exception("Failed to uninstantiate Encoder. Status: "
+ flenEncoder.GetStatusName(encoderStatus)+ " / "
+ flenEncoder.GetStatusDescription(encoderStatus));
}
// Uninstantiate the Encoder
MteStatus encoderStatus = flenEncoder.uninstantiate();
if(encoderStatus != MteStatus.mte_status_success)
{
// MTE was not uninstantiated as desired so handle failure appropriately
// Below is only an example
throw new Exception("Failed to uninstantiate Encoder. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
// Uninstantiate the Encoder
const encoderStatus = flenEncoder.uninstantiate();
if (encoderStatus !== MteStatus.mte_status_success) {
throw new Error(
`Failed to uninstantiate Encoder.` +
`Status: ${MteBase.getStatusName(encoderStatus)} / ` +
`${MteBase.getStatusDescription(encoderStatus)}`,
);
}
// free WASM memory
flenEncoder.destroy();
// Uninstantiate the Encoder
let status: mte_status = encoder.uninstantiate()
if status != mte_status_success {
// MTE was not uninstantiated as desired so handle failure appropriately
print("Encoder Uninstantiate error: \(MteBase.getStatusName(status))." +
"Description: \(MteBase.getStatusDescription(status))"
}
# Uninstantiate the Encoder.
encoder_status = flen_encoder.uninstantiate()
if encoder_status != MteStatus.mte_status_success:
# MTE was not uninstantiated as desired so handle failure appropriately
# Below is only an example
raise Exception("Failed to uninstantiate Encoder. Status: {0} / {1}\n".format(MteBase.get_status_name(encoder_status),
MteBase.get_status_description(encoder_status)))
// Uninstantiate the FLEN Encoder
encoderStatus := flenEncoder.Uninstantiate();
if(encoderStatus != mte.Status_mte_status_success){
// Handle Encoder uninstantiate failure appropriately
// Below is only an example
fmt.Fprintf(os.Stderr, "Encoder uninstantiate error (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
return int(encoderStatus)
}
<?php
// Uninstantiate the Encoder
$encoderStatus = $flenEncoder->uninstantiate();
if (constant($encoderStatus) != mte_status_success) {
//----------------------------------------------------
// Handle Encoder uninstantiate failure appropriately
// Below is only an example
echo "FLEN Encoder uninstantiate error: ".$flenEncoder->getStatusName(constant($encoderStatus)).":"
.$flenEncoder->getStatusDescription(constant($encoderStatus));
return $flenEncoder->getStatusCode(constant($encoderStatus));
}
// Clear out $flenEncoder variable
unset($flenEncoder);
?>