decoder-create
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
/* Create the decoder. */
MTE_HANDLE decoder;
mte_dec_init_info d_info = MTE_DEC_INIT_INFO_INIT(
MTE_DRBG_ENUM, MTE_TOKBYTES, MTE_VERIFIERS_ENUM,
MTE_CIPHER_ENUM, MTE_HASH_ENUM, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL);
mte_dec_args d_args = MTE_DEC_ARGS_INIT(NULL, 0, NULL, &t_cb, NULL);
decoder = MTE_ALLOCA(mte_dec_state_bytes(&d_info));
status = mte_dec_state_init(decoder, &d_info);
if (status != mte_status_success)
{
fprintf(stderr, "Decoder init error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
status = mte_dec_instantiate(decoder, &i_info);
if (status != mte_status_success)
{
fprintf(stderr, "Decoder 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 decoder.
MteDec decoder;
decoder.setEntropyCallback(&cbs);
decoder.setNonceCallback(&cbs);
decoder.setTimestampCallback(&cbs);
status = decoder.instantiate(personal);
if (status != mte_status_success)
{
std::cerr << "Decoder 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);
}
// Create MTE Core Decoder with defaults
MteDec mteDecoder = new MteDec();
// Need entropy, nonce and personalization string
// These values should be unique and entropy must be treated like encryption keys!
// 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;
// *** 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.
// 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 = mteDecoder.GetDrbgsEntropyMinBytes(mteDecoder.GetDrbg());
string entropy = (entropyMinBytes > 0)
? new String('0', entropyMinBytes)
: string.Empty;
// Set Decoder entropy and nonce
mteDecoder.SetEntropy(Encoding.UTF8.GetBytes(entropy));
mteDecoder.SetNonce(nonce);
// Initialize MTE Decoder
MteStatus decoderStatus = mteDecoder.Instantiate(personalizationString);
if(decoderStatus != MteStatus.mte_status_success)
{
// MTE cannot continue so handle failure appropriately
// Below is just an example
throw new ApplicationException($"Failed to initialize the MTE Decoder engine." +
$"Status: {mteDecoder.GetStatusName(decoderStatus)} / " +
$"{mteDecoder.GetStatusDescription(decoderStatus)}");
}
// Create the MTE Decoder
MteDec mteDecoder = new MteDec();
// Need entropy, nonce and personalization string
// These values should be unique and entropy must be treated like encryption keys!
// 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;
// *** 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.
// 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(mte_decoder.getDrbg());
String entropy = "0";
entropy = entropy.repeat(entropyMinBytes);
mte_decoder.set_entropy(entropy)
mte_decoder.set_nonce(nonce)
# Initialize MTE Decoder.
decoder_status = mte_decoder.instantiate(personalization_string)
if decoder_status != MteStatus.mte_status_success:
# MTE cannot continue so handle failure appropriately.
# Below is an Example.
raise Exception("Failed to initialize the MTE Decoder engine. Status: {0} / {1}\n".format(MteBase.get_status_name(decoder_status),
MteBase.get_status_description(decoder_status)))
import { MteDec } from "mte-wasm-browser";
// Note: mteWasm must already be declared and instantiated
// create Decoder from default
const mteDecoder = MteDec.fromdefault(mteWasm);
// set Decoder entropy
// see Best Practice guides for generating secure entropy values
mteDecoder.setEntropyStr("SecretEntropyStringHere");
// set Decoder nonce
mteDecoder.setNonce(12345678);
// instantiate using personalization token
const decoderStatus = mteDecoder.instantiate("SecretPersonalizationStringHere");
// check instantiation was successful
if (decoderStatus !== MteStatus.mte_status_success) {
const status = mteBase.getStatusName(decoderStatus);
const message = mteBase.getStatusDescription(decoderStatus);
throw new Error(`Error instantiating MTE Decoder.\n${status}: ${message}`);
}
// Create the decoder.
let decoder = try! MteDec()
decoder.setEntropyCallback(cbs)
decoder.setNonceCallback(cbs)
decoder.setTimestampCallback(cbs)
status = decoder.instantiate(personal)
if status != mte_status_success {
print("decoder 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
}
}
# Create MTE Core Decoder with defaults.
mte_decoder = MteDec.fromdefault()
# Need entropy, nonce and personalization string.
# These values should be unique and entropy must be treated like encryption keys!
# 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
# *** 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.
# 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(mte_decoder.get_drbg())
entropy = bytes(entropy_min_bytes)
# Set Decoder entropy and nonce.
mte_decoder.set_entropy(entropy)
mte_decoder.set_nonce(nonce)
# Initialize MTE Decoder.
decoder_status = mte_decoder.instantiate(personalization_string)
if decoder_status != MteStatus.mte_status_success:
# MTE cannot continue so handle failure appropriately.
# Below is an Example.
raise Exception("Failed to initialize the MTE Decoder engine. Status: {0} / {1}\n".format(MteBase.get_status_name(decoder_status),
MteBase.get_status_description(decoder_status)))
// Create Decoder with default options
mteDecoder := mte.NewDecDef()
defer mteDecoder.Destroy()
// Need entropy, nonce and personalization string
// These values should be unique and entropy must be treated like encryption keys!
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
personalizationString := "MySecretPersonalizationStringGoesHere";
nonce := 12345678;
// *** 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.
entropy_min_bytes = mte_decoder.get_drbgs_entropy_min_bytes(mte_decoder.get_drbg())
entropy = bytes("0" * entropy_min_bytes, 'utf-8')
// 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(mteDecoder.GetDrbg())
entropy := make([]byte, entropyBytes)
// Set entropy and nonce
mteDecoder.SetEntropy(entropy)
mteDecoder.SetNonceInt(nonce)
// Instantiate the Decoder.
decoderStatus := mteDecoder.InstantiateStr(personalizationString)
if status != mte.Status_mte_status_success {
// Handle an error here -- below is a sample
fmt.Fprintf(os.Stderr, "Decoder instantiate error (%v): %v\n",
mte.GetStatusName(decoderStatus), mte.GetStatusDescription(decoderStatus))
return int(decoderStatus)
}
<?php
// Create Decoder with default options
// In practice, you will create a decoder this way, create a custom decoder,
// or create MKE or FLEN decoder. See developer guide for more information
$mteDecoder = new mteDec();
// Need entropy, nonce and personalization string.
// These values should be unique and treated like encryption keys!
// The following personalization string and nonce values are for demonstration purposes
// and should NOT be used in production environments
$personalizationString = "MySecretPersonalizationStringGoesHere";
$nonce = 12345678;
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
$entropyBytes = $mteDecoder->getDrbgEntropyMinBytes(constant($mteDecoder->getDrbg()));
$entropy = "";
$entropy = str_pad($entropy, $entropyBytes);
// Set entropy and nonce
$mteDecoder->setEntropy($entropy);
$mteDecoder->setNonce($nonce);
// Instantiate the Decoder.
$decoded = $mteDecoder->instantiate($personalizationString);
if (constant($decoded["status"])==mte_status_success) {
// Handle an error here -- below is a sample
echo "Decoder instantiate error: ".$mteDecoder->getStatusName(constant($decoded["status"])).":"
.$mteDecoder->getStatusDescription(constant($decoded["status"]));
return $mteDecoder->getStatusCode(constant($decoded["status"]));
}
?>