summaryrefslogtreecommitdiff
path: root/src/CryptClass/HASHCrypt.cpp
blob: eed9cb5e003cde9f30481507cf4a43cfeafad294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
 * @file HASHCrypt.cpp
 * @brief HASHCrypt class definitions
 * @author manzerbredes
 * @date 8 Mars 2015
 *
 * Contain all definitions of HASHCrypt class.
 *
 */


//----- class -----
#include "HASHCrypt.hpp"



//Constructor
HASHCrypt::HASHCrypt(){
}

//Destructor
HASHCrypt::~HASHCrypt(){
}



//Contruct MD5 over 128 bits and put it into digest
void HASHCrypt::getMD5_128(std::string chain, byte* digest, int size){

    //Digest size controller
    this->checkDigestSize(CryptoPP::Weak1::MD5::DIGESTSIZE,size);

    //Create the MD5 on digest parameter
    CryptoPP::Weak1::MD5 hash;
    hash.CalculateDigest( digest, (byte*) chain.c_str(), chain.length() );

}



//Contruct SHA-256 and put it into digest
void HASHCrypt::getSHA_256(std::string chain, byte* digest, int size){

    //Digest size controller
    this->checkDigestSize(CryptoPP::SHA256::DIGESTSIZE,size);

    //Create the SHA-256 on digest parameter
    CryptoPP::SHA256 hash;
    hash.CalculateDigest( digest, (byte*) chain.c_str(), chain.length() );


}



//Compare 2 digest (same size)
bool HASHCrypt::compareDigest(byte* digest1, byte* digest2, int size){

    //Try is more safe
    try
    {
        //Compare the two digest
        for(int i=0; i<size; i++){
            //Return false if digest are different
            if(digest1[i] != digest2[i]){
                return false;
            }
        }
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception catched : " << e.what() << std::endl;
    }

    //Return true if digest are equals
    return true;
}



//Convert digest to string
std::string HASHCrypt::digestToString(byte* digest, int size){

    CryptoPP::HexEncoder encoder;
    std::string output;
    encoder.Attach( new CryptoPP::StringSink( output ) );
    encoder.Put( digest, size );
    encoder.MessageEnd();

    return output;
}



//Check the size of the digest
void HASHCrypt::checkDigestSize(int sizeRequired, int size){
    try{
        if(size !=sizeRequired){
            throw this->getInvalidDigestSizeError(sizeRequired, size);
        }

    }
    catch(std::string erreur){
        std::cerr << erreur <<std::endl;
        std::exit(EXIT_FAILURE);
    }
}



//Make the error
std::string HASHCrypt::getInvalidDigestSizeError(int sizeRequired, int size){
    std::ostringstream erreurStream;
    erreurStream << "Invalid digest size ! ("<< sizeRequired <<" bytes required and "<< size <<" given)";
    return erreurStream.str();
}