mke_encode_decode
- C
- C++
- CSharp
- Java
- Swift
- ObjC
- Python
- Go
#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;
char input[128];
char personal[128];
MTE_SIZE_T input_bytes;
#if MTE_RUNTIME
MTE_SIZE_T i;
char line[80];
#endif
/* Status. */
mte_status status;
/* Options. */
mte_mke_enc_init_info e_info = MTE_MKE_ENC_INIT_INFO_INIT(
MTE_DRBG_ENUM, MTE_TOKBYTES, MTE_VERIFIERS_ENUM,
MTE_CIPHER_ENUM, MTE_HASH_ENUM, NULL, NULL, NULL, NULL, NULL, NULL);
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_drbg_inst_info i_info = { &ei_cb, NULL, &n_cb, NULL, personal, 0 };
/* Encoder. */
char *encoded;
MTE_HANDLE encoder;
mte_enc_args e_args = MTE_ENC_ARGS_INIT(NULL, 0, NULL, &t_cb, NULL);
/* Decoder. */
char *decoded;
MTE_HANDLE decoder;
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;
}
}
/* 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';
i_info.ps_bytes = (MTE_SIZE_T)strlen(personal);
/* Prompt for the options if this build has runtime options. */
#if MTE_RUNTIME
/* Get the DRBG. */
printf("DRBGs:");
for (i = 1; i < mte_base_drbgs_count(); ++i)
{
printf(" %s", mte_base_drbgs_name((mte_drbgs)i));
}
printf("\nEnter the DRBG> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
e_info.enc_params.drbg = d_info.dec_params.drbg = mte_base_drbgs_algo(line);
/* Get the token size. */
printf("Enter the token size in bytes> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
e_info.enc_params.tok_bytes = d_info.dec_params.tok_bytes =
(MTE_SIZE8_T)strtoul(line, NULL, 10);
/* Get the verifiers. */
printf("Verifiers:");
for (i = 0; i < mte_base_verifiers_count(); ++i)
{
printf(" %s", mte_base_verifiers_name((mte_verifiers)i));
}
printf("\nEnter the verifiers> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
e_info.enc_params.verifiers = d_info.dec_params.verifiers =
mte_base_verifiers_algo(line);
/* Get the cipher. */
printf("Ciphers:");
for (i = 1; i < mte_base_ciphers_count(); ++i)
{
printf(" %s", mte_base_ciphers_name((mte_ciphers)i));
}
printf("\nEnter the cipher> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
e_info.cipher = d_info.cipher = mte_base_ciphers_algo(line);
/* Get the hash. */
printf("Hashes:");
for (i = 1; i < mte_base_hashes_count(); ++i)
{
printf(" %s", mte_base_hashes_name((mte_hashes)i));
}
printf("\nEnter the hash> ");
fflush(stdout);
(void)!fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
e_info.hash = d_info.hash = mte_base_hashes_algo(line);
#endif
/* Create the encoder. */
encoder = MTE_ALLOCA(mte_mke_enc_state_bytes(&e_info));
status = mte_mke_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_mke_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_mke_enc_buff_bytes_b64(encoder, input_bytes));
/* Encode the message. */
MTE_SET_ENC_IO(e_args, input, input_bytes, encoded);
status = mte_mke_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. */
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;
}
/* Allocate the buffer for decoding. */
decoded = MTE_ALLOCA(mte_mke_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_mke_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, input_bytes) == 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_mke_enc_uninstantiate(encoder);
mte_mke_dec_uninstantiate(decoder);
return exitCode;
}
static mte_status ei_cb(void *context, mte_drbg_ei_info *info)
{
/* Create all-zero entropy for this demo. This should never be done in real
applications. */
(void)context;
info->bytes = info->min_length;
memset(info->buff, 0, info->min_length);
return mte_status_success;
}
static void n_cb(void *context, mte_drbg_nonce_info *info)
{
/* Create all-zero nonce for this demo. This should never be done in real
applications. */
(void)context;
info->bytes = info->min_length;
memset(info->buff, 0, info->min_length);
}
static MTE_UINT64_T t_cb(void *context)
{
/* Return 0 for the timestamp. Real applications would request an actual
timestamp as appropriate for their system. */
(void)context;
return 0;
}
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
// 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();
mte_ciphers cipher = MteBase::getDefaultCipher();
mte_hashes hash = MteBase::getDefaultHash();
// 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());
// Get the cipher.
std::cout << "Ciphers:";
for (i = 1; i < MteBase::getCiphersCount(); ++i)
{
std::cout << ' ' << MteBase::getCiphersName(static_cast<mte_ciphers>(i));
}
std::cout << "\nEnter the cipher> " << std::flush;
std::cin >> line;
cipher = MteBase::getCiphersAlgo(line.c_str());
// Get the hash.
std::cout << "Hashes:";
for (i = 1; i < MteBase::getHashesCount(); ++i)
{
std::cout << ' ' << MteBase::getHashesName(static_cast<mte_hashes>(i));
}
std::cout << "\nEnter the hash> " << std::flush;
std::cin >> line;
hash = MteBase::getHashesAlgo(line.c_str());
}
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
size_t entropyBytes = MteBase::getDrbgsEntropyMinBytes(drbg);
uint8_t *entropy = new uint8_t[entropyBytes];
memset(entropy, 0, entropyBytes);
// Create the encoder.
MteMkeEnc encoder(drbg, tokBytes, verifiers, cipher, hash);
encoder.setEntropy(entropy, entropyBytes);
encoder.setNonce(0);
status = encoder.instantiate(personal);
if (status != mte_status_success)
{
std::cerr << "Encoder instantiate error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
delete[] entropy;
return status;
}
// Note that after the instantiate call, the entropy buffer will be zeroized.
// In this demo, the entropy buffer was set to all zeroes to begin with.
// Care should be taken to ensure that if the same entropy buffer is used
// again for a paired encoder/decoder, that buffer must be set identically
// before an instantiate call. Alternatively, two different entropy buffers
// with identical values may be used.
// Encode/encrypt 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.
MteMkeDec decoder(drbg,
tokBytes,
verifiers,
cipher,
hash,
timestampWindow,
sequenceWindow);
decoder.setEntropy(entropy, entropyBytes);
decoder.setNonce(0);
status = decoder.instantiate(personal);
if (status != mte_status_success)
{
std::cerr << "Decoder instantiate error ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// 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;
// 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.
delete[] entropy;
return 0;
}
using System;
using System.Text;
namespace MTE {
class demoCsMke {
// The timestamp window and sequencing window are hard coded for this
// demo.
private const UInt64 timestampWindow = 1;
private const Int32 sequenceWindow = 0;
static int Main(string[] args) {
// Status.
MteStatus status = MteStatus.mte_status_success;
// Options.
MteDrbgs drbg;
int tokBytes;
MteVerifiers verifiers;
MteCiphers cipher;
MteHashes hash;
// 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;
}
}
// Get the input data.
Console.Write("Enter the data to encode> ");
string input = Console.ReadLine();
// Get the personalization string.
Console.Write("Enter the personalization> ");
string personal = Console.ReadLine();
// Set up the options to use the buildtime options if the library is built
// for that; otherwise prompt for the options.
if (baseObj.HasRuntimeOpts()) {
// Get the DRBG.
Console.Write("DRBGs:");
for (int i = 1; i < baseObj.GetDrbgsCount(); ++i) {
Console.Write(" {0}", baseObj.GetDrbgsName((MteDrbgs)i));
}
Console.WriteLine();
Console.Write("Enter the DRBG> ");
drbg = baseObj.GetDrbgsAlgo(Console.ReadLine());
// Get the token size.
Console.Write("Enter the token size in bytes> ");
tokBytes = Convert.ToInt32(Console.ReadLine());
// Get the verifiers.
Console.Write("Verifiers:");
for (int i = 0; i < baseObj.GetVerifiersCount(); ++i) {
Console.Write(" {0}", baseObj.GetVerifiersName((MteVerifiers)i));
}
Console.WriteLine();
Console.Write("Enter the verifiers> ");
verifiers = baseObj.GetVerifiersAlgo(Console.ReadLine());
// Get the cipher.
Console.Write("Ciphers:");
for (int i = 1; i < baseObj.GetCiphersCount(); ++i) {
Console.Write(" {0}", baseObj.GetCiphersName((MteCiphers)i));
}
Console.WriteLine();
Console.Write("Enter the cipher> ");
cipher = baseObj.GetCiphersAlgo(Console.ReadLine());
// Get the hash.
Console.Write("Hashes:");
for (int i = 1; i < baseObj.GetHashesCount(); ++i) {
Console.Write(" {0}", baseObj.GetHashesName((MteHashes)i));
}
Console.WriteLine();
Console.Write("Enter the hash> ");
hash = baseObj.GetHashesAlgo(Console.ReadLine());
} else {
drbg = baseObj.GetDefaultDrbg();
tokBytes = baseObj.GetDefaultTokBytes();
verifiers = baseObj.GetDefaultVerifiers();
cipher = baseObj.GetDefaultCipher();
hash = baseObj.GetDefaultHash();
}
// 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 = baseObj.GetDrbgsEntropyMinBytes(drbg);
byte[] entropy = new byte[entropyBytes];
// Create the Encoder.
MteMkeEnc encoder = new MteMkeEnc(drbg,
tokBytes,
verifiers,
cipher,
hash);
encoder.SetEntropy(entropy);
encoder.SetNonce(0);
status = encoder.Instantiate(personal);
if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Encoder instantiate error ({0}): " +
encoder.GetStatusDescription(status),
encoder.GetStatusName(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 encoded message.
Console.WriteLine("Base64 message: {0}", encoded);
// Create the Decoder.
MteMkeDec decoder = new MteMkeDec(drbg,
tokBytes,
verifiers,
cipher,
hash,
timestampWindow,
sequenceWindow);
decoder.SetEntropy(entropy);
decoder.SetNonce(0);
status = decoder.Instantiate(personal);
if (status != MteStatus.mte_status_success) {
Console.Error.WriteLine("Decoder instantiate error ({0}): " +
decoder.GetStatusDescription(status),
decoder.GetStatusName(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.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class demoJavaMke
{
// The timestamp window and sequencing window are hard coded for this demo.
private static final long timestampWindow = 1;
private static final int sequenceWindow = 0;
public static void main(String[] args) throws IOException
{
// Status.
MteStatus status;
// Options.
MteDrbgs drbg;
int tokBytes;
MteVerifiers verifiers;
MteCiphers cipher;
MteHashes hash;
// 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());
}
}
// Buffered input.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Get the input data.
System.out.print("Enter the data to encode> ");
String input = br.readLine();
// Get the personalization string.
System.out.print("Enter the personalization> ");
String personal = br.readLine();
// Set up the options to use the buildtime options if the library is built
// for that; otherwise prompt for the options.
if (MteBase.hasRuntimeOpts())
{
// Get the DRBG.
System.out.print("DRBGs:");
for (int i = 1; i < MteBase.getDrbgsCount(); ++i)
{
System.out.print(" " + MteBase.getDrbgsName(MteDrbgs.valueOf(i)));
}
System.out.println();
System.out.print("Enter the DRBG> ");
drbg = MteBase.getDrbgsAlgo(br.readLine());
// Get the token size.
System.out.print("Enter the token size in bytes> ");
tokBytes = Integer.parseInt(br.readLine());
// Get the verifiers.
System.out.print("Verifiers:");
for (int i = 0; i < MteBase.getVerifiersCount(); ++i)
{
System.out.print(" " +
MteBase.getVerifiersName(MteVerifiers.valueOf(i)));
}
System.out.println();
System.out.print("Enter the verifiers> ");
verifiers = MteBase.getVerifiersAlgo(br.readLine());
// Get the cipher.
System.out.print("Ciphers:");
for (int i = 1; i < MteBase.getCiphersCount(); ++i)
{
System.out.print(" " + MteBase.getCiphersName(MteCiphers.valueOf(i)));
}
System.out.println();
System.out.print("Enter the cipher> ");
cipher = MteBase.getCiphersAlgo(br.readLine());
// Get the hash.
System.out.print("Hashes:");
for (int i = 1; i < MteBase.getHashesCount(); ++i)
{
System.out.print(" " + MteBase.getHashesName(MteHashes.valueOf(i)));
}
System.out.println();
System.out.print("Enter the hash> ");
hash = MteBase.getHashesAlgo(br.readLine());
} else {
drbg = MteBase.getDefaultDrbg();
tokBytes = MteBase.getDefaultTokBytes();
verifiers = MteBase.getDefaultVerifiers();
cipher = MteBase.getDefaultCipher();
hash = MteBase.getDefaultHash();
}
// 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(drbg);
byte[] entropy = new byte[entropyBytes];
// Create the Encoder.
MteMkeEnc encoder = new MteMkeEnc(drbg,
tokBytes,
verifiers,
cipher,
hash);
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 encoded message.
System.out.println("Base64 message: " + encoded.str);
// Create the Decoder.
MteMkeDec decoder = new MteMkeDec(drbg,
tokBytes,
verifiers,
cipher,
hash,
timestampWindow,
sequenceWindow);
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);
}
}
import Foundation
// Command line arguments. Default any that are not passed in:
// [1] = input data to be tokenized.
public func main() -> Int32 {
// Status.
var status: mte_status
// Input.
let input = CommandLine.argc > 1 ? CommandLine.arguments[1] : "hello"
// Personalization string.
let 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") {
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)
}
}
// Output original data.
print("Original data: \(input)")
// Create the encoder and decoder.
let encoder = try! MteMkeEnc()
let decoder = try! MteMkeDec()
// Create all-zero entropy for this demo. The nonce will also be set to 0.
// This should never be done in real applications.
let entropyBytes = MteBase.getDrbgsEntropyMinBytes(encoder.getDrbg())
var entropy = [UInt8](repeating: 0, count: entropyBytes)
// Instantiate the encoder.
encoder.setEntropy(&entropy)
encoder.setNonce(0)
status = encoder.instantiate(personal)
if status != mte_status_success {
print("Encoder instantiate error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.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 message.
print("Base64 message: \(encoded)")
// Instantiate the decoder.
decoder.setEntropy(&entropy)
decoder.setNonce(0)
status = decoder.instantiate(personal)
if status != mte_status_success {
print("Decoder instantiate error (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.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)")
// 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 "MteMkeEnc.h"
#import "MteMkeDec.h"
int main() {
uint64 min = 999999999999;
uint64 max = UINT_MAX;
int entropySize = 32;
uint8_t *encoderEntropy[entropySize];
uint64 encoderNonce = 0;
NSString *encoderPersonalityString = @"";
uint8_t *decoderEntropy[entropySize];
uint64 decoderNonce = 0;
NSString *decoderPersonalityString = @"";
// Status.
mte_status status;
NSString *valueToEncode = @"hello";
// MARK: Options
mte_drbgs drbg;
NSInteger tokBytes;
mte_verifiers verifiers;
mte_ciphers cipher;
mte_hashes hash;
// For this Sample, we will hard-code these two Options
uint64 timestampWindow = 1;
int32_t sequenceWindow = 0;
@autoreleasepool {
puts("****** Simple Objective-C MKE Add-On 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;
}
// MARK: Initialize Initial Values
// Fill the entropy variables
if (SecRandomCopyBytes(kSecRandomDefault, entropySize, 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;
// MARK: Initialize Options
// If Options were set at Buildtime, these must
// be used, otherwise they need to be set
if ([MteBase hasBuildtimeOpts]) {
drbg = [MteBase getBuildtimeDrbg];
tokBytes = [MteBase getBuildtimeTokBytes];
verifiers = [MteBase getBuildtimeVerifiers];
cipher = [MteBase getBuildtimeCipher];
hash = [MteBase getBuildtimeHash];
} else {
drbg = mte_drbgs_ctr_aes256_df;
tokBytes = 16;
verifiers = mte_verifiers_t64_crc32_seq;
cipher = mte_ciphers_aes256_ctr;
hash = mte_hashes_sha256;
}
// Create Encoder with Options
MteMkeEnc *encoder = MTE_AUTORELEASE([[MteMkeEnc alloc] initWithDrbg:drbg
tokBytes:tokBytes
verifiers:verifiers
cipher:cipher
hash:hash]);
[encoder setEntropy:encoderEntropy bytes:entropySize];
[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 Decoder with Options
MteMkeDec *decoder = MTE_AUTORELEASE([[MteMkeDec alloc] initWithDrbg:drbg
tokBytes:tokBytes
verifiers:verifiers
cipher:cipher
hash:hash
tWindow:timestampWindow
sWindow:sequenceWindow]);
[decoder setEntropy:decoderEntropy bytes:entropySize];
[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;
}
puts("Closing the Application.\n");
}
return 0;
}
#!/usr/bin/env python3
# Import relevant modules for the program.
from MteCiphers import MteCiphers
from MteHashes import MteHashes
from MteDrbgs import MteDrbgs
from MteVerifiers import MteVerifiers
from MteStatus import MteStatus
from MteBase import MteBase
from MteMkeEnc import MteMkeEnc
from MteMkeDec import MteMkeDec
import os
import sys
# The timestamp window and sequencing window are hard coded for this demo.
timestamp_window = 1
sequence_window = 0
def main():
# 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):
status = MteStatus.mte_status_license_error
print("License init error ({0}): {1}".format(MteBase.get_status_name(status),\
MteBase.get_status_description(status),\
file=sys.stderr))
return MteStatus.mte_status_license_error.value
# Get the input data.
input_data = input("Enter the data to encode\n> ")
# Get the personalization string.
personal_str = input("Enter personalization\n> ")
# Set up the options to use the buildtime options if the library is built
# for that; otherwise prompt for the options.
if MteBase.has_buildtime_opts():
drbg = MteBase.get_buildtime_drbg()
tok_bytes = MteBase.get_tok_bytes()
verifiers = MteBase.get_verifiers()
cipher = MteBase.get_buildtime_cipher()
hash_ = MteBase.get_buildtime_hash()
else:
# Get the DRBG.
drbg_list = []
print("DRBGs:",end="\n")
for i in range(1, MteBase.get_drbgs_count()):
print("{0}. {1}\n".format(i,MteBase.get_drbgs_name(MteDrbgs(i))), end="")
drbg_list.append(MteBase.get_drbgs_name(MteDrbgs(i)))
drbg = input("Enter the DRBG number\n> ")
drbg = MteBase.get_drbgs_algo(drbg_list[int(drbg)-1])
# Get the token size.
tok_bytes = int(input("Enter the token size in bytes\n> "))
# Get the verifiers.
verifiers_list = []
print("Verifiers:",end="\n")
for i in range(1, MteBase.get_verifiers_count()):
print("{0}. {1}\n".format(i,MteBase.get_verifiers_name(MteVerifiers(i))), end="")
verifiers_list.append(MteBase.get_verifiers_name(MteVerifiers(i)))
verifiers = input("Enter the verifier number\n> ")
verifiers = MteBase.get_verifiers_algo(verifiers_list[int(verifiers)-1])
# Get the cipher.
cipher_list = []
print("Ciphers:",end="\n")
for i in range(1, MteBase.get_ciphers_count()):
print("{0}. {1}\n".format(i,MteBase.get_ciphers_name(MteCiphers(i))), end="")
cipher_list.append(MteBase.get_ciphers_name(MteCiphers(i)))
cipher = input("Enter the cipher number\n> ")
cipher = MteBase.get_ciphers_algo(cipher_list[int(cipher)-1])
# Get the hashing algorithm.
hash_list = []
print("Hashes:", end="\n")
for i in range(1, MteBase.get_hashes_count()):
print("{0}. {1}\n".format(i,MteBase.get_hashes_name(MteHashes(i))), end="")
hash_list.append(MteBase.get_hashes_name(MteHashes(i)))
hash_ = input("Enter the hash number\n> ")
hash_ = MteBase.get_hashes_algo(hash_list[int(hash_)-1])
# Create all zero entropy for this demo. The nonce will also be set to zero.
# This should never be done in real applications.
entropy = "0"
entropy_min_bytes = MteBase.get_drbgs_entropy_min_bytes(drbg)
while len(entropy) < entropy_min_bytes:
entropy += "0"
entropy = bytearray(entropy,'utf-8')
# Create the Encoder.
encoder = MteMkeEnc(drbg,tok_bytes,verifiers,cipher,hash_)
encoder.set_entropy(entropy)
encoder.set_nonce(0)
status = encoder.instantiate(personal_str)
if status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(status),\
MteBase.get_status_description(status)
print("Encoder instantiate error ({0}): {1}".format(\
status,message),file=sys.stderr)
# Encode the input.
(encoded, status) = encoder.encode_b64(input_data)
if status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(status),\
MteBase.get_status_description(status)
print("Encode error ({0}): {1}".format(\
status,message),file=sys.stderr)
# Display the encoded message.
print(f'Base64 message: {encoded}')
# Create the Decoder.
decoder = MteMkeDec(drbg, tok_bytes, verifiers, cipher,
hash_, timestamp_window, sequence_window)
decoder.set_entropy(entropy)
decoder.set_nonce(0)
status = decoder.instantiate(personal_str)
status = decoder.instantiate(personal_str)
if status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(status),\
MteBase.get_status_description(status)
print("Decoder instantiate error ({0}): {1}".format(\
status,message),file=sys.stderr)
# 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))
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))
# Compare the decoded data against the original data.
if decoded == input_data:
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"
"os"
"goMke/mte"
)
// The timestamp window and sequencing window are hard coded for this demo.
const (
timestampWindow = 1
sequenceWindow = 0
)
func doMain() int {
// Status.
var status mte.Status
// Options.
var drbg mte.Drbgs
var tokBytes int
var verifiers mte.Verifiers
var cipher mte.Ciphers
var hash mte.Hashes
// 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.InitLicense("YOUR_COMPANY", "YOUR_LICENSE") {
company := os.Getenv("MTE_COMPANY")
license := os.Getenv("MTE_LICENSE")
if len(company) == 0 || len(license) == 0 ||
!mte.InitLicense(company, license) {
fmt.Fprintf(os.Stderr, "License init error (%v): %v\n",
mte.GetStatusName(mte.Status_mte_status_license_error),
mte.GetStatusDescription(mte.Status_mte_status_license_error))
return int(mte.Status_mte_status_license_error)
}
}
// Scanner input.
scanner := bufio.NewScanner(os.Stdin)
// Get the input data.
fmt.Print("Enter the data to encode> ")
scanner.Scan()
input := scanner.Text()
// Get the personalization string.
fmt.Print("Enter the personalization> ")
scanner.Scan()
personal := scanner.Text()
// Set up the options to use the buildtime options if the library is built
// for that; otherwise prompt for the options.
if mte.HasRuntimeOpts() {
// Get the DRBG.
fmt.Print("DRBGs:")
for i := 1; i < mte.GetDrbgsCount(); i++ {
fmt.Printf(" %v", mte.GetDrbgsName(mte.Drbgs(i)))
}
fmt.Print("\nEnter the DRBG> ")
scanner.Scan()
drbg = mte.GetDrbgsAlgo(scanner.Text())
// Get the token size.
fmt.Print("Enter the token size in bytes> ")
fmt.Scan(&tokBytes)
// Get the verifiers.
fmt.Print("Verifiers:")
for i := 0; i < mte.GetVerifiersCount(); i++ {
fmt.Printf(" %v", mte.GetVerifiersName(mte.Verifiers(i)))
}
fmt.Printf("\nEnter the verifiers> ")
scanner.Scan()
verifiers = mte.GetVerifiersAlgo(scanner.Text())
// Get the cipher.
fmt.Print("Ciphers:")
for i := 1; i < mte.GetCiphersCount(); i++ {
fmt.Printf(" %v", mte.GetCiphersName(mte.Ciphers(i)))
}
fmt.Print("\nEnter the cipher> ")
scanner.Scan()
cipher = mte.GetCiphersAlgo(scanner.Text())
// Get the hash.
fmt.Print("Hashes:")
for i := 1; i < mte.GetHashesCount(); i++ {
fmt.Printf(" %v", mte.GetHashesName(mte.Hashes(i)))
}
fmt.Print("\nEnter the hash> ")
scanner.Scan()
hash = mte.GetHashesAlgo(scanner.Text())
} else {
drbg = mte.GetDefaultDrbg()
tokBytes = mte.GetDefaultTokBytes()
verifiers = mte.GetDefaultVerifiers()
cipher = mte.GetDefaultCipher()
hash = mte.GetDefaultHash()
}
// 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(drbg)
entropy := make([]byte, entropyBytes)
// Create the Encoder.
encoder := mte.NewMkeEncOpt(drbg, tokBytes, verifiers, cipher, hash)
defer encoder.Destroy()
encoder.SetEntropy(entropy)
encoder.SetNonceInt(0)
status = encoder.InstantiateStr(personal)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encoder instantiate error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status)
}
// Encode the input.
encoded, status := encoder.EncodeStrB64(input)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encode/encrypt error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status)
}
// Display the message.
fmt.Printf("Base64 message: %v\n", encoded)
// Create the Decoder.
decoder := mte.NewMkeDecOpt(drbg,
tokBytes,
verifiers,
cipher,
hash,
timestampWindow,
sequenceWindow)
defer decoder.Destroy()
decoder.SetEntropy(entropy)
decoder.SetNonceInt(0)
status = decoder.InstantiateStr(personal)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Decoder instantiate error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status)
}
// Decode the message.
decoded, status := decoder.DecodeStrB64(encoded)
if mte.StatusIsError(status) {
fmt.Fprintf(os.Stderr, "Decode error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
return int(status)
} else if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Decode warning (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
}
// Output the decoded data.
fmt.Printf("Decoded data: %v\n", decoded)
// Compare the decoded data against the original data.
if decoded == input {
fmt.Println("The original data and decoded data match.")
} else {
fmt.Println("The original data and decoded data DO NOT match.")
return -1
}
// Success.
return 0
}
func main() {
os.Exit(doMain())
}