Crypto class Take inspiration from the sha1demo.cpp file and implement the funct
ID: 3868449 • Letter: C
Question
Crypto class
Take inspiration from the sha1demo.cpp file and implement the functions listed
in the UML below.
Member Functions:
• sha1hash(string s) - the static function accepts a string of arbitrary length
and produces a hexadecimal string of 40 characters. It makes use of the
update and final functions of the SHA1 class to produce the required hash
value.
Crypto
+ sha1hash(s : string): string
+ sha1hash(v : int): string
+ strtohex(s : string, u : bool): string
+ random_string(l : int): string
• sha1hash(int v) - overloads the above-mentioned function by accepting an
integer value instead. You should convert this value into a string variable
first and call the above function to obtain the hash value of the input.
• strtohex(string s, bool u) - this static function converts an ASCII string
to its equivalent hexadecimal output. The boolean parameter u indicates
if the output should be uppercase or lowercase. u should have a default
value which makes the function produce an uppercase string by default.
• random_string(int l) - generates a random string of length l. The function
makes use of the C++ random function. Do not set the seed in this
function, but rather in your main() function.
Explanation / Answer
Crypto.cpp
#include <string>
#include <random>
#include "Crypto.h"
#include "sha1.hpp"
using namespace std;
string Crypto::sha1hash(string s)
{
SHA1 temp;
temp.update(s);
return temp.final();
}
string Crypto::sha1hash(int v)
{
return sha1hash(to_string(v));
}
string Crypto::strtohex(string s, bool u)
{
string CHARACTERS = "0123456789";
if (u)
{
CHARACTERS += "ABCDEF";
}
else
{
CHARACTERS += "abcdef";
}
int size = s.length();
string output;
output.reserve(2*size);
for (int a=0; a<size; a++)
{
const unsigned char c = s[a];
output.push_back(CHARACTERS[c>>4]);
output.push_back(CHARACTERS[c&15]);
}
return output;
}
string Crypto::random_string(int l)
{
string output="";
const char CHARACTERS[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const int SIZE = (sizeof(CHARACTERS)-1);
for (int a=0; a<l; a++)
{
output += CHARACTERS[rand()%SIZE];
}
return output;
}
Crypto.h
#ifndef CRYPTO_H
#define CRYPTO_H
#include <string>
using namespace std;
class Crypto
{
public:
static string sha1hash(string s);
static string sha1hash(int v);
static string strtohex(string s, bool u=true);
static string random_string(int l);
};
#endif
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.