|
| 1 | +/* |
| 2 | + * ModSecurity, http://www.modsecurity.org/ |
| 3 | + * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) |
| 4 | + * |
| 5 | + * You may not use this file except in compliance with |
| 6 | + * the License. You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * If any of the files related to licensing are missing or if you have any |
| 11 | + * other questions related to licensing please contact Trustwave Holdings, Inc. |
| 12 | + * directly using the email address security@modsecurity.org. |
| 13 | + * |
| 14 | + */ |
| 15 | + |
| 16 | +#include <string> |
| 17 | +#include <fstream> |
| 18 | +#include <iostream> |
| 19 | + |
| 20 | +#include "utils/base64.h" |
| 21 | +#include "mbedtls/base64.h" |
| 22 | +#include <string.h> |
| 23 | + |
| 24 | +namespace modsecurity { |
| 25 | +namespace Utils { |
| 26 | + |
| 27 | + |
| 28 | +std::string Base64::encode(std::string& data) { |
| 29 | + size_t encoded_len = 0; |
| 30 | + unsigned char *d = NULL; |
| 31 | + std::string ret; |
| 32 | + |
| 33 | + mbedtls_base64_encode(NULL, 0, &encoded_len, |
| 34 | + reinterpret_cast<const unsigned char*>(data.c_str()), data.size()); |
| 35 | + |
| 36 | + d = reinterpret_cast<unsigned char*>(malloc(sizeof(char) * encoded_len)); |
| 37 | + if (d == NULL) { |
| 38 | + return data; |
| 39 | + } |
| 40 | + |
| 41 | + memset(d, '\0', encoded_len); |
| 42 | + |
| 43 | + mbedtls_base64_encode(d, encoded_len, &encoded_len, |
| 44 | + (unsigned char*) data.c_str(), data.size()); |
| 45 | + |
| 46 | + ret.assign(reinterpret_cast<const char*>(d)); |
| 47 | + free(d); |
| 48 | + |
| 49 | + |
| 50 | + return std::string(reinterpret_cast<const char*>(d)); |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +std::string Base64::decode(std::string& data) { |
| 55 | + size_t decoded_len = 0; |
| 56 | + unsigned char *d = NULL; |
| 57 | + std::string ret; |
| 58 | + |
| 59 | + mbedtls_base64_decode(NULL, 0, &decoded_len, |
| 60 | + reinterpret_cast<const unsigned char*>(data.c_str()), data.length()); |
| 61 | + |
| 62 | + d = reinterpret_cast<unsigned char*>(malloc(sizeof(char) * decoded_len)); |
| 63 | + if (d == NULL) { |
| 64 | + return data; |
| 65 | + } |
| 66 | + |
| 67 | + memset(d, '\0', decoded_len); |
| 68 | + |
| 69 | + mbedtls_base64_decode(d, decoded_len, &decoded_len, |
| 70 | + reinterpret_cast<const unsigned char*>(data.c_str()), data.length()); |
| 71 | + |
| 72 | + ret.assign(reinterpret_cast<const char*>(d)); |
| 73 | + free(d); |
| 74 | + |
| 75 | + return ret; |
| 76 | +} |
| 77 | + |
| 78 | + |
| 79 | +} // namespace Utils |
| 80 | +} // namespace modsecurity |
0 commit comments