Menu

SHA Example

saeed atalla

CryptoEngine provide SHA2 and SHA3 classes for hashing, in this example we will use
"Strategy Pattern" to explain how we can use them:

//Class HashContext takes a reference of CELIB::HashCrypto interface,
//then we can use it with any other inherited class such as SHA256 and others.

class HashContext{
public:
    HashContext(CELIB::HashCrypto& hashInterface)
        :m_hashInterface(hashInterface){}

    QByteArray hashString(const QByteArray& plain, bool * isOk){
        return m_hashInterface.hash(plain, isOk);
    }

    //Another hash functions...

private:
    CELIB::HashCrypto& m_hashInterface;
};

int main(int argc, char *argv[])
{
    QByteArray plain("abc"), result;
    std::cout << "\nplain:  " << plain.data() << std::endl;
    //SHA2-224:
    CELIB::SHA224 sha224;
    HashContext hc1(sha224);
    result = hc1.hashString(plain, 0);
    std::cout << "\nSHA224-Hex: " << result.toHex().toUpper().data() << std::endl;
    //SHA2-256:
    CELIB::SHA256 sha256;
    HashContext hc2(sha256);
    result = hc2.hashString(plain, 0);
    std::cout << "\nSHA256-Hex: " << result.toHex().toUpper().data() << std::endl;
    //SHA2-384:
    CELIB::SHA384 sha384;
    HashContext hc3(sha384);
    result = hc3.hashString(plain, 0);
    std::cout << "\nSHA384-Hex: " << result.toHex().toUpper().data() << std::endl;
    //SHA2-512:
    CELIB::SHA512 sha512;
    HashContext hc4(sha512);
    result = hc4.hashString(plain, 0);
    std::cout << "\nSHA512-Hex: " << result.toHex().toUpper().data() << std::endl;
    //SHA3-256:
    CELIB::SHA3_256 sha3_256;
    HashContext hc5(sha3_256);
    result = hc5.hashString(plain, 0);
    std::cout << "\nSHA3_256-Hex: " << result.toHex().toUpper().data() << std::endl;
    //etc...

    return 0;
}

output:

/*
plain:  abc

SHA224-Hex: 23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7

SHA256-Hex: BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

SHA384-Hex: CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7

SHA512-Hex: DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F

SHA3_256-Hex: 4E03657AEA45A94FC7D47BA826C8D667C0D1E6E33A64A036EC44F58FA12D6C45
*/

Static Functions:

For more flexibility, we can use static hashing functions without creating any objects:

result = CELIB::SHA256::hash(plain, 0, 0);
std::cout << "\nStatic-SHA256-Hex: " << result.toHex().toUpper().data() << std::endl;

output:

Static-SHA256-Hex: BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

Note that you can hash files with same both ways, and you can use compare(...) functions to check
if the hash string for this text/file is correct.

[Error Handling]


Related

Wiki: Home
Wiki: Error Handling

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.