SlideShare a Scribd company logo
1 of 23
#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include <functional>
#include <memory>
/**
* @enum Algorithm
*
* The purpose of this enumeration is to inform the
* static factory method which crypto transform should be
* used for when creating a crypto object.
*/
enum class Algorithm
{
eNONE,
eCAESAR,
eAES,
eRSA,
};
/**
* @class Crypto
*
* The purpose of this class is to serve as an abstract base class
for many
* cryptologic transforms.
*/
class Crypto
{
public:
/**
* @brief Constructor
*
* This function creates/initializes this oject.
* The callbacks are used by the underlying
* algorithm to pass back processed data to the using logic.
*
* NOTE: There is no correlation between the amount of data
passed into the algorithm
* and the amount returned from it. Likewise, there is no
required correlation between
* the number of times data is passed into the algorithm and
the number of times callbacks
* are called.
*
* @param encryptCallback Callback function for returning
encrypted data
* @param decryptCallback Callback function for returning
decrypted data
*/
Crypto(std::function<void(const uint8_t *data, uint32_t len)>
encryptCallback,
std::function<void(const uint8_t *data, uint32_t len)>
decryptCallback);
/**
* @brief Generate new crypto keys
*
* This function must be implemented by all derived classes.
* It signals the underlying algorithm that it should generate
* and store keys needed for that algorithm.
*/
virtual void genKeys() = 0;
/**
* @brief Get the keys and return them in a standardized form
*
* This function must be implemented by all derived classes.
* It will allocate memory, and then populate that memory
with
* keys in a way that can be generically stored/passed by using
* programs.
*
* @param pubKey Pointer to array of bytes containing public
key
* @param pubLen Lenght of the public key
* @param priKey Pointer to array of bytes containing private
key
* @param priLen Lenght of the private key
* @return Indication of valid keys present in response
*/
virtual bool getKeys(uint8_t **pubKey, uint32_t &pubLen,
uint8_t **priKey, uint32_t &priLen) = 0;
/**
* @brief Set the keys to be used in underlying transform
*
* This function must be implemented by all derived classes.
* It will pass a representation of needed keys to derived
* algorithms.
*
* @param pubKey Pointer to bytes containing public key
* @param pubLen Lenght of the public key
* @param priKey Pointer to bytes containing private key
* @param priLen Lenght of the private key
*/
virtual void setKeys(const uint8_t *pubKey, uint32_t pubLen,
const uint8_t *priKey, uint32_t priLen) = 0;
/**
* @brief Destroy keys and free resources
*
* This function must be implemented by all derived classes.
* It will inform the derived algorithm that it should "forget"
* any created keys and free resources associated with them.
* If keys are not present, it should have no action.
*/
virtual void destroyKeys() = 0;
/**
* @brief Encrypt raw data buffer (PT to CT)
*
* This function will pass a data buffer for encyrption
* to the underlying algorithm. There should be no restrictions
* on the lenght of data that is passed to the algorithm.
*
* @param data Buffer of data to be encrypted
* @param len Length of data buffer
* @return bool Success or failure (transform accepted data)
*/
virtual bool encrypt(const uint8_t *data, uint32_t len) = 0;
/**
* @brief Decrypt raw data buffer (CT to PT)
*
* This function will pass a data buffer for decyrption
* to the underlying algorithm. There should be no restrictions
* on the lenght of data that is passed to the algorithm.
*
* @param data Buffer of data to be decrypted
* @param len Length of data buffer
* @return bool Success or failure (transform accepted data)
*/
virtual bool decrypt(const uint8_t *data, uint32_t len) = 0;
/**
* @brief Create a Crypto object using the correct transform
*
* @param encryptCallback Callback function for returning
encrypted data
* @param decryptCallback Callback function for returning
decrypted data
* @param algorithm Enum indicationg which transform
should be used
* @return shared_ptr to newly constructed heap object
*/
static std::shared_ptr<Crypto>
cryptoFactory(std::function<void(const uint8_t *data, uint32_t
len)> encryptCallback,
std::function<void(const uint8_t
*data, uint32_t len)> decryptCallback,
Algorithm algorithm);
protected:
/** @brief Encrypt callback function */
std::function<void(const uint8_t *data, uint32_t len)>
m_encryptCallback;
/** @brief Decrypt callback function */
std::function<void(const uint8_t *data, uint32_t len)>
m_decryptCallback;
};
#endif /* CRYPTO_HPP */
#include "Crypto.hpp"
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
// Validates that data == ex_message
bool Verify(const uint8_t *ex_msg, int ex_len,
std::vector<uint8_t> data) {
if (ex_len != data.size()) {
std::cout
<< "tMessage length incorrect:" << std::endl
<< "ttExpected: " << ex_len << std::endl
<< "ttActual: " << data.size() << std::endl;
return false;
}
bool equal = true;
for (int i = 0; i < ex_len; ++i) {
if (data[i] != ex_msg[i]) {
equal = false;
break;
}
}
if(!equal) {
std::cout
<< "tMessage contents incorrect:" << std::endl
<< "ttExpected: "";
std::cout.write((const char*)ex_msg, ex_len);
std::cout
<< """ << std::endl
<< "ttActual: "";
std::cout.write((const char*)data.data(), data.size());
std::cout
<< """ << std::endl;
return false;
}
return true;
}
// A struct that compresses the passing of 3 counting variables
struct TestResults {
public:
int total = 0;
int passed = 0;
int failed = 0;
};
bool testBlockSize(uint8_t blockSize, const uint8_t *msg,
uint32_t len)
{
std::cout << +blockSize << " byte blocks" << std::endl;
std::shared_ptr<Crypto> testing;
std::vector<uint8_t> buffCiphertext;
std::vector<uint8_t> buffPlaintext;
auto encryptCallback =
[&buffCiphertext](const uint8_t *data, uint32_t len)
{
buffCiphertext.insert(buffCiphertext.end(), data,
data + len);
};
auto decryptCallback =
[&buffPlaintext](const uint8_t *data, uint32_t len)
{
buffPlaintext.insert(buffPlaintext.end(), data,
data + len);
};
testing = Crypto::cryptoFactory(encryptCallback,
decryptCallback, Algorithm::eAES);
if (testing == nullptr) {
std::cout << "tcryptoFactory returned nullptr!" <<
std::endl;
return false;
}
uint8_t *pubKey;
uint8_t *priKey;
uint32_t pubLen;
uint32_t priLen;
if (testing->getKeys(&pubKey, pubLen, &priKey, priLen))
{
std::cout << "tgetKeys returned something before
gen/set!" << std::endl;
return false;
}
if (testing->encrypt(nullptr, 0) || testing->decrypt(nullptr,
0)) {
std::cout << "encrypt or decrypt returned true before
gen/set!" << std::endl;
}
testing->genKeys();
if (!testing->getKeys(&pubKey, pubLen, &priKey,
priLen)) {
std::cout << "tgetKeys returned false!" << std::endl;
return false;
}
if (pubLen != 0) {
std::cout << "tpublic key was used!" << std::endl;
return false;
}
priKey[0] += 15;
uint8_t *testPri;
if (!testing->getKeys(&pubKey, pubLen, &testPri, priLen))
{
std::cout << "tgetKeys returned false! But only
sometimes?" << std::endl;
return false;
}
if (priKey[0] == testPri[0]) {
std::cout << "tPrivate member was exposed" <<
std::endl;
return false;
}
// Test the cryptoFactory
testing = Crypto::cryptoFactory(encryptCallback,
decryptCallback, Algorithm::eAES);
if (testing == nullptr) {
std::cout << "tcryptoFactory returned nullptr! But
only sometimes?" << std::endl;
return false;
}
testing->genKeys();
if (!testing->getKeys(&pubKey, pubLen, &priKey,
priLen)) {
std::cout << "tgetKeys returned false!" << std::endl;
return false;
}
for (int i = 0; i < len; i += blockSize) {
int block = (len - i > blockSize) ? blockSize : len - i;
if (!testing->encrypt(msg + i, block)) {
std::cout << "tencrypt(msg + " << i << ", " <<
block << ") "
"returned false (len: " << len << ")" <<
std::endl;
return false;
}
}
if (!testing->encrypt(nullptr, 0)) {
std::cout << "tReturned false on encrypt flush
command" << std::endl;
return false;
}
testing->destroyKeys();
testing = Crypto::cryptoFactory(encryptCallback,
decryptCallback, Algorithm::eAES);
if (testing == nullptr) {
std::cout << "tcryptoFactory returned nullptr! But
only sometimes?" << std::endl;
return false;
}
testing->setKeys(pubKey, pubLen, priKey, priLen);
uint8_t *cipher = buffCiphertext.data();
uint32_t cLen = buffCiphertext.size();
for (int i = 0; i < cLen; i += blockSize) {
int block = (cLen - i > blockSize) ? blockSize : cLen
- i;
if (!testing->decrypt(cipher + i, block)) {
std::cout << "tdecrypt(cipher + " << i << ", "
<< block << ") "
"returned false (cLen: " << cLen << ")" <<
std::endl;
return false;
}
}
if (!testing->decrypt(nullptr, 0)) {
std::cout << "tReturned false on decrypt flush
command" << std::endl;
return false;
}
testing->destroyKeys();
return Verify(msg, len, buffPlaintext);
}
// Calls the static Crypto factory method and tests both the
encryption and decryption processes
bool doTest(const char *test, const uint8_t *msg, uint32_t len)
{
std::cout << test << " - Start" << std::endl;
bool passed = true;
passed &= testBlockSize(1, msg, len);
passed &= testBlockSize(15, msg, len);
passed &= testBlockSize(16, msg, len);
passed &= testBlockSize(17, msg, len);
return passed;
}
void report(TestResults *results, const char *name, bool test) {
++(results->total);
if (test) {
++(results->passed);
std::cout << name << " - Passed" << std::endl;
}
else {
++(results->failed);
std::cout << name << " - Failed" << std::endl;
}
std::cout << std::endl;
}
int main() {
std::cout
<< "+--------------------------------------------------+"
<< std::endl
<< "| Programming Exercise 2: AES |"
<< std::endl
<< "| Unit Tests |" <<
std::endl
<< "+--------------------------------------------------+"
<< std::endl
<< std::endl;
// Counters across tests
TestResults results;
// The data to test
constexpr char *test1 = "Small message";
constexpr uint8_t m1[] = "Hello";
constexpr int m1Len = sizeof(m1) - 1;
report(&results, test1, doTest(test1, m1, m1Len));
// The data to test
constexpr char *test2 = "Complete Block";
constexpr uint8_t m2[] = "123456789012345";
constexpr int m2Len = sizeof(m2) - 1;
report(&results, test2, doTest(test2, m1, m2Len));
// The data to test
constexpr char *test3 = "Overfull Block";
constexpr uint8_t m3[] = "1234567890123456";
constexpr int m3Len = sizeof(m3) - 1;
report(&results, test3, doTest(test3, m1, m3Len));
// The data to test
constexpr char *test4 = "Large Message";
constexpr uint8_t m4[] = "Water... Earth... Fire... Air. "
"Long ago, the four nations lived together in
harmony. "
"Then everything changed when the Fire Nation
attacked. "
"Only the Avatar, master of all four elements, could
stop them. "
"But when the world needed him most, he vanished. "
"A hundred years passed and my brother and I
discovered the new Avatar, an airbender named Aang. "
"And although his airbending skills are great, he still
has a lot to learn before he's ready to save anyone. "
"But I believe Aang can save the world.";
constexpr int m4Len = sizeof(m4) - 1;
report(&results, test4, doTest(test4, m1, m4Len));
std::cout
<< "+--------------------------------------------------+"
<< std::endl
<< "| Summary: |" <<
std::endl
<< "| Tests Attempted: " << results.total << std::endl
<< "| Tests Passed: " << results.passed << std::endl
<< "| Tests Failed: " << results.failed << std::endl
<< "+--------------------------------------------------+"
<< std::endl;
return 0;
}
(AES Library Use)First Cryptographic Algorithm
The AES standard is a NIST standard. It is a symmetric cypher,
(i.e. the same key is used for encryption and decryption, see pg.
140 of the Cormen text). The NSA has approved the algorithms
use to protect U.S. government data classified at levels up to
and including TOP SECRET. When properly implemented, this
is a strong cypher capable of protecting your sensitive data.
More information can be found about the AES algorithm at:
https://en.wikipedia.org/wiki/Advanced_Encryption_Standard.
At this point, you need not understand the details of this
cryptographic transform. Rather, you are tasked with
integrating a well-known implementation of the AES algorithm
into the interface developed in previous assignment. For this
exercise you will use a crypto library called mcrypt. There are
many examples of how this code can be used found on-line.
The man pages for this library are also quite useful and can be
displayed with the command: man libmcrypt. Programming
Concepts
To correctly complete this programming task, the student must
possess an understanding of basic Linux system operation, IO
streams, inheritance, polymorphism, interfaces, abstract classes,
dynamic linking, functional objects/lambdas, and basic memory
management.
The challenging aspects of this integration are not
cryptographic (We’ll save that for the RSA PEX). Rather, most
of the complexity revolves around the streaming of data into
and out of the algorithm, supporting data that must be in
complete block sizes, and linking against the mcrypt dynamic
library.System Requirements
This design is intended to be quite flexible not only in the
transforms that are supported, but in the ways that the
transforms are used. It would be equally easy to use this code
to transfer data over a socket as it would be to read/write files
on a disk. The system is designed to support encryption,
decryption, and key management in a single simple library.
Note that these requirements are identical to the last PEX; this
is by design.
A typical use of this library could be as follows (secure data file
storage):
1. The user instantiates a Crypto object. During this
instantiation, the user is required to provide callbacks. The
purpose of these callbacks is to provide instruction to the
library on what do with data that has been successfully
transformed, (encrypted or decrypted).
2. The static factory function parameters dictate what
cryptographic transform shall be used.
3. The library will be used to generate keys for this action
4. The keys may be stored for use on a later execution, (e.g. to
decrypt the file)
5. The file to be encrypted/secured is opened by the user and
read into a memory buffer.
6. The contents of the memory buffer are then written to the
encryption engine.
7. The encryption engine will transform the data appropriately.
It may then do any of the following:
a. Call the callback in which the user program can write the
obfuscated data to disk.
b. Call the associated callback with only a portion of the
encrypted data, (some encryption algorithms need to handle data
in specific block sizes.)
c. Make no callbacks and buffer the data until a certain amount
has been collected
8. Once all of the data has been written, one additional write
shall be made to the engine where the length of the data is
specified as zero. This will instruct the encryption engine to
flush all buffers completely. Note that some algorithms may
need padding to fill a complete block.
9. The entire process is executed in reverse to decrypt the file
when needed.
Other requirements:
1. The system shall utilize the interface header file provided
(Crypto.hpp) verbatim. This will allow the instructor to execute
test/grading code using your implementation. This header file
is located at…... It is very well documented in-line and
students are encouraged to study it closely.
2. The student may construct the implementation of the
provided header in any way they choose.
3. Additional classes/files may be used as the student sees fit.
4. Students should consider building a new class derived from
the provided interface for each new transform supported.
5. The system shall support transforms in which the size of the
plain text and cipher text streams are not the same.
6. The system shall accept all data provided to an
encrypt/decrypt function call.
7. The system may buffer and return encrypted/decrypted data
via any number of callback executions.
8. The system may execute callbacks from the encrypt/decrypt
function, (i.e. it is possible to see a callback before the
encrypt/decrypt call completes)
9. The user callback shall consume all data provided to it before
returning to the caller.
10. The system shall support shifting binary data, not just
alpha-numeric strings
Grading Rubric
(PEX2)
Requirement / Criteria
Available Points
Student’s Score
Compiles and links correctly; uses provided interface verbatim.
Links against the libmcrypt shared library.
10
Static factory function creates correct object
10
Key management operates correctly
10
Writes smaller than block size are correctly encrypted
20
Writes larger than block size are correctly encrypted
20
Byte streams not evenly divisible by block size are correct
20
Encrypted/decrypted complex file checked with MD5 sum
10
Total
100

More Related Content

Similar to #ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx

Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
C++ Secure Programming
C++ Secure ProgrammingC++ Secure Programming
C++ Secure ProgrammingMarian Marinov
 
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015ThierryAbalea
 
The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202Mahmoud Samir Fayed
 
A Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCatA Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCatAndrey Karpov
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialJeff Smith
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialJeff Smith
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres OpenBruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres OpenPostgresOpen
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitAndrey Karpov
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxhendriciraida
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
 

Similar to #ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx (20)

C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
C++ Secure Programming
C++ Secure ProgrammingC++ Secure Programming
C++ Secure Programming
 
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
 
The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202
 
A Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCatA Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCat
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres OpenBruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGit
 
Ac2
Ac2Ac2
Ac2
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 

More from gertrudebellgrove

-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docxgertrudebellgrove
 
-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docx-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docxgertrudebellgrove
 
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docxgertrudebellgrove
 
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docxgertrudebellgrove
 
- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docx- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docxgertrudebellgrove
 
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docxgertrudebellgrove
 
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docxgertrudebellgrove
 
-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docx-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docxgertrudebellgrove
 
- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docx- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docxgertrudebellgrove
 
- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docx- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docxgertrudebellgrove
 
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docxgertrudebellgrove
 
- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docx- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docxgertrudebellgrove
 
- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docx- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docxgertrudebellgrove
 
- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docx- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docxgertrudebellgrove
 
- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docxgertrudebellgrove
 
- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docx- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docxgertrudebellgrove
 
) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docx) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docxgertrudebellgrove
 
(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docx(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docxgertrudebellgrove
 
( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docx( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docxgertrudebellgrove
 
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docxgertrudebellgrove
 

More from gertrudebellgrove (20)

-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx-I am unable to accept emailed exams or late exams. No exception.docx
-I am unable to accept emailed exams or late exams. No exception.docx
 
-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docx-delineate characteristics, prevalence of  exceptionality-evalua.docx
-delineate characteristics, prevalence of  exceptionality-evalua.docx
 
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
-1st play name is READY STEADY YETI GO-2nd play name is INTO .docx
 
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
-6th-Edition-Template-without-Abstract.dotWhat are Heuristics .docx
 
- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docx- write one 5-7 page paper about All forms of Euthanasia are moral..docx
- write one 5-7 page paper about All forms of Euthanasia are moral..docx
 
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
-1st Play name is BERNHARDTHAMLET -2nd Play name is READY ST.docx
 
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
. 1. Rutter and Sroufe identified _____________ as one of three impo.docx
 
-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docx-Prior to the Civil War, how did the (dominant) discourse over the U.docx
-Prior to the Civil War, how did the (dominant) discourse over the U.docx
 
- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docx- Using the definition Awareness of sensation and perception to ex.docx
- Using the definition Awareness of sensation and perception to ex.docx
 
- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docx- should include an introduction to the environmental issue and its .docx
- should include an introduction to the environmental issue and its .docx
 
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
- FIRST EXAM SPRING 20201. Describe how the view of operations.docx
 
- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docx- Considering the concepts, examples and learning from the v.docx
- Considering the concepts, examples and learning from the v.docx
 
- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docx- Discuss why a computer incident response team (CIRT) plan is neede.docx
- Discuss why a computer incident response team (CIRT) plan is neede.docx
 
- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docx- Discuss why a computer incident response team (CIRT) plan is n.docx
- Discuss why a computer incident response team (CIRT) plan is n.docx
 
- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx- 2 -Section CPlease write your essay in the blue book.docx
- 2 -Section CPlease write your essay in the blue book.docx
 
- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docx- Confidence intervals for a population mean, standard deviation kno.docx
- Confidence intervals for a population mean, standard deviation kno.docx
 
) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docx) Create a new thread. As indicated above, select  two tools describ.docx
) Create a new thread. As indicated above, select  two tools describ.docx
 
(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docx(Write 3 to 4 sentences per question)  1. Describe one way y.docx
(Write 3 to 4 sentences per question)  1. Describe one way y.docx
 
( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docx( America and Venezuela) this is a ppt. groups assignment. Below is .docx
( America and Venezuela) this is a ppt. groups assignment. Below is .docx
 
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
++ 2 PAGES++Topic Make a bill to legalize all felon has the rig.docx
 

Recently uploaded

21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonhttgc7rh9c
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 

Recently uploaded (20)

VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 

#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx

  • 1. #ifndef CRYPTO_HPP #define CRYPTO_HPP #include <functional> #include <memory> /** * @enum Algorithm * * The purpose of this enumeration is to inform the * static factory method which crypto transform should be * used for when creating a crypto object. */ enum class Algorithm { eNONE, eCAESAR, eAES, eRSA, }; /** * @class Crypto * * The purpose of this class is to serve as an abstract base class for many * cryptologic transforms. */ class Crypto { public: /** * @brief Constructor *
  • 2. * This function creates/initializes this oject. * The callbacks are used by the underlying * algorithm to pass back processed data to the using logic. * * NOTE: There is no correlation between the amount of data passed into the algorithm * and the amount returned from it. Likewise, there is no required correlation between * the number of times data is passed into the algorithm and the number of times callbacks * are called. * * @param encryptCallback Callback function for returning encrypted data * @param decryptCallback Callback function for returning decrypted data */ Crypto(std::function<void(const uint8_t *data, uint32_t len)> encryptCallback, std::function<void(const uint8_t *data, uint32_t len)> decryptCallback); /** * @brief Generate new crypto keys * * This function must be implemented by all derived classes. * It signals the underlying algorithm that it should generate * and store keys needed for that algorithm. */ virtual void genKeys() = 0; /** * @brief Get the keys and return them in a standardized form * * This function must be implemented by all derived classes. * It will allocate memory, and then populate that memory with * keys in a way that can be generically stored/passed by using
  • 3. * programs. * * @param pubKey Pointer to array of bytes containing public key * @param pubLen Lenght of the public key * @param priKey Pointer to array of bytes containing private key * @param priLen Lenght of the private key * @return Indication of valid keys present in response */ virtual bool getKeys(uint8_t **pubKey, uint32_t &pubLen, uint8_t **priKey, uint32_t &priLen) = 0; /** * @brief Set the keys to be used in underlying transform * * This function must be implemented by all derived classes. * It will pass a representation of needed keys to derived * algorithms. * * @param pubKey Pointer to bytes containing public key * @param pubLen Lenght of the public key * @param priKey Pointer to bytes containing private key * @param priLen Lenght of the private key */ virtual void setKeys(const uint8_t *pubKey, uint32_t pubLen, const uint8_t *priKey, uint32_t priLen) = 0; /** * @brief Destroy keys and free resources * * This function must be implemented by all derived classes. * It will inform the derived algorithm that it should "forget" * any created keys and free resources associated with them. * If keys are not present, it should have no action. */ virtual void destroyKeys() = 0; /**
  • 4. * @brief Encrypt raw data buffer (PT to CT) * * This function will pass a data buffer for encyrption * to the underlying algorithm. There should be no restrictions * on the lenght of data that is passed to the algorithm. * * @param data Buffer of data to be encrypted * @param len Length of data buffer * @return bool Success or failure (transform accepted data) */ virtual bool encrypt(const uint8_t *data, uint32_t len) = 0; /** * @brief Decrypt raw data buffer (CT to PT) * * This function will pass a data buffer for decyrption * to the underlying algorithm. There should be no restrictions * on the lenght of data that is passed to the algorithm. * * @param data Buffer of data to be decrypted * @param len Length of data buffer * @return bool Success or failure (transform accepted data) */ virtual bool decrypt(const uint8_t *data, uint32_t len) = 0; /** * @brief Create a Crypto object using the correct transform * * @param encryptCallback Callback function for returning encrypted data * @param decryptCallback Callback function for returning decrypted data * @param algorithm Enum indicationg which transform should be used * @return shared_ptr to newly constructed heap object */ static std::shared_ptr<Crypto> cryptoFactory(std::function<void(const uint8_t *data, uint32_t
  • 5. len)> encryptCallback, std::function<void(const uint8_t *data, uint32_t len)> decryptCallback, Algorithm algorithm); protected: /** @brief Encrypt callback function */ std::function<void(const uint8_t *data, uint32_t len)> m_encryptCallback; /** @brief Decrypt callback function */ std::function<void(const uint8_t *data, uint32_t len)> m_decryptCallback; }; #endif /* CRYPTO_HPP */ #include "Crypto.hpp" #include <iostream> #include <algorithm> #include <iterator> #include <vector> // Validates that data == ex_message bool Verify(const uint8_t *ex_msg, int ex_len, std::vector<uint8_t> data) { if (ex_len != data.size()) { std::cout
  • 6. << "tMessage length incorrect:" << std::endl << "ttExpected: " << ex_len << std::endl << "ttActual: " << data.size() << std::endl; return false; } bool equal = true; for (int i = 0; i < ex_len; ++i) { if (data[i] != ex_msg[i]) { equal = false; break; } } if(!equal) { std::cout << "tMessage contents incorrect:" << std::endl << "ttExpected: "";
  • 7. std::cout.write((const char*)ex_msg, ex_len); std::cout << """ << std::endl << "ttActual: ""; std::cout.write((const char*)data.data(), data.size()); std::cout << """ << std::endl; return false; } return true; } // A struct that compresses the passing of 3 counting variables struct TestResults { public: int total = 0; int passed = 0;
  • 8. int failed = 0; }; bool testBlockSize(uint8_t blockSize, const uint8_t *msg, uint32_t len) { std::cout << +blockSize << " byte blocks" << std::endl; std::shared_ptr<Crypto> testing; std::vector<uint8_t> buffCiphertext; std::vector<uint8_t> buffPlaintext; auto encryptCallback = [&buffCiphertext](const uint8_t *data, uint32_t len) { buffCiphertext.insert(buffCiphertext.end(), data, data + len); };
  • 9. auto decryptCallback = [&buffPlaintext](const uint8_t *data, uint32_t len) { buffPlaintext.insert(buffPlaintext.end(), data, data + len); }; testing = Crypto::cryptoFactory(encryptCallback, decryptCallback, Algorithm::eAES); if (testing == nullptr) { std::cout << "tcryptoFactory returned nullptr!" << std::endl; return false; } uint8_t *pubKey; uint8_t *priKey; uint32_t pubLen; uint32_t priLen;
  • 10. if (testing->getKeys(&pubKey, pubLen, &priKey, priLen)) { std::cout << "tgetKeys returned something before gen/set!" << std::endl; return false; } if (testing->encrypt(nullptr, 0) || testing->decrypt(nullptr, 0)) { std::cout << "encrypt or decrypt returned true before gen/set!" << std::endl; } testing->genKeys(); if (!testing->getKeys(&pubKey, pubLen, &priKey, priLen)) { std::cout << "tgetKeys returned false!" << std::endl; return false; }
  • 11. if (pubLen != 0) { std::cout << "tpublic key was used!" << std::endl; return false; } priKey[0] += 15; uint8_t *testPri; if (!testing->getKeys(&pubKey, pubLen, &testPri, priLen)) { std::cout << "tgetKeys returned false! But only sometimes?" << std::endl; return false; } if (priKey[0] == testPri[0]) { std::cout << "tPrivate member was exposed" << std::endl; return false; }
  • 12. // Test the cryptoFactory testing = Crypto::cryptoFactory(encryptCallback, decryptCallback, Algorithm::eAES); if (testing == nullptr) { std::cout << "tcryptoFactory returned nullptr! But only sometimes?" << std::endl; return false; } testing->genKeys(); if (!testing->getKeys(&pubKey, pubLen, &priKey, priLen)) { std::cout << "tgetKeys returned false!" << std::endl; return false; } for (int i = 0; i < len; i += blockSize) { int block = (len - i > blockSize) ? blockSize : len - i; if (!testing->encrypt(msg + i, block)) {
  • 13. std::cout << "tencrypt(msg + " << i << ", " << block << ") " "returned false (len: " << len << ")" << std::endl; return false; } } if (!testing->encrypt(nullptr, 0)) { std::cout << "tReturned false on encrypt flush command" << std::endl; return false; } testing->destroyKeys(); testing = Crypto::cryptoFactory(encryptCallback, decryptCallback, Algorithm::eAES); if (testing == nullptr) { std::cout << "tcryptoFactory returned nullptr! But only sometimes?" << std::endl; return false;
  • 14. } testing->setKeys(pubKey, pubLen, priKey, priLen); uint8_t *cipher = buffCiphertext.data(); uint32_t cLen = buffCiphertext.size(); for (int i = 0; i < cLen; i += blockSize) { int block = (cLen - i > blockSize) ? blockSize : cLen - i; if (!testing->decrypt(cipher + i, block)) { std::cout << "tdecrypt(cipher + " << i << ", " << block << ") " "returned false (cLen: " << cLen << ")" << std::endl; return false; } } if (!testing->decrypt(nullptr, 0)) { std::cout << "tReturned false on decrypt flush command" << std::endl;
  • 15. return false; } testing->destroyKeys(); return Verify(msg, len, buffPlaintext); } // Calls the static Crypto factory method and tests both the encryption and decryption processes bool doTest(const char *test, const uint8_t *msg, uint32_t len) { std::cout << test << " - Start" << std::endl; bool passed = true; passed &= testBlockSize(1, msg, len); passed &= testBlockSize(15, msg, len); passed &= testBlockSize(16, msg, len); passed &= testBlockSize(17, msg, len);
  • 16. return passed; } void report(TestResults *results, const char *name, bool test) { ++(results->total); if (test) { ++(results->passed); std::cout << name << " - Passed" << std::endl; } else { ++(results->failed); std::cout << name << " - Failed" << std::endl; } std::cout << std::endl; } int main() { std::cout
  • 17. << "+--------------------------------------------------+" << std::endl << "| Programming Exercise 2: AES |" << std::endl << "| Unit Tests |" << std::endl << "+--------------------------------------------------+" << std::endl << std::endl; // Counters across tests TestResults results; // The data to test constexpr char *test1 = "Small message"; constexpr uint8_t m1[] = "Hello"; constexpr int m1Len = sizeof(m1) - 1; report(&results, test1, doTest(test1, m1, m1Len)); // The data to test
  • 18. constexpr char *test2 = "Complete Block"; constexpr uint8_t m2[] = "123456789012345"; constexpr int m2Len = sizeof(m2) - 1; report(&results, test2, doTest(test2, m1, m2Len)); // The data to test constexpr char *test3 = "Overfull Block"; constexpr uint8_t m3[] = "1234567890123456"; constexpr int m3Len = sizeof(m3) - 1; report(&results, test3, doTest(test3, m1, m3Len)); // The data to test constexpr char *test4 = "Large Message"; constexpr uint8_t m4[] = "Water... Earth... Fire... Air. " "Long ago, the four nations lived together in harmony. " "Then everything changed when the Fire Nation attacked. " "Only the Avatar, master of all four elements, could
  • 19. stop them. " "But when the world needed him most, he vanished. " "A hundred years passed and my brother and I discovered the new Avatar, an airbender named Aang. " "And although his airbending skills are great, he still has a lot to learn before he's ready to save anyone. " "But I believe Aang can save the world."; constexpr int m4Len = sizeof(m4) - 1; report(&results, test4, doTest(test4, m1, m4Len)); std::cout << "+--------------------------------------------------+" << std::endl << "| Summary: |" << std::endl << "| Tests Attempted: " << results.total << std::endl << "| Tests Passed: " << results.passed << std::endl << "| Tests Failed: " << results.failed << std::endl << "+--------------------------------------------------+" << std::endl;
  • 20. return 0; } (AES Library Use)First Cryptographic Algorithm The AES standard is a NIST standard. It is a symmetric cypher, (i.e. the same key is used for encryption and decryption, see pg. 140 of the Cormen text). The NSA has approved the algorithms use to protect U.S. government data classified at levels up to and including TOP SECRET. When properly implemented, this is a strong cypher capable of protecting your sensitive data. More information can be found about the AES algorithm at: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard. At this point, you need not understand the details of this cryptographic transform. Rather, you are tasked with integrating a well-known implementation of the AES algorithm into the interface developed in previous assignment. For this exercise you will use a crypto library called mcrypt. There are many examples of how this code can be used found on-line. The man pages for this library are also quite useful and can be displayed with the command: man libmcrypt. Programming Concepts To correctly complete this programming task, the student must possess an understanding of basic Linux system operation, IO streams, inheritance, polymorphism, interfaces, abstract classes, dynamic linking, functional objects/lambdas, and basic memory management. The challenging aspects of this integration are not cryptographic (We’ll save that for the RSA PEX). Rather, most of the complexity revolves around the streaming of data into and out of the algorithm, supporting data that must be in complete block sizes, and linking against the mcrypt dynamic library.System Requirements This design is intended to be quite flexible not only in the
  • 21. transforms that are supported, but in the ways that the transforms are used. It would be equally easy to use this code to transfer data over a socket as it would be to read/write files on a disk. The system is designed to support encryption, decryption, and key management in a single simple library. Note that these requirements are identical to the last PEX; this is by design. A typical use of this library could be as follows (secure data file storage): 1. The user instantiates a Crypto object. During this instantiation, the user is required to provide callbacks. The purpose of these callbacks is to provide instruction to the library on what do with data that has been successfully transformed, (encrypted or decrypted). 2. The static factory function parameters dictate what cryptographic transform shall be used. 3. The library will be used to generate keys for this action 4. The keys may be stored for use on a later execution, (e.g. to decrypt the file) 5. The file to be encrypted/secured is opened by the user and read into a memory buffer. 6. The contents of the memory buffer are then written to the encryption engine. 7. The encryption engine will transform the data appropriately. It may then do any of the following: a. Call the callback in which the user program can write the obfuscated data to disk. b. Call the associated callback with only a portion of the encrypted data, (some encryption algorithms need to handle data in specific block sizes.) c. Make no callbacks and buffer the data until a certain amount has been collected 8. Once all of the data has been written, one additional write shall be made to the engine where the length of the data is specified as zero. This will instruct the encryption engine to flush all buffers completely. Note that some algorithms may
  • 22. need padding to fill a complete block. 9. The entire process is executed in reverse to decrypt the file when needed. Other requirements: 1. The system shall utilize the interface header file provided (Crypto.hpp) verbatim. This will allow the instructor to execute test/grading code using your implementation. This header file is located at…... It is very well documented in-line and students are encouraged to study it closely. 2. The student may construct the implementation of the provided header in any way they choose. 3. Additional classes/files may be used as the student sees fit. 4. Students should consider building a new class derived from the provided interface for each new transform supported. 5. The system shall support transforms in which the size of the plain text and cipher text streams are not the same. 6. The system shall accept all data provided to an encrypt/decrypt function call. 7. The system may buffer and return encrypted/decrypted data via any number of callback executions. 8. The system may execute callbacks from the encrypt/decrypt function, (i.e. it is possible to see a callback before the encrypt/decrypt call completes) 9. The user callback shall consume all data provided to it before returning to the caller. 10. The system shall support shifting binary data, not just alpha-numeric strings Grading Rubric (PEX2) Requirement / Criteria Available Points Student’s Score Compiles and links correctly; uses provided interface verbatim. Links against the libmcrypt shared library. 10
  • 23. Static factory function creates correct object 10 Key management operates correctly 10 Writes smaller than block size are correctly encrypted 20 Writes larger than block size are correctly encrypted 20 Byte streams not evenly divisible by block size are correct 20 Encrypted/decrypted complex file checked with MD5 sum 10 Total 100