decoder-create
- C
- C++
- CSharp
- Java
- JavaScript
- Swift
- Python
- Go
- PHP
/* Create the decoder. */
MTE_HANDLE decoder;
mte_mke_dec_init_info d_info = MTE_MKE_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_mke_dec_state_bytes(&d_info));
status = mte_mke_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_mke_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.
MteMkeDec 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 MKE Decoder with defaults
MteMkeDec mkeDecoder = new MteMkeDec();
// 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 = mkeDecoder.GetDrbgsEntropyMinBytes(mkeDecoder.GetDrbg());
string entropy = (entropyMinBytes > 0)
? new String('0', entropyMinBytes)
: string.Empty;
// Set Decoder entropy and nonce
mkeDecoder.SetEntropy(Encoding.UTF8.GetBytes(entropyString));
mkeDecoder.SetNonce(nonce);
// Initialize MTE Decoder
MteStatus decoderStatus = mkeDecoder.Instantiate(personalizationString);
if(decoderStatus !=MteStatus.mte_status_success)
{
// MTE cannot continue so handle failure appropriately
// Below is an Example
throw new ApplicationException($"Failed to initialize the MTE Decoder engine." +
$"Status: {mkeDecoder.GetStatusName(decoderStatus)} / " +
$"{mkeDecoder.GetStatusDescription(decoderStatus)}");
}
// Create the MTE MKE Decoder
MteMkeDec mkeDecoder = new MteMkeDec();
// 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(mkeDecoder.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
mkeDecoder.setEntropy(entropy.getBytes());
mkeDecoder.setNonce(nonce);
// Initialize MTE Decoder
MteStatus decoderStatus = mkeDecoder.instantiate(personalizationString.getBytes());
if (decoderStatus != MteStatus.mte_status_success)
{
// MTE cannot continue so handle failure appropriately
// Below is an Example
throw new Exception("Failed to initialize the MTE Decoder engine. Status: "
+ MteBase.getStatusName(decoderStatus)+ " / "
+ MteBase.getStatusDescription(decoderStatus));
}
// Create MTE MKE Decoder with defaults
const mkeDecoder = MteMkeDec.fromdefault(mteWasm);
// 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 = mkeDecoder.getDrbgsEntropyMinBytes(
mkeDecoder.getDrbg(),
);
const decoderEntropy =
entropyMinBytes > 0 ? "0".repeat(entropyMinBytes) : decoderEntropy;
// Set Decoder entropy and nonce
mkeDecoder.setEntropyStr(entropy);
mkeDecoder.setNonce(nonce);
// Instantiate MTE MKE Decoder
const decoderStatus = mkeDecoder.instantiate(personalizationString);
if (decoderStatus !== MteStatus.mte_status_success) {
// MTE cannot continue so handle failure appropriately
// Below is an Example
const status = mteBase.getStatusName(decoderStatus);
const message = mteBase.getStatusDescription(decoderStatus);
throw new Error(`Error instantiating MKE Decoder.\n${status}: ${message}`);
}
// Create the decoder.
let decoder = try! MteMkeDec()
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 MKE Decoder with defaults.
mke_decoder = MteMkeDec.fromdefault()
## 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 = mke_decoder.get_drbgs_entropy_min_bytes(mke_decoder.get_drbg())
entropy = bytes("0" * entropy_min_bytes, 'utf-8')
# Set Decoder entropy and nonce.
mke_decoder.set_entropy(entropy)
mke_decoder.set_nonce(nonce)
# Initialize MTE Decoder.
decoder_status = mke_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 MKE Decoder with default options
mkeDecoder := mte.NewMkeDecDef()
defer mkeDecoder.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.
// 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(mkeDecoder.GetDrbg())
entropy := make([]byte, entropyBytes)
// Set entropy and nonce
mkeDecoder.SetEntropy(entropy)
mkeDecoder.SetNonceInt(nonce)
// Instantiate the Decoder.
decoderStatus := mkeDecoder.InstantiateStr(personalizationString)
if status != mte.Status_mte_status_success {
// Handle an error here -- below is a sample
fmt.Fprintf(os.Stderr, "MKE Decoder instantiate error (%v): %v\n",
mte.GetStatusName(decoderStatus), mte.GetStatusDescription(decoderStatus))
return int(decoderStatus)
}
<?php
// Create MTE MKE Decoder with defaults
$mkeDecoder = new mteMkeDec();
// 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 = $mkeDecoder->getDrbgEntropyMinBytes(constant($mkeDecoder->getDrbg()));
$entropy = "";
$entropy = str_pad($entropy, $entropyBytes);
// Set entropy and nonce
$mkeDecoder->setEntropy($entropy);
$mkeDecoder->setNonce($nonce);
// Instantiate the Decoder.
$decoded = $mkeDecoder->instantiate($personalizationString);
if (constant($decoded["status"])==mte_status_success) {
// Handle an error here -- below is a sample
echo "Decoder instantiate error: "
.$mkeDecoder->getStatusName(constant($decoded["status"])).":"
.$mkeDecoder->getStatusDescription(constant($decoded["status"]));
return $mkeDecoder->getStatusCode(constant($decoded["status"]));
}
?>