Skip to content

Commit

Permalink
Adding base64
Browse files Browse the repository at this point in the history
  • Loading branch information
pat committed Oct 14, 2015
1 parent 387a622 commit 9a87fa4
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 130 deletions.
46 changes: 46 additions & 0 deletions utils/Base64.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include "Base64.h"
#include <stdio.h>

#if __GNUC__ >= 4 and __GNUC_MINOR__ >= 3
#define MOVEBE(x) __builtin_bswap32(x);
#else
#define MOVEBE(x) ((x&0xff000000)>>24)|((x&0xff)<<24)|((x&0xff0000)>>8)|((x&0xff00)<<8)
#endif

char* Base64::digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::string Base64::encode(const char* data, unsigned int size)
{
std::string str;
unsigned int tmp;
unsigned int i = 0;
while (i<size)
{
tmp = MOVEBE(*((unsigned int*)&data[i]));
if (size-i == 1)
{
str += digits[(tmp>>26)&0x3F];
str += digits[(tmp>>20)&0x3F];
str += "==";
i++;
}
else if (size-i == 2)
{
str += digits[(tmp>>26)&0x3F];
str += digits[(tmp>>20)&0x3F];
str += digits[(tmp>>14)&0x3F];
str += "=";
i+=2;
}
else
{
str += digits[(tmp>>26)&0x3F];
str += digits[(tmp>>20)&0x3F];
str += digits[(tmp>>14)&0x3F];
str += digits[(tmp>>8)&0x3F];
i+=3;
}
}

return str;
}
10 changes: 10 additions & 0 deletions utils/Base64.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#pragma once
#include <string>

class Base64
{
private:
static char* digits;
public:
static std::string encode(const char* data, unsigned int size);
};
4 changes: 2 additions & 2 deletions websocket/HTTPProtocolParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ SOFTWARE.
#include "HTTPProtocolParser.h"
#include "utils/Logging.h"
#include "utils/sha1.h"
#include "base64.h"
#include "utils/Base64.h"
#include <sstream>
#include <algorithm>
#include <string.h>
Expand Down Expand Up @@ -169,7 +169,7 @@ std::string HTTPProtocolParser::switchProtocol(const std::string& key, const std
std::string accept = key+MAGIC;

Dumais::Utils::SHA1 sha(accept.c_str(),accept.size());
accept = base64_encode(sha.getDigest(),20);
accept = Base64::encode((char*)sha.getDigest(),20);

std::stringstream ss;
ss << "HTTP/1.1 101 Switching Protocols\r\n";
Expand Down
2 changes: 1 addition & 1 deletion websocket/Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SOURCES = WebSocketServer.cpp WebSocket.cpp base64.cpp HTTPProtocolParser.cpp WSProtocolParser.cpp
SOURCES = WebSocketServer.cpp WebSocket.cpp HTTPProtocolParser.cpp WSProtocolParser.cpp
OBJECTS=$(SOURCES:.cpp=.o)
CFLAGS=-I ../ -g -std=c++11
.cpp.o:
Expand Down
123 changes: 0 additions & 123 deletions websocket/base64.cpp

This file was deleted.

4 changes: 0 additions & 4 deletions websocket/base64.h

This file was deleted.

0 comments on commit 9a87fa4

Please sign in to comment.