encoder-create
- 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"]));
}
?>