SlideShare a Scribd company logo
#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

PDF
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
PDF
Toonz code leaves much to be desired
PPTX
RTTI and Namespaces.pptx ppt of c++ programming language
DOCX
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
PPT
Python Objects
PPT
Microkernel Development
PDF
Tutorial - 16 : How to pass parameters from one script to another by CallScri...
PPT
Whats new in_csharp4
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
Toonz code leaves much to be desired
RTTI and Namespaces.pptx ppt of c++ programming language
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
Python Objects
Microkernel Development
Tutorial - 16 : How to pass parameters from one script to another by CallScri...
Whats new in_csharp4

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

PDF
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
PDF
Zn task - defcon russia 20
DOCX
C# labprograms
DOCX
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
PDF
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PDF
[232]TensorRT를 활용한 딥러닝 Inference 최적화
PDF
[232] TensorRT를 활용한 딥러닝 Inference 최적화
PPT
2012 JDays Bad Tests Good Tests
ODP
C++ Secure Programming
PDF
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
PDF
The Ring programming language version 1.8 book - Part 91 of 202
PDF
A Spin-off: CryEngine 3 SDK Checked with CppCat
PDF
Programming with ZooKeeper - A basic tutorial
PDF
Programming with ZooKeeper - A basic tutorial
PPT
Lo Mejor Del Pdc2008 El Futrode C#
PDF
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
PDF
33rd Degree 2013, Bad Tests, Good Tests
PDF
The CppCat Analyzer Checks TortoiseGit
DOCX
I need you to modify and change the loop in this code without changing.docx
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
Zn task - defcon russia 20
C# labprograms
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화
2012 JDays Bad Tests Good Tests
C++ Secure Programming
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
The Ring programming language version 1.8 book - Part 91 of 202
A Spin-off: CryEngine 3 SDK Checked with CppCat
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Lo Mejor Del Pdc2008 El Futrode C#
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
33rd Degree 2013, Bad Tests, Good Tests
The CppCat Analyzer Checks TortoiseGit
I need you to modify and change the loop in this code without changing.docx
Ad

More from gertrudebellgrove (20)

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

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Lesson notes of climatology university.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Structure & Organelles in detailed.
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
master seminar digital applications in india
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Anesthesia in Laparoscopic Surgery in India
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
01-Introduction-to-Information-Management.pdf
VCE English Exam - Section C Student Revision Booklet
Cell Structure & Organelles in detailed.
Sports Quiz easy sports quiz sports quiz
master seminar digital applications in india
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
2.FourierTransform-ShortQuestionswithAnswers.pdf
RMMM.pdf make it easy to upload and study
Abdominal Access Techniques with Prof. Dr. R K Mishra
GDM (1) (1).pptx small presentation for students
Microbial diseases, their pathogenesis and prophylaxis
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Anesthesia in Laparoscopic Surgery in India

#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