/* Binary encodes data to a file. */ static void C4SNetEncode(FILE *file, c4snet_data_t *data) { Base64encodeDataType(file, (int) data->vtype); Base64encode(file, &data->size, sizeof(int)); Base64encodeDataType(file, (int) data->type); if (data->vtype == VTYPE_array) { Base64encode(file, data->data.ptr, AllocatedSpace(data)); } else { Base64encode(file, &data->data, C4SNetSizeof(data)); } }
void RTPSessionInterface::UpdateDigestAuthChallengeParams(bool newNonce, bool createOpaque, UInt32 qop) { if (newNonce || (fAuthNonce.Ptr == NULL)) this->CreateDigestAuthenticationNonce(); if (createOpaque) { // Generate a random UInt32 and convert it to a string // The base64 encoded form of the string is made the opaque value SInt64 theMicroseconds = OS::Microseconds(); ::srand((unsigned int)theMicroseconds); UInt32 randomNum = ::rand(); char* randomNumStr = new char[128]; qtss_sprintf(randomNumStr, "%" _U32BITARG_ "", randomNum); int len = ::strlen(randomNumStr); fAuthOpaque.Len = Base64encode_len(len); char *opaqueStr = new char[fAuthOpaque.Len]; (void)Base64encode(opaqueStr, randomNumStr, len); delete[] randomNumStr; // Don't need this anymore if (fAuthOpaque.Ptr != NULL) // Delete existing pointer before assigning new delete[] fAuthOpaque.Ptr; // one fAuthOpaque.Ptr = opaqueStr; fAuthOpaque.Len = ::strlen(opaqueStr); } else { if (fAuthOpaque.Ptr != NULL) delete[] fAuthOpaque.Ptr; fAuthOpaque.Len = 0; } fAuthNonceCount++; fAuthQop = qop; }
int main(int argc, char *argv[]) { int bytesLen = 0; char *bytes = hexStrToBytes(sInputStr, &bytesLen); if (!bytes) { printf("Failure! Couldn't convert hex to bytes.\n"); return 1; } char *base64Str = malloc(Base64encode_len(bytesLen)); if (!base64Str) { printf("Failure! Couldn't alloc buffer for base64 string.\n"); return 1; } Base64encode(base64Str, bytes, bytesLen); if (strcmp(base64Str, sOutputStr) == 0) { printf("Success!\n"); } else { printf("Failure!\n"); } free(base64Str); return 0; }
char * cellophane_generateKey(int length) { char * key; int c = 0; char * tmp = malloc(16); unsigned char * digest = malloc(16); char random_number[16]; strcpy(tmp, ""); while( (c * 16) < length) { tmp = realloc(tmp,(c+1)*16); srand(time(NULL)); sprintf(random_number,"%d",rand()); cellophane_compute_md5((char *)random_number,digest); strcat(tmp, (const char *)digest); c++; } key = malloc(Base64encode_len(c*16)); Base64encode(key, tmp, c*16); return key; }
LUA_STRING Crypto::encodingBase64Lua(bool isDecoding, const char* input, int inputLength) { LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->clean(); int bufferSize = isDecoding ? Base64decode_len(input) : Base64encode_len(inputLength); char *buffer = bufferSize ? (char*)malloc(bufferSize) : NULL; int size = 0; if (buffer) { size = isDecoding ? Base64decode(buffer, input) : Base64encode(buffer, input, inputLength); } if (size) { stack->pushString(buffer, size); } else { stack->pushNil(); } if (buffer) { free(buffer); } return 1; }
int CACrypto::encodeBase64(const char* input, int inputLength, char* output, int outputBufferLength) { CCAssert(Base64encode_len(inputLength) <= outputBufferLength, "CACrypto::encodeBase64() - outputBufferLength too small"); return Base64encode(output, input, inputLength); }
void fetch_data(FILE *fp, const size_t offset, const size_t in_size) { char in_buf[in_size]; fseek(fp, offset, SEEK_SET); size_t read = fread(in_buf, 1, in_size, fp); if (read != in_size) { printf("Error, read = %d\n", read); return; } Base64encode(out_buf, in_buf, in_size); printf("%s\n", out_buf); }
/* * Signature: ([B)[B */ static jbyteArray Base64Encode(JNIEnv *env, jobject thiz, jbyteArray ba) { char * data = (*env)->GetByteArrayElements(env, ba, 0); int len = (*env)->GetArrayLength(env, ba); unsigned long enDataLen; char* enData = (char*)malloc(BUFFER_LEN); enDataLen = Base64encode(enData,data,len); jbyteArray jarrRV =(*env)->NewByteArray(env,enDataLen); (*env)->SetByteArrayRegion(env,jarrRV, 0,enDataLen, enData); (*env)->ReleaseByteArrayElements(env,ba,data,0); free(enData); return jarrRV; }
fzBuffer Data::B64Encode(const char *input, fzUInt inLength) { FZ_ASSERT(input, "Input pointer cannot be NULL"); FZ_ASSERT(inLength > 0, "Input data length cannot be 0."); //should be enough to store 6-bit buffers in 8-bit buffers fzUInt outputSize = Base64encode_len(inLength); char *output = new(std::nothrow) char[outputSize]; if( output ) { Base64encode(output, input, inLength); return fzBuffer(output, outputSize); }else{ FZLOGERROR("Base64: error allocating memory."); return fzBuffer::empty(); } }
void RTPSessionInterface::SetChallengeParams(QTSS_AuthScheme scheme, UInt32 qop, bool newNonce, bool createOpaque) { // Set challenge params // Set authentication scheme fAuthScheme = scheme; if (fAuthScheme == qtssAuthDigest) { // Set Quality of Protection // auth-int (Authentication with integrity) not supported yet fAuthQop = qop; if (newNonce || (fAuthNonce.Ptr == NULL)) this->CreateDigestAuthenticationNonce(); if (createOpaque) { // Generate a random UInt32 and convert it to a string // The base64 encoded form of the string is made the opaque value SInt64 theMicroseconds = OS::Microseconds(); ::srand((unsigned int)theMicroseconds); UInt32 randomNum = ::rand(); char* randomNumStr = new char[128]; qtss_sprintf(randomNumStr, "%" _U32BITARG_ "", randomNum); int len = ::strlen(randomNumStr); fAuthOpaque.Len = Base64encode_len(len); char *opaqueStr = new char[fAuthOpaque.Len]; (void)Base64encode(opaqueStr, randomNumStr, len); delete[] randomNumStr; // Don't need this anymore if (fAuthOpaque.Ptr != NULL) // Delete existing pointer before assigning new delete[] fAuthOpaque.Ptr; // one fAuthOpaque.Ptr = opaqueStr; } else { if (fAuthOpaque.Ptr != NULL) delete[] fAuthOpaque.Ptr; fAuthOpaque.Len = 0; } // Increase the Nonce Count by one // This number is a count of the next request the server // expects with this nonce. (Implies that the server // has already received nonce count - 1 requests that // sent authorization with this nonce fAuthNonceCount++; } }
void printOid(gss_OID oidElem) { OBJECT_IDENTIFIER_t *objId = NULL; asn_dec_rval_t ret; int b64len; char *b64; int r; b64len = Base64encode_len(oidElem->length); b64 = (char *)malloc(sizeof(char) * b64len); r = Base64encode(b64, (char *)(oidElem->elements), oidElem->length); // ret = asn_DEF_OBJECT_IDENTIFIER.ber_decoder(0, &asn_DEF_OBJECT_IDENTIFIER, &objId, oidElem->elements, oidElem->length,0); //if(ret.code != RC_OK) { // printf("\n**COULD NOT CREATE OID**\n"); // } print_arcs(objId); //free(objId); }
/* * Signature: ([B)[B */ static jbyteArray Encrypto(JNIEnv *env, jobject thiz, jbyteArray ba, jint tp) { char * data = (*env)->GetByteArrayElements(env, ba, 0); // int len = (*env)->GetArrayLength(env, ba); int type = tp; char * key; if(tp == 1){ key = PASS; }else if(tp == 2){ key = UPASS; }else{ key = NPASS; } int cipherBufferLen; void * cipherBuffer = malloc(CIPHER_BUFFER_LEN); cipherBufferLen = MGEncryptor(data, strlen(data), key, strlen(key), cipherBuffer); unsigned long enDataLen; char* enData = (char*)malloc(BUFFER_LEN); enDataLen = Base64encode(enData,cipherBuffer,cipherBufferLen); free(cipherBuffer); jbyteArray jarrRV =(*env)->NewByteArray(env,enDataLen); (*env)->SetByteArrayRegion(env,jarrRV, 0,enDataLen, enData); (*env)->ReleaseByteArrayElements(env,ba,data,0); free(enData); return jarrRV; }
extern "C" int Base64Encode(char* base64Dest, const void* byteDataSrc, int byteDataSrcLength) { return Base64encode(base64Dest, (const char*) byteDataSrc, byteDataSrcLength); }
void nc_otoc_start(nc_opts *opts, int pair_raw_sock) { int shell_fd_sock; int pair_fd_sock; fd_set readfds; int maxfds; char time_str[NOW_STR_LEN]; enum {init, none, text_sent, text_received, pkey_sent, pkey_received} last_action = init; shell_fd_sock = fileno(stdin); pair_fd_sock = nc_utils_get_rec_sockfd(pair_raw_sock); maxfds = pair_fd_sock + 1; /* --- start of sending public key --- */ if(opts->secure) { char *msg = NULL; char *msg_type = OTOC_MTYPE_PKEY; char *msg_body = NULL; /* --- start of encoding public key --- */ const char *plain_pkey = (const char*) my_publickey; int plain_pkey_len = crypto_box_PUBLICKEYBYTES; char encoded_pkey[Base64encode_len(plain_pkey_len)]; Base64encode(encoded_pkey, plain_pkey, plain_pkey_len); nc_log_writef("debug", "encode my public key: %s", encoded_pkey); /* --- end of encoding public key --- */ msg_body = encoded_pkey; nc_json_make_otoc_msg(&msg_type, &msg_body, plain_pkey_len, &msg); nn_send(pair_raw_sock, msg, strlen(msg), 0); nc_log_writef("debug", "one to one chat sent public key: %s", msg); last_action = pkey_sent; } /* --- end of sending public key --- */ /* --- start of shel command registration --- */ nc_otoc_register_cmd("/help", func_cmd_help); nc_otoc_register_cmd("/leave", func_cmd_leave); /* --- end of shell commmand registration --- */ for(;;) { switch(last_action) { case init: case pkey_sent: fprintf(stdout, ">> Entering (room code %d) ...\n", pair_raw_sock); fprintf(stdout, ">>> "); fflush(stdout); break; case text_received: fprintf(stdout, ">>> "); fflush(stdout); break; case text_sent: fprintf(stdout, ">>> "); fflush(stdout); break; case none: fprintf(stdout, ">>> "); fflush(stdout); break; case pkey_received: break; } FD_ZERO(&readfds); FD_SET(pair_fd_sock, &readfds); FD_SET(shell_fd_sock, &readfds); select(maxfds, &readfds, NULL, NULL, NULL); if(FD_ISSET(shell_fd_sock, &readfds)) { char *buf = NULL; size_t buf_sz = 1024; int i; nc_utils_now_str(time_str); getline(&buf, &buf_sz, stdin); if(buf[0] == '\n') { last_action = none; } else if(buf[0] == '/') { nc_utils_del_new_line(buf); for(i = 0; i < cmd_current_code; i++) { if(strstr(buf, cmds[i].name)) { if(cmds[i].func(buf) < 0) { return; } break; } } last_action = none; } else { if(opts->secure) { /* --- make ciphermsg with key pairs --- */ int ciphermsg_len = crypto_box_MACBYTES + strlen(buf); unsigned char nonce[crypto_box_NONCEBYTES]; unsigned char ciphermsg[ciphermsg_len]; /* @TODO: use random nonce */ //randombytes_buf(nonce, sizeof nonce); memset(nonce, '\0', sizeof nonce); crypto_box_easy(ciphermsg, (const unsigned char*) buf, strlen(buf), nonce, peers_publickey[pair_raw_sock], my_secretkey); /* --- make msg encoded with base64 --- */ const char *plain_ciphermsg = (const char*) ciphermsg; int plain_ciphermsg_len = ciphermsg_len; int encoded_ciphermsg_len = Base64encode_len(plain_ciphermsg_len); char encoded_ciphermsg[encoded_ciphermsg_len]; Base64encode(encoded_ciphermsg, plain_ciphermsg, plain_ciphermsg_len); nc_log_writef("debug", "encode ciphermsg: %s", encoded_ciphermsg); /* --- serialize msg with json --- */ char *msg = NULL; char *msg_type = OTOC_MTYPE_STXT; char *msg_body = NULL; msg_body = encoded_ciphermsg; nc_json_make_otoc_msg(&msg_type, &msg_body, strlen(buf), &msg); nc_log_writef("debug", "serialize encoded ciphermsg: %s", msg); /* --- send msg --- */ nn_send(pair_raw_sock, msg, strlen(msg), 0); } else { char *msg = NULL; char *msg_type = OTOC_MTYPE_RTXT; nc_json_make_otoc_msg(&msg_type, &buf, strlen(buf), &msg); nn_send(pair_raw_sock, msg, strlen(msg), 0); fprintf(stdout, "[%s] >>> %s", time_str, buf); fflush(stdout); nc_utils_del_new_line(buf); nc_log_writef("debug", "one to one chat sent: %s", buf); nc_utils_empty_string(buf); last_action = text_sent; } } } else if(FD_ISSET(pair_fd_sock, &readfds)) { char *buf = NULL; char *msg_body = NULL; char *msg_type = NULL; int original_msg_body_len; nn_recv(pair_raw_sock, &buf, NN_MSG, 0); nc_json_extract_otoc_msg(&buf, &msg_type, &original_msg_body_len, &msg_body); nc_utils_del_new_line(buf); nc_log_writef("debug", "one to one chat received: %s", msg_type); nn_freemsg(buf); if(strncmp(msg_type, OTOC_MTYPE_PKEY, OTOC_MTYPE_LEN) == 0) { /* public key message */ /* --- start of decoding public key --- */ int plain_pkey_len = Base64decode_len(msg_body); char plain_pkey[plain_pkey_len]; Base64decode(plain_pkey, (const char*) msg_body); strncpy(peers_publickey[pair_raw_sock], plain_pkey, crypto_box_PUBLICKEYBYTES); nc_log_writef("debug", "decoded peer's public key was stored."); /* --- end of decoding public key --- */ last_action = pkey_received; } else if(strncmp(msg_type, OTOC_MTYPE_RTXT, OTOC_MTYPE_LEN) == 0) { /* raw text message */ nc_utils_now_str(time_str); fprintf(stdout, "\r[%s] <<< %s", time_str, msg_body); fflush(stdout); last_action = text_received; } else if(strncmp(msg_type, OTOC_MTYPE_STXT, OTOC_MTYPE_LEN) == 0) { /* secure text message */ if(!opts->secure) { char *alert = "\r[%s] <<< { ... encrypted message ... }\n" "==========================================\n" "Your peer uses NanoChat undre secure mode.\n" "Use -s flag to see his encrypted messages.\n" "==========================================\n"; nc_utils_now_str(time_str); fprintf(stdout, alert, time_str); fflush(stdout); last_action = text_received; } else { /* --- decode secure msg body --- */ int plain_ciphermsg_len = Base64decode_len(msg_body); char plain_ciphermsg[plain_ciphermsg_len]; Base64decode(plain_ciphermsg, (const char*) msg_body); /* --- decrypt ciphermsg --- */ int decrypted_len = original_msg_body_len; int ciphermsg_len = crypto_box_MACBYTES + decrypted_len; unsigned char decrypted[decrypted_len]; unsigned char nonce[crypto_box_NONCEBYTES]; memset(nonce, '\0', sizeof nonce); crypto_box_open_easy(decrypted, plain_ciphermsg, ciphermsg_len, nonce, peers_publickey[pair_raw_sock], my_secretkey); /* --- show decrypted msg body --- */ decrypted[original_msg_body_len] = '\0'; nc_utils_now_str(time_str); fprintf(stdout, "\r[%s] <<< %s", time_str, decrypted); fflush(stdout); last_action = text_received; } } } } }
static bool writeDictToFileRecursive(CFDictionaryRef dict, int level, FILE *fp) { for (int i = 0; i < level; i++) fwrite("\t", 1, 1, fp); fwrite("<dict>\n", 1, 7, fp); CFIndex len = CFDictionaryGetCount(dict); if (len == 0) { for (int i = 0; i < level; i++) fwrite("\t", 1, 1, fp); fwrite("</dict>\n", 1, 8, fp); return true; } CFStringRef *keys = (CFStringRef*)malloc(len * sizeof(CFStringRef)); CFTypeRef *values = (CFTypeRef*)malloc(len * sizeof(CFTypeRef)); CFDictionaryGetKeysAndValues(dict, (const void**)keys, (const void**)values); for (CFIndex ci = 0; ci < len; ci++) { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<key>", 1, 5, fp); CFIndex cflen = CFStringGetLength(keys[ci]); if (cflen > 0) { char buf[cflen+1]; if (CFStringGetCString(keys[ci], buf, cflen+1, kCFStringEncodingUTF8) == false) { free(keys); free(values); return false; } fwrite(buf, 1, cflen, fp); } fwrite("</key>\n", 1, 7, fp); CFTypeID valtype = CFGetTypeID(values[ci]); if (valtype == CFStringGetTypeID()) { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<string>", 1, 8, fp); cflen = CFStringGetLength((CFStringRef)values[ci]); if (cflen > 0) { char buf[cflen+1]; if (CFStringGetCString((CFStringRef)values[ci], buf, cflen+1, kCFStringEncodingUTF8) == false) { free(keys); free(values); return false; } fwrite(buf, 1, cflen, fp); } fwrite("</string>\n", 1, 10, fp); } else if (valtype == CFDictionaryGetTypeID()) { if (!writeDictToFileRecursive((CFDictionaryRef)values[ci], level+1, fp)) { free(keys); free(values); return false; } } else if (valtype == CFDataGetTypeID()) { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<data>\n", 1, 7, fp); CFIndex datalen = CFDataGetLength((CFDataRef)values[ci]); if (datalen > 0) { int encodedlen = Base64encode_len((int)datalen); char encodeddata[encodedlen]; Base64encode(encodeddata, (const char*)CFDataGetBytePtr((CFDataRef)values[ci]), (int)datalen); encodedlen = strlen(encodeddata); int count = 0; while (count < encodedlen) { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); if ( (encodedlen-count) > 60 ) { fwrite(encodeddata+count, 1, 60, fp); count += 60; } else { fwrite(encodeddata+count, 1, encodedlen-count, fp); count = encodedlen; } fwrite("\n", 1, 1, fp); } } for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("</data>\n", 1, 8, fp); } else if (valtype == CFBooleanGetTypeID()) { if (CFBooleanGetValue((CFBooleanRef)values[ci]) == true) { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<true/>\n", 1, 8, fp); } else { for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<false/>\n", 1, 9, fp); } } else if (valtype == CFArrayGetTypeID()) { // TODO: Array output is not supported yet for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<array>\n", 1, 8, fp); for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("</array>\n", 1, 9, fp); } #if defined(__APPLE__) else if (valtype == CFDateGetTypeID()) { // TODO: Date output is not supported yet for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<date>\n", 1, 7, fp); for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("</date>\n", 1, 8, fp); } #endif else if (valtype == CFNumberGetTypeID()) { // TODO: Number output is not supported yet for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("<real>\n", 1, 7, fp); for (int i = 0; i <= level; i++) fwrite("\t", 1, 1, fp); fwrite("</real>\n", 1, 8, fp); } else { // unknown type free(keys); free(values); return false; } } free(keys); free(values); for (int i = 0; i < level; i++) fwrite("\t", 1, 1, fp); fwrite("</dict>\n", 1, 8, fp); return true; }
void* SomeAwesomeThings(void* Param){ Client* theClient = (Client*)Param; char* message = (char*)malloc(4086); char sendMessage[4086]; char encrypt[4086]; char* receiver; char* tmp; char* ender; char* err; Client* ClientCounter; int msgSize; int usernameSet = 0; int nameLength; int sub_msg_len; int encrypt_len; //RC4 component RC4Container RC4key; int iter1; int iter2; RC4key.iter1 = &iter1; RC4key.iter2 = &iter2; int RC4KeySet = 0; // unsigned char hash_out[SHA_DIGEST_LENGTH + 1]; char hash_string[SHA_DIGEST_LENGTH * 2 + 1]; int iterator; memset(sendMessage, '\0', sizeof(sendMessage)); err = (char*) malloc(130); // if((msgSize = read(theClient->sockfd, message, sizeof(message) - 1)) > 0){ // message[msgSize] = '\0'; // int nameLength = strstr(message, "\r\n.\r\n") - message; // for(msgSize = 0; msgSize < nameLength; msgSize++){ // theClient->Name[msgSize] = message[msgSize]; // } // theClient->Name[nameLength] = '\0'; // printf("%s has connected\n", theClient->Name); // } while((msgSize = read(theClient->sockfd, message, 4086 - 1)) > 0){ message[msgSize] = '\0'; sub_msg_len = 0; while((ender = strstr(message, "\r\n.\r\n")) != NULL){ // *ender = '\0'; sub_msg_len += ender - message + 5; if(sub_msg_len > msgSize) break; // printf("%s\n", message); //Do things here tmp = strstr(message, "\r\n"); *tmp = '\0'; printf("%s\n", message); if(strcmp(message, "Mode: Public") == 0){ tmp = tmp + 2; nameLength = strstr(tmp, "\r\n.\r\n") - tmp + 5; sprintf(sendMessage,"%s\r\nUser: %s\r\n", message, theClient->Name); strncat(sendMessage, tmp, nameLength); for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){ if(ClientCounter == theClient) continue; write(ClientCounter->sockfd, sendMessage, sizeof(sendMessage)); } } else if((strcmp(message, "Mode: Private") == 0) || (strcmp(message, "Mode: InitPriv") == 0) || (strcmp(message, "Mode: AccPriv") == 0) ){ tmp = tmp + 2; tmp = strstr(tmp, " ") + 1; receiver = tmp; tmp = strstr(tmp, "\r\n"); *tmp = '\0'; tmp = tmp + 2; nameLength = strstr(tmp, "\r\n.\r\n") - tmp + 5; sprintf(sendMessage,"%s\r\nUser: %s\r\n", message, theClient->Name); strncat(sendMessage, tmp, nameLength); for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){ if(strcmp(receiver, ClientCounter->Name) == 0){ write(ClientCounter->sockfd, sendMessage, sizeof(sendMessage)); break; } } } else if(strcmp(message, "Mode: GetList") == 0){ sprintf(sendMessage, "Mode: List\r\n"); for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){ if(ClientCounter == theClient)continue; strcat(sendMessage, ClientCounter->Name); strcat(sendMessage, "\r\n"); } strcat(sendMessage, "\r\n.\r\n"); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } else if(strcmp(message, "Mode: Username") == 0){ tmp = tmp + 2; if(usernameSet == 0){ if(RC4KeySet == 1){ printf("Setting username\n"); nameLength = strstr(tmp, "\r\n.\r\n") - tmp; char* decode; int decode_len = Base64decode(tmp, (unsigned char**)&decode, nameLength); encrypt_len = RC4Crypt(decode_len, (unsigned char*)decode, (unsigned char*)encrypt, &RC4key); free(decode); tmp = strstr(encrypt, "\r\n.,\r\n"); nameLength = tmp - encrypt; *tmp = '\0'; tmp = tmp + 6; if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){ for(msgSize = 0; msgSize < nameLength; msgSize++){ theClient->Name[msgSize] = *(encrypt + msgSize); } theClient->Name[nameLength] = '\0'; printf("%s\n", theClient->Name); usernameSet++; } } } } else if(strcmp(message, "Mode: GetCA") == 0){ sprintf(sendMessage, "Mode: ServCA\r\n"); strcat(sendMessage, public_key); strcat(sendMessage, "\r\n.\r\n"); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } else if(strcmp(message, "Mode: SetPubKey") == 0){ tmp = tmp + 2; nameLength = strstr(tmp, "\r\n.\r\n") - tmp; if(RC4KeySet == 1){ char* decoded; int decoded_len = Base64decode(tmp, (unsigned char**)&decoded, nameLength); encrypt_len = RC4Crypt(decoded_len, (unsigned char*)decoded, (unsigned char*)encrypt, &RC4key); free(decoded); encrypt[encrypt_len] = '\0'; tmp = strstr(encrypt, "\r\n.,\r\n"); nameLength = tmp - encrypt; *tmp = '\0'; tmp = tmp + 6; if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){ for(iterator = 0; iterator < nameLength; iterator++){ *(theClient->public_key + iterator) = *(encrypt + iterator); } *(theClient->public_key + nameLength) = '\0'; } else{ //TODO: Return some error printf("Failed to set public key\n"); sprintf(sendMessage, "Mode: FailPubKey\r\n.\r\n"); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } } } else if(strcmp(message, "Mode: SetRC4Key") == 0){ if(RC4KeySet == 0){ tmp = tmp + 2; nameLength = strstr(tmp, "\r\n.\r\n") - tmp; char* decoded; int dedoded_len = Base64decode(tmp, (unsigned char**)&decoded, nameLength); if((encrypt_len = private_decrypt((unsigned char*)decoded, dedoded_len, (unsigned char*)private_key, (unsigned char*)encrypt, RSA_PKCS1_OAEP_PADDING)) == -1){ ERR_load_crypto_strings(); ERR_error_string(ERR_get_error(), err); fprintf(stderr, "Error decrypting message: %s\n", err); sprintf(sendMessage, "Mode: FailRC4Key\r\n.\r\n"); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } else{ tmp = strstr(encrypt, "\r\n.,\r\n"); nameLength = tmp - encrypt; *tmp = '\0'; tmp = tmp + 6; //TODO: Check if hash of encrypt is the same with tmp if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){ initRC4key(&RC4key, encrypt, nameLength); RC4KeySet = 1; } else{ sprintf(sendMessage, "Mode: FailRC4Key\r\n.\r\n"); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } } free(decoded); } } else if(strcmp(message, "Mode: GetPubKey") == 0){ tmp = tmp + 2; tmp = strstr(tmp, " ") + 1; receiver = tmp; tmp = strstr(tmp, "\r\n"); *tmp = '\0'; for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){ if(strcmp(receiver, ClientCounter->Name) == 0) break; } if(ClientCounter != NULL){ if(ClientCounter->public_key[0] != '\0' && RC4KeySet == 1){ SHA1((unsigned char*)ClientCounter->public_key, strlen(ClientCounter->public_key), (unsigned char*)hash_out); for(iterator = 0; iterator < SHA_DIGEST_LENGTH; iterator++){ sprintf(&hash_string[iterator * 2], "%02x", (unsigned int)hash_out[iterator]); } sprintf(sendMessage, "%s\r\n.,\r\n%s", ClientCounter->public_key, hash_string); encrypt_len = RC4Crypt(strlen(sendMessage), (unsigned char*)sendMessage, (unsigned char*)encrypt, &RC4key); encrypt[encrypt_len] = '\0'; char* encoded; int encoded_len = Base64encode(encrypt, encrypt_len, &encoded); encoded[encoded_len] = '\0'; sprintf(sendMessage, "Mode: ClientPubKey\r\nUser: %s\r\n%s\r\n.\r\n", ClientCounter->Name, encoded); free(encoded); printf("%s\n", sendMessage); printf("%s\n", ClientCounter->public_key); write(theClient->sockfd, sendMessage, sizeof(sendMessage)); } else{ sprintf(sendMessage, "Mode: FailPubKey\r\nUser: %s\r\n.\r\n", ClientCounter->Name); } } } *ender = '\0'; ender += 5; message = ender; } } printf("%s has been disconnected\n", theClient->Name); if(theClient == head){ head = theClient->Next; if(head != NULL)head->Previous = NULL; else tail = NULL; } else{ theClient->Previous->Next = theClient->Next; if(theClient == tail){ tail = theClient->Previous; } } if(theClient->keypair != NULL) RSA_free(theClient->keypair); free(theClient); return NULL; }
int ICACHE_FLASH_ATTR http_ws_handle_connect(http_connection *c) { NODE_DBG("http_ws_handle_connect c =%p",c); if(c->state == HTTPD_STATE_ON_URL){ http_set_save_header(c,HTTP_ORIGIN); http_set_save_header(c,HTTP_CONNECTION); http_set_save_header(c,HTTP_UPGRADE); http_set_save_header(c,HTTP_SEC_WEBSOCKET_KEY); http_set_save_header(c,HTTP_SEC_WEBSOCKET_PROTOCOL); http_set_save_header(c,HTTP_SEC_WEBSOCKET_VERSION); return HTTP_WS_CGI_MORE; } //wait handshake request complete if(c->state != HTTPD_STATE_BODY_END) return HTTP_WS_CGI_MORE; header * upgrade_header = http_get_header(c,HTTP_UPGRADE); header * connection_header = http_get_header(c,HTTP_CONNECTION); header * origin_header = http_get_header(c,HTTP_ORIGIN); header * key_header = http_get_header(c,HTTP_SEC_WEBSOCKET_KEY); if(upgrade_header==NULL) goto badrequest; if(connection_header==NULL) goto badrequest; if(origin_header==NULL) goto badrequest; if(key_header==NULL) goto badrequest; NODE_DBG("headers ok"); if(os_strcasecmp(upgrade_header->value,"websocket")!=0) goto badrequest; // Following (https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17) //calculate sha1 of concatenetion key+uuid uint8_t digest[20]; //sha1 is always 20 byte long SHA1_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx,key_header->value,os_strlen(key_header->value)); SHA1_Update(&ctx,ws_uuid,os_strlen(ws_uuid)); SHA1_Final(digest,&ctx); char base64Digest[31]; // Base64encode(base64Digest,(const char*)digest,20); //accept the handshake http_SET_HEADER(c,HTTP_UPGRADE,"WebSocket"); http_SET_HEADER(c,HTTP_CONNECTION,"Upgrade"); http_SET_HEADER(c,HTTP_WEBSOCKET_ACCEPT,base64Digest); http_websocket_HANDSHAKE(c); c->handshake_ok=1; if(client_connected_callback!=NULL) client_connected_callback(c); return HTTP_WS_CGI_MORE; badrequest: http_response_BAD_REQUEST(c); return HTTP_WS_CGI_DONE; }