MTE Core Code Samples
Purpose
Samples expand on our "Examples" by providing longer snippets of code demonstrating entire processes. The objective of an MTE Core "Samples" is to provide examples of how to use the MTE Core Encoder and MTE Core Decoder within a single working application.
In this example an input message is being encoded and decoded within a single program but in actual implementations the encoder and decoder would be on separate endpoints. By having both the Encoder and Decoder within one application it allows for the simplest working demonstration for interacting with the MTE. For more information, please see the official MTE developer guides.
Simple MTE Core Console Demo
- C
- C++
- CSharp
- Java
- Swift
- ObjC
- Python
- Go
- PHP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Callbacks. */
static mte_status ei_cb(void *, mte_drbg_ei_info *info);
static void n_cb(void *, mte_drbg_nonce_info *info);
static MTE_UINT64_T t_cb(void *context);
int main(int argc, char **argv)
{
int exitCode;
/* Status. */
mte_status status;
/* Input data. */
static const char input[] = "hello";
/* Personalization string. */
static const char personal[] = "demo";
/* Options. */
mte_enc_init_info e_info = MTE_ENC_INIT_INFO_INIT(
MTE_DRBG_ENUM, MTE_TOKBYTES, MTE_VERIFIERS_ENUM, NULL, NULL);
mte_dec_init_info d_info = MTE_DEC_INIT_INFO_INIT(
MTE_DRBG_ENUM, MTE_TOKBYTES, MTE_VERIFIERS_ENUM, 1, 0, NULL, NULL);
mte_drbg_inst_info i_info =
{ &ei_cb, NULL, &n_cb, NULL, personal, sizeof(personal) - 1 };
/* Encoder. */
char *encoded;
MTE_HANDLE encoder = MTE_ALLOCA(mte_enc_state_bytes(&e_info));
mte_enc_args e_args = MTE_ENC_ARGS_INIT(NULL, 0, NULL, &t_cb, NULL);
/* Decoder. */
char *decoded;
MTE_HANDLE decoder = MTE_ALLOCA(mte_dec_state_bytes(&d_info));
mte_dec_args d_args = MTE_DEC_ARGS_INIT(NULL, 0, NULL, &t_cb, NULL);
/* 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;
}
}
/* Output original data. */
printf("Original data: %s\n", input);
/* Create the encoder. */
status = mte_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_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;
}
/* Allocate the buffer for encoding. */
encoded = MTE_ALLOCA(mte_enc_buff_bytes_b64(encoder, sizeof(input) - 1));
/* Encode the message. */
MTE_SET_ENC_IO(e_args, input, sizeof(input) - 1, encoded);
status = mte_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;
}
/* Display the encoded message. */
printf("Base64 message: %s\n", (const char *)e_args.encoded);
/* Create the decoder. */
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;
}
/* Allocate the buffer for decoding. */
decoded = MTE_ALLOCA(mte_dec_buff_bytes_b64(decoder, e_args.bytes));
/* Decode the message. */
MTE_SET_DEC_IO(d_args, e_args.encoded, e_args.bytes, decoded);
status = mte_dec_decode_b64(decoder, &d_args);
if (mte_base_status_is_error(status))
{
fprintf(stderr, "Decode error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
else if (status != mte_status_success)
{
fprintf(stderr, "Decode warning (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
}
/* Output the decoded data. */
printf("Decoded data: %s\n", (const char *)d_args.decoded);
/* Compare the decoded data against the original data. */
if (memcmp(d_args.decoded, input, sizeof(input) - 1) == 0)
{
exitCode = 0;
puts("The original data and decoded data match.");
}
else
{
exitCode = -1;
puts("The original data and decoded data DO NOT match.");
}
/* Success. */
mte_enc_uninstantiate(encoder);
mte_dec_uninstantiate(decoder);
return exitCode;
}
#include "MteEnc.h"
#include "MteDec.h"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
// Callbacks that will get entropy, nonce, and timestamp from stdin.
// THIS IS NOT A SECURE WAY TO CAPTURE THESE ITEMS AND IS ONLY FOR
// DEMONSTRATION PURPOSES.
class Cbs : public MteBase::EntropyCallback,
public MteBase::NonceCallback,
public MteBase::TimestampCallback
{
public:
Cbs();
virtual ~Cbs();
private:
virtual mte_status entropyCallback(mte_drbg_ei_info& info);
virtual void nonceCallback(mte_drbg_nonce_info& info);
virtual MTE_UINT64_T timestampCallback();
uint8_t *myEntropy;
};
// The timestamp window and sequencing window are hard coded for this demo. */
static const uint64_t timestampWindow = 1;
static const int32_t sequenceWindow = 0;
int main(int /*argc*/, char ** /*argv*/)
{
size_t i;
std::string line;
std::string input;
std::string personal;
// Status.
mte_status status;
// Options.
mte_drbgs drbg = MteBase::getDefaultDrbg();
size_t tokBytes = MteBase::getDefaultTokBytes();
mte_verifiers verifiers = MteBase::getDefaultVerifiers();
// 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 (!MteBase::initLicense("YOUR_COMPANY", "YOUR_LICENSE"))
{
const char *company = getenv("MTE_COMPANY");
const char *license = getenv("MTE_LICENSE");
if (company == NULL || license == NULL ||
!MteBase::initLicense(company, license))
{
std::cerr << "License init error ("
<< MteBase::getStatusName(mte_status_license_error)
<< "): "
<< MteBase::getStatusDescription(mte_status_license_error)
<< std::endl;
return mte_status_license_error;
}
}
// Get the input data.
std::cout << "Enter the data to encode> " << std::flush;
std::cin >> input;
// Get the personalization string.
std::cout << "Enter the personalization> " << std::flush;
std::cin >> personal;
// Prompt for the options if available.
if (MteBase::hasRuntimeOpts())
{
// Get the DRBG.
std::cout << "DRBGs:";
for (i = 1; i < MteBase::getDrbgsCount(); ++i)
{
std::cout << ' ' << MteBase::getDrbgsName(static_cast<mte_drbgs>(i));
}
std::cout << "\nEnter the DRBG> " << std::flush;
std::cin >> line;
drbg = MteBase::getDrbgsAlgo(line.c_str());
// Get the token size.
std::cout << "Enter the token size in bytes> " << std::flush;
std::cin >> tokBytes;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Get the verifiers.
std::cout << "Verifiers:";
for (i = 0; i < MteBase::getVerifiersCount(); ++i)
{
std::cout << ' '
<< MteBase::getVerifiersName(static_cast<mte_verifiers>(i));
}
std::cout << "\nEnter the verifiers> " << std::flush;
std::cin >> line;
verifiers = MteBase::getVerifiersAlgo(line.c_str());
}
// Create the callbacks to get entropy, nonce, and timestamp from stdin.
Cbs cbs;
// Create the encoder.
MteEnc encoder(drbg, tokBytes, verifiers);
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;
}
// Save the encoder state.
const char *saved = encoder.saveStateB64();
if (saved == NULL)
{
std::cerr << "Encoder state save error." << std::endl;
return mte_status_unsupported;
}
std::string esaved = saved;
// Encode the input.
const char *encoded = encoder.encodeB64(input, status);
if (status != mte_status_success)
{
std::cerr << "Encode error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Display the encoded message.
std::cout << "Base64 message: " << encoded << std::endl;
// Create the decoder.
MteDec decoder(drbg,
tokBytes,
verifiers,
timestampWindow,
sequenceWindow);
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;
}
// Save the decoder state.
saved = decoder.saveStateB64();
if (saved == NULL)
{
std::cerr << "Decoder state save error." << std::endl;
return mte_status_unsupported;
}
std::string dsaved = saved;
// Decode the message.
std::string decoded;
status = decoder.decodeB64(encoded, decoded);
if (MteBase::statusIsError(status))
{
std::cerr << "Decode error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
else if (status != mte_status_success)
{
std::cerr << "Decode warning ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
}
// Output the decoded data.
std::cout << "Decoded data: " << decoded << std::endl;
// Output decode info.
std::cout << "Encode timestamp: " << decoder.getEncTs() << std::endl;
std::cout << "Decode timestamp: " << decoder.getDecTs() << std::endl;
std::cout << "Messages skipped: " << decoder.getMsgSkipped() << std::endl;
// Compare the decoded data against the original data.
if (decoded == input)
{
std::cout << "The original data and decoded data match." << std::endl;
}
else
{
std::cout << "The original data and decoded data DO NOT match."
<< std::endl;
return -1;
}
// Restore the encoder and decoder state.
status = encoder.restoreStateB64(esaved.c_str());
if (status != mte_status_success)
{
std::cerr << "Encoder state restore error("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return mte_status_unsupported;
}
status = decoder.restoreStateB64(dsaved.c_str());
if (status != mte_status_success)
{
std::cerr << "Decoder state restore error("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return mte_status_unsupported;
}
// Encode the input.
encoded = encoder.encodeB64(input, status);
if (status != mte_status_success)
{
std::cerr << "Encode error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Display the encoded message.
std::cout << "Base64 message: " << encoded << std::endl;
// Decode the message.
status = decoder.decodeB64(encoded, decoded);
if (MteBase::statusIsError(status))
{
std::cerr << "Decode error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
else if (status != mte_status_success)
{
std::cerr << "Decode warning ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
}
// Output the decoded data.
std::cout << "Decoded data: " << decoded << std::endl;
// Output decode info.
std::cout << "Encode timestamp: " << decoder.getEncTs() << std::endl;
std::cout << "Decode timestamp: " << decoder.getDecTs() << std::endl;
std::cout << "Messages skipped: " << decoder.getMsgSkipped() << std::endl;
// Compare the decoded data against the original data.
if (decoded == input)
{
std::cout << "The original data and decoded data match." << std::endl;
}
else
{
std::cout << "The original data and decoded data DO NOT match."
<< std::endl;
return -1;
}
// Success.
return 0;
}
using System;
namespace MTE {
class demoCsMin {
static int Main() {
// Status.
MteStatus status;
// Input.
string input = "hello";
// Personalization string.
string personal = "demo";
// 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.
MteBase baseObj = new MteBase();
if (!baseObj.InitLicense("YOUR_COMPANY", "YOUR_LICENSE")) {
string company = Environment.GetEnvironmentVariable("MTE_COMPANY");
string license = Environment.GetEnvironmentVariable("MTE_LICENSE");
if (company == null || license == null ||
!baseObj.InitLicense(company, license)) {
status = MteStatus.mte_status_license_error;
Console.Error.WriteLine("License init error ({0}): {1}",
baseObj.GetStatusName(status),
baseObj.GetStatusDescription(status));
return (int)status;
}
}
// Output original data.
Console.WriteLine("Original data: {0}", input);
// Create the Encoder and Decoder.
MteEnc encoder = new MteEnc();
MteDec decoder = new MteDec();
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
int entropyBytes = encoder.GetDrbgsEntropyMinBytes(encoder.GetDrbg());
byte[] entropy = new byte[entropyBytes];
// Instantiate the Encoder.
encoder.SetEntropy(entropy);
encoder.SetNonce(0);
status = encoder.Instantiate(personal);
if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Encoder instantiate error ({0}): {1}",
encoder.GetStatusName(status),
encoder.GetStatusDescription(status));
return (int)status;
}
// Encode the input.
string encoded = encoder.EncodeB64(input, out status);
if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Encode error ({0}): {1}",
encoder.GetStatusName(status),
encoder.GetStatusDescription(status));
return (int)status;
}
// Display the message.
Console.WriteLine("Base64 message: {0}", encoded);
// Instantiate the Decoder.
decoder.SetEntropy(entropy);
decoder.SetNonce(0);
status = decoder.Instantiate(personal);
if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Decoder instantiate error ({0}): {1}",
decoder.GetStatusName(status),
decoder.GetStatusDescription(status));
return (int)status;
}
// Decode the message.
string decoded = decoder.DecodeStrB64(encoded, out status);
if (decoder.StatusIsError(status)) {
Console.Error.WriteLine("Decode error ({0}): {1}",
decoder.GetStatusName(status),
decoder.GetStatusDescription(status));
return (int)status;
} else if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Decode warning ({0}): {1}",
decoder.GetStatusName(status),
decoder.GetStatusDescription(status));
}
// Output the decoded data.
Console.WriteLine("Decoded data: {0}", decoded);
// Compare the decoded data against the original data.
if (decoded == input) {
Console.WriteLine("The original data and decoded data match.");
} else {
Console.WriteLine("The original data and decoded data DO NOT match.");
return -1;
}
// Success.
return 0;
}
}
}
import com.eclypses.mte.*;
public class demoJavaMin
{
public static void main(String[] args)
{
// Status.
MteStatus status;
// Input.
String input = "hello";
// Personalization string.
String personal = "demo";
// 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 (!MteBase.initLicense("YOUR_COMPANY", "YOUR_LICENSE"))
{
String company = System.getenv("MTE_COMPANY");
String license = System.getenv("MTE_LICENSE");
if (company == null || license == null ||
!MteBase.initLicense(company, license))
{
status = MteStatus.mte_status_license_error;
System.err.println("Encode error (" +
MteBase.getStatusName(status) + "): " +
MteBase.getStatusDescription(status));
System.exit(status.getValue());
}
}
// Output original data.
System.out.println("Original data: " + input);
// Create the Encoder and Decoder.
MteEnc encoder = new MteEnc();
MteDec decoder = new MteDec();
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
int entropyBytes = MteBase.getDrbgsEntropyMinBytes(encoder.getDrbg());
byte[] entropy = new byte[entropyBytes];
// Instantiate the Encoder.
encoder.setEntropy(entropy);
encoder.setNonce(0);
status = encoder.instantiate(personal);
if (status != MteStatus.mte_status_success)
{
System.err.println("Encoder instantiate error (" +
MteBase.getStatusName(status) + "): " +
MteBase.getStatusDescription(status));
System.exit(status.getValue());
}
// Encode the input.
MteBase.StrStatus encoded = encoder.encodeB64(input);
if (encoded.status != MteStatus.mte_status_success)
{
System.err.println("Encode error (" +
MteBase.getStatusName(encoded.status) + "): " +
MteBase.getStatusDescription(encoded.status));
System.exit(encoded.status.getValue());
}
// Display the message.
System.out.println("Base64 message: " + encoded.str);
// Instantiate the Decoder.
decoder.setEntropy(entropy);
decoder.setNonce(0);
status = decoder.instantiate(personal);
if (status != MteStatus.mte_status_success)
{
System.err.println("Decoder instantiate error (" +
MteBase.getStatusName(status) + "): " +
MteBase.getStatusDescription(status));
System.exit(status.getValue());
}
// Decode the message.
MteBase.StrStatus decoded = decoder.decodeStrB64(encoded.str);
if (MteBase.statusIsError(decoded.status))
{
System.err.println("Decode error (" +
MteBase.getStatusName(decoded.status) + "): " +
MteBase.getStatusDescription(decoded.status));
System.exit(decoded.status.getValue());
}
else if (decoded.status != MteStatus.mte_status_success)
{
System.err.println("Decode warning (" +
MteBase.getStatusName(decoded.status) + "): " +
MteBase.getStatusDescription(decoded.status));
}
// Output the decoded data.
System.out.println("Decoded data: " + decoded.str);
// Compare the decoded data against the original data.
if (decoded.str.equals(input))
{
System.out.println("The original data and decoded data match.");
}
else
{
System.out.println("The original data and decoded data DO NOT match.");
System.exit(-1);
}
// Success.
System.exit(0);
}
}
public func main() -> Int32 {
// Status.
var status: mte_status
// Options.
var drbg = MteBase.getDefaultDrbg()
var tokBytes = MteBase.getDefaultTokBytes()
var verifiers = MteBase.getDefaultVerifiers()
// 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 !MteBase.initLicense("YOUR_COMPANY", "YOUR_LICENSE") {
let company = ProcessInfo.processInfo.environment["MTE_COMPANY"]
let license = ProcessInfo.processInfo.environment["MTE_LICENSE"];
if company == nil || license == nil ||
!MteBase.initLicense(company!, license!) {
status = mte_status_license_error
print("License init error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
}
// Get the input data.
print("Enter the data to encode> ", terminator: "")
let input = readLine()!
// Get the personalization string.
print("Enter the personalization> ", terminator: "")
let personal = readLine()!
// Prompt for the options if available.
if MteBase.hasRuntimeOpts() {
// Get the DRBG.
print("DRBGs:", terminator: "")
for i in 1..<MteBase.getDrbgsCount() {
print(" \(MteBase.getDrbgsName(mte_drbgs(rawValue: UInt32(i))))",
terminator: "")
}
print("\nEnter the DRBG> ", terminator: "")
drbg = MteBase.getDrbgsAlgo(readLine()!)
// Get the token size.
print("Enter the token size in bytes> ", terminator: "")
tokBytes = Int(readLine()!)!
// Get the verifiers.
print("Verifiers:", terminator: "")
for i in 0..<MteBase.getVerifiersCount() {
print(" \(MteBase.getVerifiersName(mte_verifiers(rawValue: UInt32(i))))",
terminator: "")
}
print("\nEnter the verifiers> ", terminator: "")
verifiers = MteBase.getVerifiersAlgo(readLine()!)
}
// Create the callbacks to get entropy, nonce, and timestamp from stdin.
let cbs = Cbs()
// Create the encoder.
let encoder = try! MteEnc(drbg, tokBytes, verifiers)
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)
}
// Save the encoder state.
let esaved = encoder.saveStateB64()
if esaved == nil {
print("Encoder state save error.")
return Int32(mte_status_unsupported.rawValue)
}
// Encode the input.
var encoded: String
(encoded, status) = encoder.encodeB64(input)
if status != mte_status_success {
print("Encode error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Display the encoded message.
print("Base64 message: \(encoded)")
// Create the decoder.
let decoder = try! MteDec(drbg,
tokBytes,
verifiers,
timestampWindow,
sequenceWindow)
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)
}
// Save the decoder state.
let dsaved = decoder.saveStateB64()
if dsaved == nil {
print("Decoder state save error.")
return Int32(mte_status_unsupported.rawValue)
}
// Decode the message.
var decoded: String
(decoded, status) = decoder.decodeStrB64(encoded)
if MteBase.statusIsError(status) {
print("Decode error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
} else if status != mte_status_success {
print("Decode warning (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
}
// Output the decoded data.
print("Decoded data: \(decoded)")
// Output decode info.
print("Encode timestamp: \(decoder.getEncTs())")
print("Decode timestamp: \(decoder.getDecTs())")
print("Messages skipped: \(decoder.getMsgSkipped())")
// Compare the decoded data against the original data.
if decoded == input {
print("The original data and decoded data match.")
}
else {
print("The original data and decoded data DO NOT match.")
return -1
}
// Restore the encoder and decoder state.
status = encoder.restoreStateB64(esaved!)
if status != mte_status_success {
print("Encoder state restore error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
status = decoder.restoreStateB64(dsaved!)
if status != mte_status_success {
print("Decoder state restore error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Encode the input.
(encoded, status) = encoder.encodeB64(input)
if status != mte_status_success {
print("Encode error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Display the encoded message.
print("Base64 message: \(encoded)")
// Decode the message.
(decoded, status) = decoder.decodeStrB64(encoded)
if MteBase.statusIsError(status) {
print("Decode error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
} else if status != mte_status_success {
print("Decode warning (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
}
// Output the decoded data.
print("Decoded data: \(decoded)")
// Output decode info.
print("Encode timestamp: \(decoder.getEncTs())")
print("Decode timestamp: \(decoder.getDecTs())")
print("Messages skipped: \(decoder.getMsgSkipped())")
// Compare the decoded data against the original data.
if decoded == input {
print("The original data and decoded data match.")
}
else {
print("The original data and decoded data DO NOT match.")
return -1
}
// Success.
return 0
}
#import "MteEnc.h"
#import "MteDec.h"
int main() {
uint64 min = 999999999999;
uint64 max = UINT_MAX;
uint8_t *encoderEntropy[32];
uint64 encoderNonce = 0;
NSString *encoderPersonalityString = @"";
uint8_t *decoderEntropy[32];
uint64 decoderNonce = 0;
NSString *decoderPersonalityString = @"";
// Status.
mte_status status;
NSString *valueToEncode = @"hello";
@autoreleasepool {
puts("****** Simple Objective-C MTE Core Console Demo ******\n\n");
// Check License
if (![MteBase initLicense:@"YOUR_COMPANY" code:@"YOUR_LICENSE"])
{
status = mte_status_license_error;
fprintf(stderr, "License init error (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
// Fill the entropy variables
if (SecRandomCopyBytes(kSecRandomDefault, 32, encoderEntropy) != 0) {
printf("%s", "Unable to generate Entropy");
}
memcpy(decoderEntropy, encoderEntropy, sizeof(encoderEntropy));
// Fill the nonce variables
encoderNonce = min + arc4random_uniform((uint32_t)(max - min + 1));
decoderNonce = encoderNonce;
// Fill the PersonalizationString variables
encoderPersonalityString = [[NSUUID UUID] UUIDString];
decoderPersonalityString = encoderPersonalityString;
// Create default Encoder
MteEnc *encoder = MTE_AUTORELEASE([[MteEnc alloc] init]);
[encoder setEntropy:encoderEntropy bytes:32];
[encoder setNonce:encoderNonce];
status = [encoder instantiate:encoderPersonalityString];
if (status != mte_status_success)
{
fprintf(stderr, "Encoder instantiate error (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
NSString *encoded = [encoder encodeB64:valueToEncode status:&status];
if (status != mte_status_success)
{
fprintf(stderr, "Encode error (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
// Create default Decoder
MteDec *decoder = MTE_AUTORELEASE([[MteDec alloc] init]);
[decoder setEntropy:decoderEntropy bytes:32];
[decoder setNonce:decoderNonce];
[decoder instantiate:decoderPersonalityString];
if (status != mte_status_success)
{
fprintf(stderr, "Decoder instantiate error (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
NSString *decoded = [decoder decodeB64:encoded status:&status];
if ([MteBase statusIsError:status])
{
fprintf(stderr, "Decode error (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
else if (status != mte_status_success)
{
fprintf(stderr, "Decode warning (%s): %s\n",
[[MteBase getStatusName:status] UTF8String],
[[MteBase getStatusDescription:status] UTF8String]);
return status;
}
// Compare the decoded data against the original data.
if ([decoded isEqualToString:valueToEncode])
{
puts("The original data and decoded data match.\n");
}
else
{
puts("The original data and decoded data DO NOT match.");
return -1;
}
}
return 0;
}
from MteDrbgs import MteDrbgs
from MteVerifiers import MteVerifiers
from MteStatus import MteStatus
from MteBase import MteBase
from MteEnc import MteEnc
from MteDec import MteDec
import os
import sys
# The timestamp window and sequencing window are hard coded for this demo.
timestamp_window = 1
sequence_window = 0
def main():
# Input.
input_ = "hello"
# Personalization string.
personal = "demo"
# 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 not MteBase.init_license("YOUR_COMPANY", "YOUR_LICENSE"):
company = os.getenv("MTE_COMPANY")
license = os.getenv("MTE_LICENSE")
if company is None or \
license is None or \
not MteBase.init_license(company, license):
print("License init error ({0}): {1}".format(
MteBase.get_status_name(MteStatus.mte_status_license_error),
MteBase.get_status_description(MteStatus.mte_status_license_error)),
file=sys.stderr)
return MteStatus.mte_status_license_error.value
# Output original data.
print("Original data: {0}".format(input_))
# Create the Encoder and Decoder.
encoder = MteEnc.fromdefault()
decoder = MteDec.fromdefault()
# Create all-zero entropy for this demo. The nonce will also be set to 0.
# This should never be done in real applications.
entropyBytes = MteBase.get_drbgs_entropy_min_bytes(encoder.get_drbg())
entropy = bytes(entropyBytes)
# Instantiate the Encoder.
encoder.set_entropy(entropy)
encoder.set_nonce(0)
status = encoder.instantiate(personal)
if status != MteStatus.mte_status_success:
print("Encoder instantiate error ({0}): {1}".format(
MteBase.get_status_name(status),
MteBase.get_status_description(status)),
file=sys.stderr)
return status.value
# Encode the input.
(encoded, status) = encoder.encode_b64(input_)
if status != MteStatus.mte_status_success:
print("Encode error ({0}): {1}".format(
MteBase.get_status_name(status),
MteBase.get_status_description(status)),
file=sys.stderr)
return status.value
# Display the message.
print(f"Base64 message: {encoded}")
# Instantiate the Decoder.
decoder.set_entropy(entropy)
decoder.set_nonce(0)
status = decoder.instantiate(personal)
if status != MteStatus.mte_status_success:
print("Decoder instantiate error ({0}): {1}".format(
MteBase.get_status_name(status),
MteBase.get_status_description(status)),
file=sys.stderr)
return status.value
# Decode the message.
(decoded, status) = decoder.decode_str_b64(encoded)
if MteBase.status_is_error(status):
print("Decode error ({0}): {1}".format(
MteBase.get_status_name(status),
MteBase.get_status_description(status)),
file=sys.stderr)
return status.value
elif status != MteStatus.mte_status_success:
print("Decode warning ({0}): {1}".format(
MteBase.get_status_name(status),
MteBase.get_status_description(status)),
file=sys.stderr)
# Output the decoded data.
print(f"Decoded data: {decoded}")
# Compare the decoded data against the original data.
if decoded == input_:
print("The original data and decoded data match.")
else:
print("The original data and decoded data DO NOT match.")
return -1
# Success.
return 0
package main
import (
"bufio"
"fmt"
"goDemo/mte"
"os"
"strings"
)
// Application constants
const (
nonce = 0
personalizationString = "demo"
companyName = ""
companyLicense = ""
)
func main() {
//-----------------------------------------------------
// defer the exit so all other defer calls are called
//-----------------------------------------------------
retcode := 0
defer func() { os.Exit(retcode) }()
//-----------------------------------------
// Display the version of MTE we are using
// (optional) For demo purposes ONLY
//-----------------------------------------
mteVersion := mte.GetVersion()
fmt.Printf("Using Mte Version %s\n", mteVersion)
//----------------------------
// Initialize the MTE license
//----------------------------
if !mte.InitLicense(companyName, companyLicense) {
fmt.Println("MTE license appears to be invalid. MTE cannot be initalized.")
retcode = int(mte.Status_mte_status_license_error)
return
}
//--------------------------
// create the MTE Encoder
//--------------------------
mteEncoder := mte.NewEncDef()
defer mteEncoder.Destroy()
//-------------------------------------------------------------------------
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
//-------------------------------------------------------------------------
entropyBytes := mte.GetDrbgsEntropyMinBytes(mteEncoder.GetDrbg())
entropy := make([]byte, entropyBytes)
// Fill with 0's
for i := 0; i < entropyBytes; i++ {
entropy[i] = '0'
}
//--------------------------
// Set entropy and nonce
//--------------------------
mteEncoder.SetEntropy(entropy)
mteEncoder.SetNonceInt(nonce)
//--------------------------
// Instantiate the Encoder.
//--------------------------
encoderStatus := mteEncoder.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))
retcode = int(encoderStatus)
return
}
//-------------------------
// create the MTE decoder
//-------------------------
mteDecoder := mte.NewDecDef()
defer mteDecoder.Destroy()
//----------------------------------------------------------------------------
// Since the entropy is zero'ized so fill again
// Providing Entropy in this fashion is insecure. This is for demonstration
// purposes only and should never be done in practice.
//----------------------------------------------------------------------------
for i := 0; i < entropyBytes; i++ {
entropy[i] = '0'
}
//---------------------
// Initialize decoder
//---------------------
mteDecoder.SetEntropy(entropy)
mteDecoder.SetNonceInt(nonce)
decoderStatus := mteDecoder.InstantiateStr(personalizationString)
if decoderStatus != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Decoder instantiate error (%v): %v\n",
mte.GetStatusName(decoderStatus), mte.GetStatusDescription(decoderStatus))
retcode = int(decoderStatus)
return
}
//-------------------------------
// run loop until quit typed in
//-------------------------------
for {
//-----------------------------
// Prompting message to encode
//-----------------------------
fmt.Print("\nPlease enter text to encode: (To end please type 'quit')\n")
reader := bufio.NewReader(os.Stdin)
textToEncode, _ := reader.ReadString('\n')
//---------------------------
// take off carriage return
//---------------------------
textToEncode = strings.Replace(textToEncode, "\n", "", -1)
textToEncode = strings.Replace(textToEncode, "\r", "", -1)
if strings.ToLower(textToEncode) == "quit" {
fmt.Println("Program stopped.")
retcode = int(100)
return
}
//--------------------------------
// Encode the string to a string
//--------------------------------
encoded, encoderStatus := mteEncoder.EncodeStrB64(textToEncode)
if encoderStatus != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encode error (%v): %v\n",
mte.GetStatusName(encoderStatus), mte.GetStatusDescription(encoderStatus))
retcode = int(encoderStatus)
return
}
//--------------------------------------------------------------------------
// (optional) convert to base64 to view outgoing mte packet
// This is for demonstration purposes ONLY and should NOT be done normally
//--------------------------------------------------------------------------
fmt.Printf("Base64 encoded representation of the packet being sent: %q\n\n", encoded)
//--------------------------
// Decode string to string
//--------------------------
decoded, decoderStatus := mteDecoder.DecodeStrB64(encoded)
if mte.StatusIsError(decoderStatus) {
fmt.Fprintf(os.Stderr, "Decode error (%v): %v\n",
mte.GetStatusName(decoderStatus), mte.GetStatusDescription(decoderStatus))
retcode = int(decoderStatus)
return
} else if decoderStatus != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Decode warning (%v): %v\n",
mte.GetStatusName(decoderStatus), mte.GetStatusDescription(decoderStatus))
}
//-----------------------------------------
// If the decoded is blank -- notify user
// otherwise display decoded message
//-----------------------------------------
if len(decoded) == 0 {
fmt.Print(os.Stderr, "Message was blank\n")
} else {
fmt.Printf("Decoded Message: '%s'", decoded)
}
}
}
<?php
define("COMPANY", "company");
define("LICENSE", "license");
$inputString = "hello";
$personalizationString = "demo";
// 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(COMPANY, LICENSE)){
throw new Exception ("MTE license appears to be invalid. MTE cannot be initialized.");
}
echo "Original data: ".$inputString."<br><br>";
// Create the Encoder and Decoder.
$mteEnc = new MteEnc();
$mteDec = new MteDec();
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
$entropyBytes = $mteEnc->getDrbgsEntropyMinBytes(constant($mteEnc->getDrbg()));
$entropy = "";
$entropy = str_pad($entropy, $entropyBytes, "0");
// Instantiate the Encoder.
$mteEnc->setEntropy($entropy);
$mteEnc->setNonce(0);
$mteStatus = $mteEnc->instantiate($personalizationString);
if (constant($mteStatus)!=mte_status_success) {
echo "Encoder instantiate error: ".$mteEnc->getStatusName(constant($mteStatus)).":"
.$mteEnc->getStatusDescription(constant($mteStatus))."<br><br>";
return $mteEncoder->getStatusCode(constant($mteStatus));
}
$encoded = $mteEnc->encodeB64($inputString);
if (constant($encoded["status"])!=mte_status_success) {
echo "Encoder encode error: ".$mteEnc->getStatusName(constant($encoded["status"])).":"
.$mteEnc->getStatusDescription(constant($encoded["status"]))."<br><br>";
return $mteEncoder->getStatusCode(constant($encoded["status"]));
}
// Uninstantiate and unset the Encoder
$mteEnc->uninstantiate();
unset($mteEnc);
// Display the MTE encoded message.
echo "Base64 message: ". $encoded["str"]. "<br><br>";
// Instantiate the Decoder.
$mteDec->setEntropy($entropy);
$mteDec->setNonce(0);
$mteStatus = $mteDec->instantiate($personalizationString);
if (constant($mteStatus)!=mte_status_success) {
echo "Decoder instantiate error: ".$mteDec->getStatusName(constant($mteStatus)).":"
.$mteDec->getStatusDescription(constant($mteStatus))."<br><br>";
return $mteDec->getStatusCode(constant($mteStatus));
}
$decoded = $mteDec->decodeB64($encoded["str"]);
if($mteDec->statusIsError(constant($decoded["status"]))){
echo "Decoder decode error: ".$mteDec->getStatusName(constant($decoded["status"])).":"
.$mteDec->getStatusDescription(constant($decoded["status"]))."<br><br>";
return $mteDec->getStatusCode(constant($decoded["status"]));
}
// Display the decoded Data
echo "Decoded data: ".$decoded["str"]."<br><br>";
// Uninstantiate and unset Decoder
$mteDec->uninstantiate();
unset($mteDec);
?>