mke_encode_chunking
- C
- C++
- CSharp
- Java
- Swift
- Python
- Go
// Init the MTE.
if (!mte_init(NULL, NULL))
{
printf("There was an error attempting to initialize the MTE.\n");
return 1;
}
// Initialize MTE license. If a license code is not required (e.g., trial
// mode), this can be skipped.
if (!mte_license_init("LicenseCompanyName", "LicenseKey"))
{
printf("There was an error attempting to initialize the MTE License.\n");
return 1;
}
// Check encrypt and decrypt chunk sizes.
size_t block_size = mte_base_ciphers_block_bytes(MTE_CIPHER_ENUM);
if (block_size > 1)
{
printf("The chunk size must be set to 1.");
return 1;
}
mte_status status;
// Set personalization string to demo for this sample.
const char* personal = "demo";
// Set nonce to the timestamp.
nonce = get_timestamp();
// Get minimum entropy amount of bytes.
size_t min_entropy_bytes = mte_base_drbgs_entropy_min_bytes(MTE_DRBG_ENUM);
if (min_entropy_bytes == 0)
{
min_entropy_bytes = 1;
}
entropy_size = min_entropy_bytes;
entropy_buff = malloc(min_entropy_bytes);
// Create byte array of random bytes to use as entropy.
int res = get_random(entropy_buff, entropy_size);
if (res != 0)
{
printf("There was an error attempting to create random entropy.\n");
return res;
}
// Create default MKE Encoder.
mte_mke_enc_init_info encoder_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);
static MTE_HANDLE encoder;
encoder = malloc(mte_mke_enc_state_bytes(&encoder_info));
// Initiate the Encoder state.
status = mte_mke_enc_state_init(encoder, &encoder_info);
if (status != mte_status_success)
{
printf("Encoder init error (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return 1;
}
// Set the Encoder instantiation information.
mte_drbg_inst_info enc_inst_info = { &entropy_input_callback, NULL, &nonce_callback, NULL, personal, strlen(personal) };
status = mte_mke_enc_instantiate(encoder, &enc_inst_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;
}
while (true)
{
char file_path[256];
printf("Please enter path to file (To end please type 'quit')\n");
fflush(stdout);
(void)fgets(file_path, sizeof(file_path), stdin);
file_path[strlen(file_path) - 1] = '\0';
if (strcasecmp(file_path, "quit") == 0)
{
break;
}
const char* base_file_name;
// Find last index of the path separator character.
char* path_char_index = strrchr(file_path, path_separator_char);
if (path_char_index == NULL) {
// No path characters in file name.
base_file_name = file_path;
}
else
{
// Get everything after path character.
base_file_name = path_char_index + 1;
}
// Get last index of period for file extension.
const char* file_extension;
char* file_extension_index = strrchr(base_file_name, '.');
if (file_extension_index == NULL)
{
// No extension in file name.
file_extension = "";
}
else
{
// Include the period in the file extension.
file_extension = file_extension_index;
}
// Create input file stream.
FILE* input_file;
size_t file_size = 0;
// Open the input file, for read mode "r" and binary "b".
input_file = fopen(file_path, "rb");
if (input_file == NULL)
{
fprintf(stderr, "Error reading file.");
break;
}
// Get the input file size.
fseek(input_file, 0, SEEK_END);
file_size = ftell(input_file);
// Close the input file.
fclose(input_file);
//=========================================////
//***** Begin MKE Encryption Process. *****////
//=========================================////
// Create encoded file name that includes the same extension.
char encoded_file_name[256] = "encoded";
strcat(encoded_file_name, file_extension);
// Delete any existing encoded file.
res = remove(encoded_file_name);
if (res == 0)
{
printf("Previous file %s deleted.\n", encoded_file_name);
}
// Create buffer to hold encrypt chunk size.
char* encrypt_chunk_buf;
encrypt_chunk_buf = malloc(encrypt_chunk_size);
// Get the chunk state size requirement.
size_t buff_bytes = mte_mke_enc_encrypt_state_bytes(encoder);
// Create buffer to hold MTE encryption.
unsigned char* enc_mke_buf;
enc_mke_buf = malloc(buff_bytes);
// Start chunking session.
status = mte_mke_enc_encrypt_start(encoder, enc_mke_buf);
if (status != mte_status_success)
{
fprintf(stderr, "Error starting encryption: (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
// Re-open input file, for read mode "r" and binary "b".
input_file = fopen(file_path, "rb");
// Open the encoded file, for write mode "w" and binary "b".
FILE* encoded_file;
encoded_file = fopen(encoded_file_name, "wb");
mte_enc_args encoding_args = MTE_ENC_ARGS_INIT(NULL, 0, NULL, ×tamp_callback, NULL);
// Go through until the end of the input file.
while (!feof(input_file))
{
// Set encrypt chunk to zero.
memset(encrypt_chunk_buf, '\0', encrypt_chunk_size);
// Read a portion of the input file of size encrypt_chunk_size to the encryption buffer.
size_t amount = fread(encrypt_chunk_buf, 1, encrypt_chunk_size, input_file);
// Check if the amount read is 0, the end of input file has been reached.
if (amount == 0)
{
continue;
}
// Encrypt the chunk buffer. Use the amount read from this pass.
// The same buffer can be used to encrypt in place, but is not necessary.
// This means the input buffer and the encrypted buffer can be the same.
MTE_SET_ENC_IO(encoding_args, encrypt_chunk_buf, amount, encrypt_chunk_buf);
status = mte_mke_enc_encrypt_chunk(encoder, enc_mke_buf, &encoding_args);
if (status != mte_status_success)
{
fprintf(stderr, "Error encrypting chunk: Status: %s/%s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return false;
}
if (encoding_args.bytes > 0)
{
// Write the chunk buffer to the encoded file.
fwrite(encoding_args.encoded, 1, encoding_args.bytes, encoded_file);
fflush(encoded_file);
}
}
// Close the input file.
fclose(input_file);
// Finish the encryption with the encryption buffer.
MTE_SET_ENC_IO(encoding_args, NULL, 0, NULL);
status = mte_mke_enc_encrypt_finish(encoder, enc_mke_buf, &encoding_args);
if (status != mte_status_success)
{
fprintf(stderr, "Error finishing encryption: (%s): %s\n",
mte_base_status_name(status),
mte_base_status_description(status));
return status;
}
if (encoding_args.bytes > 0)
{
// Write the result bytes from encrypt finish.
fwrite(encoding_args.encoded, 1, encoding_args.bytes, encoded_file);
fflush(encoded_file);
}
// Free the encrypt buffer.
free(encrypt_chunk_buf);
// Close the encoded file.
fclose(encoded_file);
printf("Successfully encoded file %s\n", encoded_file_name);
mte_status status;
// Initialize MTE license. If a license code is not required (e.g., trial
// mode), this can be skipped.
if (!MteBase::initLicense("LicenseCompanyName", "LicenseKey"))
{
status = mte_status_license_error;
std::cerr << "There was an error attempting to initialize the MTE License." << std::endl;
return status;
}
// Check encrypt and decrypt chunk sizes.
size_t blockSize = MteBase::getCiphersBlockBytes(MTE_CIPHER_ENUM);
if (blockSize > 1)
{
std::cerr << "The chunk size must be set to 1." << std::endl;
return 1;
}
// Set personalization string to demo for this sample.
std::string personal = "demo";
// Set nonce to the timestamp.
nonce = getTimestamp();
// Create the callbacks to get entropy, nonce, and timestamp.
Cbs cbs;
size_t minEntropySize = MteBase::getDrbgsEntropyMinBytes(MTE_DRBG_ENUM);
if (minEntropySize == 0)
{
minEntropySize = 1;
}
entropy = new uint8_t[minEntropySize];
// Populate entropy buffer with random bytes.
int res = getRandom(entropy, minEntropySize);
if (res != 0)
{
std::cerr << "There was an error attempting to create random entropy." << std::endl;
return mte_status_drbg_catastrophic;
}
// Create default MKE encoder.
MteMkeEnc encoder;
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;
}
while (true)
{
std::string filePath;
// Prompt for file path.
std::cout << "Please enter path to file (To end please type 'quit')" << std::endl;
std::getline(std::cin, filePath);
if (strcasecmp(filePath.c_str(), "quit") == 0)
{
break;
}
// Find the last index of the path separator character.
std::string baseFileName;
const char* pathIndexChar = strrchr(filePath.c_str(), path_separator_char);
if (pathIndexChar == nullptr)
{
// No path characters in file name.
baseFileName = filePath;
}
else
{
// Get everything after path character.
baseFileName = pathIndexChar + 1;
}
// Get last index of period for file extension.
std::string fileExtention;
const char* fileExtensionIndex = strrchr(baseFileName.c_str(), '.');
if (fileExtensionIndex == nullptr) {
// No extension in file name.
fileExtention = "";
}
else
{
// Include the period in the file extension.
fileExtention = fileExtensionIndex;
}
// Create input file stream for read and binary.
std::ifstream inputFile;
inputFile.open(filePath, std::ifstream::in | std::ifstream::binary);
if (!inputFile.good())
{
std::cerr << "Error opening file." << std::endl;
return -1;
}
// Get the input file size by seeking to the end, then return to beginning.
inputFile.seekg(0, inputFile.end);
size_t fileLength = inputFile.tellg();
inputFile.seekg(0, inputFile.beg);
//=========================================////
//***** Begin MKE Encryption Process. *****////
//=========================================////
// Create encoded file name that includes the same extension.
std::string encodedFileName = "encoded" + fileExtention;
// Open the encoded file stream for writing and binary.
std::ofstream encodedFile;
// Delete any existing encoded file.
if (std::remove(encodedFileName.c_str()) == 0)
{
std::cout << "Deleted existing file " << encodedFileName << std::endl;
}
encodedFile.open(encodedFileName, std::ofstream::out | std::ofstream::binary);
// Start chunking session.
status = encoder.startEncrypt();
if (status != mte_status_success)
{
std::cerr << "Error starting encryption: ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Go through until the end of the input file.
while (!inputFile.eof())
{
// Create buffer to hold encrypt chunk size.
char encryptChunkBuf[encryptChunkSize];
// Read a portion of the input file of size encryptChunkSize to the encryption buffer.
inputFile.read(encryptChunkBuf, encryptChunkSize);
// The amount read from the stream.
std::streamsize amountRead = inputFile.gcount();
// Encrypt the chunk buffer.
status = encoder.encryptChunk(encryptChunkBuf, amountRead);
if (status != mte_status_success)
{
std::cerr << "Error encrypting chunk: ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Write the chunk buffer to the encoded file.
encodedFile.write(encryptChunkBuf, amountRead);
encodedFile.flush();
}
// Close the input file.
inputFile.close();
// Finish the encryption with the encryption buffer.
size_t finishSize = 0;
const void* finishBuffer = encoder.finishEncrypt(finishSize, status);
if (status != mte_status_success)
{
std::cerr << "Error finishing encryption: ("
<< MteBase::getStatusName(status)
<< "): "
<< MteBase::getStatusDescription(status)
<< std::endl;
return status;
}
// Write the result bytes from encrypt finish.
if (finishSize > 0)
{
encodedFile.write(static_cast<const char*>(finishBuffer), finishSize);
encodedFile.flush();
}
// Close the encoded file.
encodedFile.close();
std::cout << "Successfully encoded file " << encodedFileName << std::endl;
//-----------------------
// Set encoded file name
//-----------------------
string encodedFileName = "encodedText";
//-----------------------------------
// Create default MTE MKE and Status
//-----------------------------------
MteMkeEnc mkeEncoder = new MteMkeEnc();
MteStatus encoderStatus;
//------------------------------------------------------------------------
// Set identifier
// These values should be treated like encryption keys
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
//------------------------------------------------------------------------
string identifier = "demo";
string fPath = string.Empty;
//--------------------------------------------------
// Prompt for path till we have one and it is valid
//--------------------------------------------------
while (string.IsNullOrWhiteSpace(fPath) || !File.Exists(fPath))
{
//------------------------------------
// Prompting message for file to copy
//------------------------------------
Console.WriteLine("Please enter path to file\n");
fPath = Console.ReadLine();
//-------------------------------
// Check to make sure file exits
//-------------------------------
if (!File.Exists(fPath))
{
Console.WriteLine($"File at the path '{fPath}' does not exist");
}
}
//----------------------------------------
// Set the correct extension for the file
//----------------------------------------
encodedFileName = $"{encodedFileName}{Path.GetExtension(fPath)}";
//---------------------------------------------------------------------
// Check how long entropy we need, set default all 0's
// should be treated like encryption keys - this is just example
//---------------------------------------------------------------------
int entropyMinBytes = mkeEncoder.GetDrbgsEntropyMinBytes(mkeEncoder.GetDrbg());
string entropy = (entropyMinBytes > 0) ? new String('0', entropyMinBytes) : entropy;
//--------------------------------
// Set MKE values for the Encoder
//--------------------------------
mkeEncoder.SetEntropy(Encoding.UTF8.GetBytes(entropy));
mkeEncoder.SetNonce(0);
//-------------------------
// Initialize MKE Encoder
//-------------------------
encoderStatus = mkeEncoder.Instantiate(identifier);
if (encoderStatus != MteStatus.mte_status_success)
{
throw new ApplicationException($"Failed to initialize the MTE encoder engine. Status: " +
$"{mkeEncoder.GetStatusName(encoderStatus)} / {mkeEncoder.GetStatusDescription(encoderStatus)}");
}
//-----------------------------
// Initialize chunking session
//-----------------------------
encoderStatus = mkeEncoder.StartEncrypt();
if(encoderStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to start encode chunk. Status: "
+ mkeEncoder.GetStatusName(encoderStatus)+ " / "
+ mkeEncoder.GetStatusDescription(encoderStatus));
}
//-------------------------------------------------------
// Before we start we want to delete any files
// that are already there in order to create new ones
//-------------------------------------------------------
if (File.Exists(encodedFileName))
{
File.Delete(encodedFileName);
}
//------------------------------------
// Read file in and encode using MKE
//------------------------------------
using (FileStream stream = File.OpenRead(fPath))
using (FileStream writeStream = File.OpenWrite(encodedFileName))
{
BinaryReader reader = new BinaryReader(stream);
BinaryWriter writer = new BinaryWriter(writeStream);
//-----------------------------------
// Create a buffer to hold the bytes
//-----------------------------------
byte[] buffer = new Byte[1024];
int bytesRead;
//------------------------------------------
// While the read method returns bytes
// Keep writing them to the output stream
//------------------------------------------
while ((bytesRead = stream.Read(buffer, 0, 1024)) > 0)
{
//-------------------------------
// Encode the data in place
// encoded data put back in buffer
//-------------------------------
MteStatus chunkStatus = mkeEncoder.EncryptChunk(buffer, 0, bytesRead);
if(chunkStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to encode chunk. Status: "
+ mkeEncoder.GetStatusName(chunkStatus)+ " / "
+ mkeEncoder.GetStatusDescription(chunkStatus));
}
writeStream.Write(buffer, 0, bytesRead);
}
//-----------------------------
// Finish the chunking session
//-----------------------------
byte[] finalEncodedChunk = mkeEncoder.FinishEncrypt(out MteStatus finishStatus);
if(finishStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to finish encode chunk. Status: "
+ mkeEncoder.GetStatusName(finishStatus)+ " / "
+ mkeEncoder.GetStatusDescription(finishStatus));
}
//-----------------------------------
// Append the final data to the file
//-----------------------------------
writeStream.Write(finalEncodedChunk, 0, finalEncodedChunk.Length);
}
private static final int BUFFER_SIZE = 1024; // 1KB
private static String _pathToEncodedFile = "src/encoded";
private static String _pathToDecodedFile = "src/decoded";
private static final String _defaultExtension = ".txt";
// -----------------
// Buffered input.
// -----------------
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fPath = "";
// ----------------------
// Prompt for file path
// ----------------------
System.out.print("Enter full path to file: \n");
//----------------------------------------
// Loop till we get a valid file to encode
//----------------------------------------
while(true) {
//---------------------------------------------
// Ensure file exists, and update both output
// files with correct file extension
//---------------------------------------------
fPath = br.readLine();
File textFile = new File(fPath);
if(textFile.exists()){
String filename = textFile.getName();
String extension = "";
if (filename.contains(".")) {
extension = filename.substring(filename.lastIndexOf("."));
_pathToEncodedFile = _pathToEncodedFile + extension;
_pathToDecodedFile = _pathToDecodedFile + extension;
}else {
_pathToEncodedFile = _pathToEncodedFile + _defaultExtension;
_pathToDecodedFile = _pathToDecodedFile + _defaultExtension;
}
break;
}else {
System.out.print("Invalid file path, please type in full path to file.\n");
}
}
//--------------------
// Create MKE Encoder
//--------------------
MteMkeEnc mkeEncoder = new MteMkeEnc();
//-------------------------------------------------------------------------
// Set identifier
// These values should be treated like encryption keys
// The following personalization string and nonce values are for
// demonstration only and should not be used in a production environment
//-------------------------------------------------------------------------
string identifier = "demo";
//---------------------------------------------------------------
// Check how long entropy we need, set default all 0's
// should be treated like encryption keys - this is just example
//---------------------------------------------------------------
int entropyMinBytes = MteBase.getDrbgsEntropyMinBytes(mkeEncoder.getDrbg());
String entropy = (entropyMinBytes > 0) ? new String('0', entropyMinBytes) : entropy;
//--------------------------------
// Set MKE values for the Encoder
//--------------------------------
mkeEncoder.setEntropy(entropy.getBytes());
mkeEncoder.setNonce(0);
//-------------------------
// Instantiate MKE Encoder
//-------------------------
MteStatus encoderStatus = mkeEncoder.instantiate(identifier);
if (encoderStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to initialize the MTE encoder engine. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
//-----------------------------
// Initialize chunking session
//-----------------------------
encoderStatus = mkeEncoder.startEncrypt();
if(encoderStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to start encode chunk. Status: "
+ MteBase.getStatusName(encoderStatus)+ " / "
+ MteBase.getStatusDescription(encoderStatus));
}
String inputFile = fPath;
String outputFile = _pathToEncodedFile;
//------------------------------------------------
// Delete file if exists so we can write new one
//------------------------------------------------
Path fileToDeletePathEN = Paths.get(outputFile);
Files.deleteIfExists(fileToDeletePathEN);
try (
InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile);
) {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
//------------------------------------------------------------
// Encode the data in place - encoded data put back in buffer
//------------------------------------------------------------
MteStatus chunkStatus = mkeEncoder.encryptChunk(buffer, 0, bytesRead);
if(chunkStatus != MteStatus.mte_status_success)
{
throw new Exception("Failed to encode chunk. Status: "
+ MteBase.getStatusName(chunkStatus)+ " / "
+ MteBase.getStatusDescription(chunkStatus));
}
//------------------------------------
// Write the encoded text to the file
//------------------------------------
outputStream.write(buffer, 0, bytesRead);
}
//-----------------------------
// Finish the chunking session
//-----------------------------
MteBase.ArrStatus finalEncodedChunk = mkeEncoder.finishEncrypt();
if(finalEncodedChunk.status != MteStatus.mte_status_success)
{
throw new Exception("Failed to finish encode chunk. Status: "
+ MteBase.getStatusName(finalEncodedChunk.status)+ " / "
+ MteBase.getStatusDescription(finalEncodedChunk.status));
}
//-----------------------------------
// Append the final data to the file
//-----------------------------------
outputStream.write(finalEncodedChunk.arr);
} catch (IOException ex) {
ex.printStackTrace();
}
// Status.
var status: mte_status
// Initialize MTE license. If a license code is not required (e.g., trial
// mode), this can be skipped.
if !MteBase.initLicense("LicenseCompanyName", "LicenseKey") {
let company = ProcessInfo.processInfo.environment["LicenseCompanyName"]
let license = ProcessInfo.processInfo.environment["LicenseKey"];
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)
}
}
// This sample works with the MKE add-on that uses a cipher block size of 1. Any other
// cipher block sizes are not guaranteed to work.
let blockSize = MteBase.getCiphersBlockBytes(MteBase.getDefaultCipher())
if (blockSize > 1)
{
print("The chunk size must be set to 1.")
return 1
}
// Set personalization string to demo for this sample.
let personal = "demo"
// Set nonce to the timestamp.
gNonce = getTimestamp()
// Create the callbacks to get entropy, nonce, and timestamp from stdin.
let cbs = Cbs()
// Get the minimum entropy size in bytes.
var minEntropySize = MteBase.getDrbgsEntropyMinBytes(MteBase.getDefaultDrbg())
if minEntropySize == 0 {
minEntropySize = 1
}
// Create entropy buffer.
gEntropy = [UInt8](repeating: 0, count: minEntropySize)
// Populate entropy buffer with random bytes.
let res = getRandom(&gEntropy)
if res != 0 {
print("There was an error attempting to create random entropy.")
return res
}
// Create default MKE encoder.
let encoder = try! MteMkeEnc()
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)
}
// Create default MKE 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)
}
while (true) {
var filePath: String
// Prompt for file path.
print("Please enter path to file (To end please type 'quit')")
filePath = readLine(strippingNewline: true) ?? ""
if filePath.isEmpty || filePath.lowercased() == "quit" {
break
}
// Find the base file name.
let baseFileName = NSURL(fileURLWithPath: filePath).lastPathComponent!
// Find the file extension.
let fileExtension = "." + (baseFileName as NSString).pathExtension
let inputFile: FileHandle
do {
inputFile = try FileHandle(forReadingFrom: URL.init(filePath: filePath))
} catch {
print ("Error reading file \(baseFileName)")
return -1
}
// Get the input file size.
do {
let attributes = try FileManager.default.attributesOfItem(atPath: filePath)
let fileLength = attributes[.size] as? Int ?? 0
if fileLength <= 0 {
print("Error opening file.")
return -1
}
} catch {
print("Error opening file.")
return -1
}
//=========================================////
//***** Begin MKE Encryption Process. *****////
//=========================================////
// Create encoded file name that includes the same extension.
let encodedFileName = "encoded" + fileExtension
// Delete any existing encoded file.
if FileManager.default.fileExists(atPath: encodedFileName) {
do {
try FileManager.default.removeItem(atPath: encodedFileName)
print("File \(encodedFileName) was deleted.")
} catch {
print ("Error deleting file \(encodedFileName)")
return -1
}
}
// Open the encoded file for writing.
FileManager.default.createFile(atPath: encodedFileName, contents: nil)
let encodedFile: FileHandle
do {
encodedFile = try FileHandle(forWritingTo: URL.init(filePath: encodedFileName))
} catch {
print ("Error creating file \(encodedFileName)")
return -1
}
// Start encrypt chunking session.
status = encoder.startEncrypt()
if status != mte_status_success {
print("Error starting encryption (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Go through until the end of the input file.
while (true) {
// Create buffer to hold encrypt chunk size.
let data = inputFile.readData(ofLength: encryptChunkSize)
var encryptChunkBuf = data.bytes
// Read a portion of the input file of size encryptChunkSize to the encryption buffer.
if (data.count == 0) {
break
}
// Encrypt the chunk buffer.
status = encoder.encryptChunk(&encryptChunkBuf)
if status != mte_status_success {
print("Error encrypting chunk (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Write the chunk buffer to the encoded file.
do {
try encodedFile.write(contentsOf: encryptChunkBuf)
} catch {
print ("Error writing to \(encodedFileName)")
return -1
}
}
// Close the input file.
do {
try inputFile.close()
} catch {
print ("Error closing \(baseFileName)")
}
// Finish the encryption with the encryption buffer.
let finishBuffer = encoder.finishEncrypt()
status = finishBuffer.status
if status != mte_status_success {
print("Error finishing encryption (\(MteBase.getStatusName(status))): " +
MteBase.getStatusDescription(status))
return Int32(status.rawValue)
}
// Write the result bytes from encrypt finish.
if finishBuffer.encoded.count > 0 {
do {
try encodedFile.write(contentsOf: finishBuffer.encoded)
} catch {
print ("Error writing to \(encodedFileName)")
return -1
}
}
// Close the encoded file.
do {
try encodedFile.close()
} catch {
print ("Error closing \(encodedFileName)")
}
print ("Successfully encoded file \(encodedFileName)")
#!/usr/bin/env python3
# Import relevant modules for the program.
from MteMkeEnc import MteMkeEnc
from MteStatus import MteStatus
from MteBase import MteBase
import os
import sys
def main():
# Create MKE Encoder.
mke_encoder = MteMkeEnc.fromdefault()
# Set identifier.
# These values should 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.
personal_str = "demo"
# Check how long entropy we need, set default all 0's.
# This should be treated like encryption keys - this is just an example.
entropy = "0"
entropy_min_bytes = MteBase.get_drbgs_entropy_min_bytes(mke_encoder.get_drbg())
while len(entropy) < entropy_min_bytes:
entropy += "0"
entropy = bytearray(entropy,'utf-8')
# Set mte values for the Encoder.
mke_encoder.set_entropy(entropy)
mke_encoder.set_nonce(0)
# Instantiate the MKE Encoder.
encoder_status = mke_encoder.instantiate(personal_str)
if encoder_status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(encoder_status),\
MteBase.get_status_description(encoder_status)
print("Encoder instantiate error ({0}): {1}".format(\
status,message),file=sys.stderr)
return encoder_status.value
# Initialize chunking session
encoder_status = mke_encoder.start_encrypt()
if encoder_status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(encoder_status),\
MteBase.get_status_description(encoder_status)
print("Failed to start encode chunk ({0}): {1}".format(\
status,message),file=sys.stderr)
return encoder_status.value
# Open input file and create and open output file.
# Deletes output file if it exists.
in_file = "src/plaintext.txt"
out_file = "src/encoded.txt"
dir_ = "src"
try:
if os.path.exists(out_file):
os.remove(out_file)
except:
print("Error while deleting file ", out_file)
finally:
if not os.path.exists(dir_):
os.makedirs(dir_)
out_file = open(out_file, "wb")
in_file = open(in_file,"rb")
# While bytes read from file exist,
# continue to read them to encode.
bytes_read = bytearray()
chunk_size = 1024 ## Set buffer size
while True:
in_bytes = in_file.read(chunk_size)
bytes_read+=in_bytes
## Break if no bytes are left
if len(in_bytes) == 0:
break
# Read and encrypt chunks of the input file.
for byte_chunk in range(0, len(bytes_read)-1,chunk_size):
data = bytearray(chunk_size)
# Append chunks and extra bytes to an array for encoding.
for bytes_ in range(len(data)):
if (byte_chunk + bytes_) < len(bytes_read):
data[bytes_] = bytes_read[byte_chunk + bytes_]
# Add all bytes to be encrypted.
data_bytes = bytes(data)
# Encode data in place - encoded data put back in buffer.
encoder_status = mke_encoder.encrypt_chunk(data_bytes)
if encoder_status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(encoder_status),\
MteBase.get_status_description(encoder_status)
print("Failed to encode chunk ({0}): {1}".format(\
status,message),file=sys.stderr)
return encoder_status.value
# Write bytes to output file.
if len(data_bytes) > 0:
out_file.write(data_bytes)
# Finish the chunking session.
encoded_chunk,encoder_status = mke_encoder.finish_encrypt()
if encoder_status != MteStatus.mte_status_success:
(status,message) = MteBase.get_status_name(encoder_status),\
MteBase.get_status_description(encoder_status)
print("Failed to finish encode session.\n({0}): {1}".format(status,message),\
file=sys.stderr)
return encoder_status.value
# Append final result to output file.
if len(encoded_chunk) > 0:
out_file.write(encoded_chunk)
# Close the IO stream files.
in_file.close()
out_file.close()
# Success.
return 0
package main
import (
"bufio"
"fmt"
"goSocket/mte"
"io"
"os"
"path/filepath"
"strings"
)
//-----------------------
// Application constants
//-----------------------
const (
bufferSize = 1024
defaultExtension = ".txt"
nonce = 1
identifier = "mySecretIdentifier"
companyName = ""
companyLicense = ""
)
func main() {
//------------------------------------
// Prompting message for file to copy
//------------------------------------
fmt.Print("Please enter path to file\n")
reader := bufio.NewReader(os.Stdin)
fPath, _ := reader.ReadString('\n')
//---------------------------
// take off carriage return
//---------------------------
fPath = strings.Replace(fPath, "\n", "", -1)
fPath = strings.Replace(fPath, "\r", "", -1)
//--------------------------------
// Check to make sure file exists
//--------------------------------
_, err := os.Stat(fPath)
if err != nil {
fmt.Printf("Path does not exist! %s", err)
return
}
encodedFileName := "encodedFile"
decodedFileName := "decodedFile"
//-----------------------
// Get the file extension
//-----------------------
extension := defaultExtension
fExt := filepath.Ext(fPath)
if len(fExt) > 0 {
extension = fExt
}
encodedFileName = encodedFileName + extension
decodedFileName = decodedFileName + extension
//---------------
// Open the file
//---------------
f, err := os.Open(fPath)
if err != nil {
fmt.Printf("error opening %s: %s", fPath, err)
return
}
defer f.Close()
//-----------------------------------------
// Check if file we are creating is there
// If present delete file
//-----------------------------------------
_, err = os.Stat(encodedFileName)
if err == nil {
e := os.Remove(encodedFileName)
if e != nil {
fmt.Printf("Error trying to delete file %s", encodedFileName)
}
}
//--------------------------------
// Create MKE Encoder and Decoder
//--------------------------------
encoder := mte.NewMkeEncDef()
defer encoder.Destroy()
//----------------------------------------------------
// defer the exit so all other defer calls are called
//----------------------------------------------------
retcode := 0
defer func() { os.Exit(retcode) }()
//------------------------------------
// Check version and output to screen
//------------------------------------
mteVersion := mte.GetVersion()
fmt.Printf("Using Mte Version %s\n", mteVersion)
//--------------------------------
// Check license -- use constants
// If no license can be blank
//--------------------------------
if !mte.InitLicense(companyName, companyLicense) {
fmt.Println("There was an error attempting to initialize the MTE License.")
return
}
//----------------------------------------------------------------------------
// check how long entropy we need, set default
// Providing Entropy in this fashion is insecure. This is for demonstration
// purposes only and should never be done in practice.
//----------------------------------------------------------------------------
entropyBytes := mte.GetDrbgsEntropyMinBytes(encoder.GetDrbg())
entropy := make([]byte, entropyBytes)
//---------------
// Fill with 0's
//---------------
for i := 0; i < entropyBytes; i++ {
entropy[i] = '0'
}
//--------------------
// Initialize encoder
//--------------------
encoder.SetEntropy(entropy)
encoder.SetNonceInt(nonce)
status := encoder.InstantiateStr(identifier)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encoder instantiate error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
retcode = int(status)
return
}
//---------------------
// Initialize Chunking
//---------------------
status = encoder.StartEncrypt()
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "MTE Encoder startDecrypt error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
retcode = int(status)
return
}
//-------------------------
// Create destination file
//-------------------------
destination, err := os.Create(encodedFileName)
if err != nil {
fmt.Printf("Error trying to create destination file %s, err: %s", encodedFileName, err)
}
defer destination.Close()
//-------------------------------------------------
// Iterate through file and write to new location
//-------------------------------------------------
for {
//------------------------------
// Create buffer for file parts
//------------------------------
buf := make([]byte, bufferSize)
amountRead, err := f.Read(buf)
if err != nil && err != io.EOF {
fmt.Printf("Error trying to read file %s, err: %s", fPath, err)
}
if amountRead == 0 {
//-----------------------------------------------
// Reached the end of the file, break out of loop
//-----------------------------------------------
break
}
//----------------------------------------------------------
// If the amount that was read is less than the buffer size,
// take a slice of the original buffer
//---------------------------------------------------------
if amountRead < bufferSize {
buf = buf[:amountRead]
}
//-----------------------------------------------------------
// Encrypt the chunk
//-----------------------------------------------------------
status = encoder.EncryptChunk(buf)
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encode error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
break
}
//----------------------------------------
// Write the encoded bytes to destination
//----------------------------------------
if _, err := destination.Write(buf); err != nil {
fmt.Printf("Error trying to write to file %s, err: %s", encodedFileName, err)
}
}
//-----------------------------
// End of the file reached
// Finish the chunking session
//-----------------------------
finishEncode, status := encoder.FinishEncrypt()
if status != mte.Status_mte_status_success {
fmt.Fprintf(os.Stderr, "Encode finish error (%v): %v\n",
mte.GetStatusName(status), mte.GetStatusDescription(status))
}
//-------------------------------------------------
// If there are bytes to write, write them to file
//-------------------------------------------------
if finishEncode != nil {
if _, err := destination.Write(finishEncode); err != nil {
fmt.Printf("Error trying to write to file %s, err: %s", encodedFileName, err)
}
}
destination.Close()
//---------------------------
// Print out success message
//---------------------------
fmt.Printf("Finished creating %s file\n", encodedFileName)
}