#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 << "\t\tExpected: " << ex_len << std::endl << "\t\tActual: " << 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 << "\t\tExpected: \""; std::cout.write((const char*)ex_msg, ex_len); std::cout << "\"" << std::endl << "\t\tActual: \""; 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

Get help from top-rated tutors in any subject.

Efficiently complete your homework and academic assignments by getting help from the experts at homeworkarchive.com