Get rid of the compiler warning about strict aliasing rule.
[bpdyndnsd] / src / util.cpp
CommitLineData
a78b44b5 1/** @file
a2f5be94 2 * @brief Util namespace implementation.
a78b44b5
BS
3 *
4 *
5 *
6 * @copyright Intra2net AG
7 * @license GPLv2
8*/
9
10#include "util.h"
11
a2f5be94 12#include <sstream>
a78b44b5 13#include <openssl/evp.h>
a78b44b5 14
a2f5be94 15using namespace std;
a78b44b5
BS
16
17/**
18 * Computes a MD5 Digest from the given string and returns the HEX representation
19 * @param data The string to compute the md5 for
20 * @return The computed md5 in hex
21 */
a2f5be94 22string Util::compute_md5_digest(string data) throw (invalid_argument)
a78b44b5
BS
23{
24 // compute an MD5 digest.
25
a78b44b5
BS
26 EVP_MD_CTX mdctx;
27 const EVP_MD *md;
28 unsigned char md_value[EVP_MAX_MD_SIZE];
a2f5be94 29 unsigned int md_len = 0;
a78b44b5 30
a2f5be94 31 // Add all digest algorithms to the internal table.
a78b44b5
BS
32 OpenSSL_add_all_digests();
33
a2f5be94 34 // Get the md5 digest algorithm from the internal table.
a78b44b5
BS
35 md = EVP_get_digestbyname("md5");
36
a2f5be94
BS
37 // Test if md is initialized.
38 if ( (md == NULL) || (EVP_MD_size(md) == 0) )
39 throw invalid_argument("NULL pointer: md");
40
41 // Initalize digest content mdctx.
a78b44b5 42 EVP_MD_CTX_init(&mdctx);
a2f5be94
BS
43
44 // Now we can call init_ex.
a78b44b5 45 EVP_DigestInit_ex(&mdctx, md, NULL);
a2f5be94
BS
46
47 // Test if data is empty.
48 if ( data.empty() )
49 throw invalid_argument("Passed data is empty");
50
51 // Hash the data. At this point data is not empty and &mdctx is initialized.
52 EVP_DigestUpdate(&mdctx, data.c_str(), data.size());
53
54 // Retrieve the digest value from &mdctx and place it in md_value.
a78b44b5 55 EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
a78b44b5 56
a2f5be94
BS
57 // Test if md_value is filled correctly and md_len is not zero.
58 if ( (md_len == 0) || (md_value == NULL) || (EVP_MD_CTX_size(&mdctx) == 0) )
59 throw invalid_argument("Retrieved invalid digest value");
60
61 // Internal cleanup of the digest content.
62 EVP_MD_CTX_cleanup(&mdctx);
63 EVP_cleanup();
a78b44b5 64
a2f5be94
BS
65 // Convert md5 digest C string to hex.
66 ostringstream oss_digest_md5_hex;
67 for(unsigned int i = 0; i < md_len; ++i)
a78b44b5 68 {
a2f5be94
BS
69 // We have to do a static cast to an decimal representation, cause otherwise ostringstream would interpret
70 // the stream as a character and output the character representation of the hex value.
71 oss_digest_md5_hex << hex << static_cast<unsigned short>(md_value[i]);
a78b44b5
BS
72 }
73
a2f5be94 74 return oss_digest_md5_hex.str();
a78b44b5 75}
52e7ca71
BS
76
77
78/**
79 * Get the status code from the given data.
80 * @param data The data containing the status code at front, limited by " ".
81 * @return The parsed status code.
82 */
83string Util::parse_status_code(string data)
84{
85 list<string> tokens;
86 ba::split(tokens,data,boost::is_any_of(" "));
87 return tokens.front();
88}