Advertisement
Guest User

Untitled

a guest
Sep 29th, 2016
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #pragma once
  2.  
  3. class OpenSSL_Base64
  4. {
  5. public:
  6.     static size_t calcDecodeLength(const char* b64input);
  7.     static size_t Base64Decode(char* b64message, unsigned char** buffer, size_t* length);
  8.     static char * Base64Encode(char *decoded_bytes, size_t decoded_length);
  9. };
  10.  
  11. #include "OpenSSL_Base64.h"
  12.  
  13. #include <string.h>
  14. #include <assert.h>
  15. #include <openssl/bio.h>
  16. #include <openssl/evp.h>
  17. #include <openssl/buffer.h>
  18.  
  19. size_t OpenSSL_Base64::calcDecodeLength(const char* b64input) { //Calculates the length of a decoded string
  20.     size_t len = strlen(b64input),
  21.         padding = 0;
  22.  
  23.     if (b64input[len - 1] == '=' && b64input[len - 2] == '=') //last two chars are =
  24.         padding = 2;
  25.     else if (b64input[len - 1] == '=') //last char is =
  26.         padding = 1;
  27.  
  28.     return (len * 3) / 4 - padding;
  29. }
  30.  
  31. size_t OpenSSL_Base64::Base64Decode(char* b64message, unsigned char** buffer, size_t* length) { //Decodes a base64 encoded string
  32.     BIO *bio, *b64;
  33.  
  34.     int decodeLen = calcDecodeLength(b64message);
  35.     *buffer = (unsigned char*)malloc(decodeLen + 1);
  36.     (*buffer)[decodeLen] = '\0';
  37.  
  38.     bio = BIO_new_mem_buf(b64message, -1);
  39.     b64 = BIO_new(BIO_f_base64());
  40.     bio = BIO_push(b64, bio);
  41.  
  42.     BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer
  43.     *length = BIO_read(bio, *buffer, strlen(b64message));
  44.     assert(*length == decodeLen); //length should equal decodeLen, else something went horribly wrong
  45.     BIO_free_all(bio);
  46.  
  47.     return (0); //success
  48. }
  49.  
  50. char * OpenSSL_Base64::Base64Encode(char *decoded_bytes, size_t decoded_length)
  51. {
  52.     int x;
  53.     BIO *bioMem, *b64;
  54.     BUF_MEM *bufPtr;
  55.     char *buff;
  56.  
  57.     b64 = BIO_new(BIO_f_base64());
  58.     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  59.     bioMem = BIO_new(BIO_s_mem());
  60.     b64 = BIO_push(b64, bioMem);
  61.  
  62.     BIO_write(b64, decoded_bytes, decoded_length);
  63.     x = BIO_flush(b64);
  64.     if (x < 1) {
  65.         BIO_free_all(b64);
  66.         return NULL;
  67.     }
  68.  
  69.     BIO_get_mem_ptr(b64, &bufPtr);
  70.  
  71.     buff = (char *)malloc(bufPtr->length + 1);
  72.     memcpy(buff, bufPtr->data, bufPtr->length);
  73.     buff[bufPtr->length] = 0;
  74.  
  75.     BIO_free_all(b64);
  76.     return buff;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement