Пример #1
0
static void http_test() 
{
  DEBUG("\n\n== http_test ==\n");  
  size_t resp_size = 0;
  char buffer[1024];
  size_t out_len = 0;
  DO_CLEAR(buffer, 0, 1024);
  sprintf(buffer, "name=%s&number=%s&class=%s&memo=%s", base64encode(TEST_NAME, &out_len),  base64encode(TEST_NUMBER, &out_len),
     base64encode(TEST_CLASS, &out_len),  base64encode(TEST_MEMO, &out_len));
  DEBUG("param = %s\n", buffer);
  http_global_init();
  char *res = http_post(URL, (const char *)&buffer, NULL, &resp_size);
  http_global_release();
  if (res != NULL) {
    DEBUG("%s : response =\n%s \n", __func__, res);
    char *content = getContent(res, resp_size);
    if (content != NULL) {
      DEBUG("content base64 = %s\n", content);
      char *decode = base64_decode((const unsigned char *)content, strlen(content), &out_len);
      if (decode != NULL) {
        DEBUG("content plaintext = %s \n", decode);
        DO_FREE(decode);
      }
      DO_FREE(content);
    }
    DO_FREE(res);
  }
}
	TITANIUM_FUNCTION(Utils, base64encode)
	{
		if (arguments.size() >= 1) {
			const auto _0 = arguments.at(0);

			// Titanium.Blob / Titanium.Filesystem.File
			if (_0.IsObject()) {
				const auto js_obj = static_cast<JSObject>(_0);

				// Titanium.Blob
				const auto blob_obj = js_obj.GetPrivate<Blob>();
				if (blob_obj != nullptr) {
					return static_cast<JSValue>(base64encode(blob_obj)->get_object());
				}

				// Titanium.Filesystem.File
				const auto file_obj = js_obj.GetPrivate<Filesystem::File>();
				if (file_obj != nullptr) {
					return static_cast<JSValue>(base64encode(file_obj)->get_object());
				}

			// String
			} else if (_0.IsString()) {
				auto obj = static_cast<std::string>(_0);
				return static_cast<JSValue>(base64encode(obj)->get_object());
			}
		}
		return get_context().CreateUndefined();
	}
Пример #3
0
int main()
{
	const PsimagLite::String s = "ADP GmbH\nAnalyse Design & Programmierung"
	                             "\nGesellschaft mit beschränkter Haftung" ;

	PsimagLite::PsiBase64::Encode base64encode(s);
	PsimagLite::String encoded = base64encode();
	std::cout<<"encoded: "<<encoded<<"\n";
	std::cout<<"decoded: "<<PsimagLite::PsiBase64::Decode(encoded)()<<"\n";
}
Пример #4
0
int main(int argc, char *argv[]) {
  const char indata[] = "MyBloodyValentinMyBloodyValentin";
  unsigned char data[32768];
  char hex[256], base64[256];
  int len;

  unsigned char iv[] = { 'Y', 'E', 'L', 'L', 'O', 'W', ' ', 'S', 'U', 'B', 'M', 'A', 'R', 'I', 'N', 'E' };
  unsigned char key[] = { 'Y', 'E', 'L', 'L', 'O', 'W', ' ', 'S', 'U', 'B', 'M', 'A', 'R', 'I', 'N', 'E' };

  len = strlen(indata);
  printf("// testing aes-128-ecb\n");

  printf("Plaintext:\n");
  hexdump(indata, len);
  
  memcpy(data, indata, len);

  aes_ecb_encrypt(data, len, key, sizeof(key));
  printf("Ciphertext:\n");
  hexdump(data, 16);

  base64[base64encode(data, len, base64)] = '\0';
  printf("base64: %s\n", base64);

  aes_ecb_decrypt(data, len, key, sizeof(key));
  data[len] = '\0';

  printf("Decrypted plaintext: %s\n", data);
  hexdump(data, len);

  printf("// testing aes-128-cbc\n");

  printf("Plaintext:\n");
  hexdump(indata, len);
  
  memcpy(data, indata, len);

  aes_cbc_encrypt(data, len, key, sizeof(key), iv);
  printf("Ciphertext:\n");
  hexdump(data, 16);

  base64[base64encode(data, len, base64)] = '\0';
  printf("base64: %s\n", base64);

  aes_cbc_decrypt(data, len, key, sizeof(key), iv);
  data[len] = '\0';

  printf("Decrypted plaintext: %s\n", data);
  hexdump(data, len);



  return 0;
}
Пример #5
0
void SparkWriter::WriteEncodedString(void *data, long numParticles, int dim, int numBytes, std::ofstream *outfile)
{
  uLongf inputBytes = numParticles * dim * numBytes;
  uLongf numberOfBlocks = ceil(inputBytes / (double) VTP_BINARY_BLOCK_SIZE);
  uLongf lastBlockSize  = inputBytes % VTP_BINARY_BLOCK_SIZE;


  int *headerData = new int[3+numberOfBlocks];
  headerData[0] = numberOfBlocks;
  headerData[1] = (numberOfBlocks>1) ? VTP_BINARY_BLOCK_SIZE : lastBlockSize;
  headerData[2] = lastBlockSize;

  uLongf compressedDataSize = compressBound((uLongf) lastBlockSize) + (numberOfBlocks-1)*compressBound((uLongf) VTP_BINARY_BLOCK_SIZE);
  unsigned char *compressBuffer = new unsigned char[compressedDataSize];
  int totalCompressedDataSize = 0;

  uLongf currentSize = compressedDataSize;

  unsigned char *compressBufferPtr = compressBuffer;
  for (int i=0; i<numberOfBlocks; i++)
  {
    int blockSize = VTP_BINARY_BLOCK_SIZE;
    if (numberOfBlocks == 1 || i==numberOfBlocks-1) // last block
      blockSize = lastBlockSize;
    int blockStart = i*VTP_BINARY_BLOCK_SIZE;

    compress(compressBufferPtr,
              &currentSize,
              (unsigned char *) data+blockStart,
              blockSize);

    compressBufferPtr += currentSize;
    totalCompressedDataSize += currentSize;

    headerData[3+i] = (int) currentSize;
    currentSize = compressedDataSize - (compressBufferPtr-compressBuffer);
  }

  uLongf b64HeaderSize = ((4*(numberOfBlocks+3)+2)/3)*4;
  uLongf b64DataSize   = ((totalCompressedDataSize+2)/3)*4;

  char *outputBuffer = new char[b64HeaderSize + b64DataSize+1];
  base64encode(headerData, 4*(numberOfBlocks+3), outputBuffer, b64HeaderSize+1);
  base64encode(compressBuffer, totalCompressedDataSize, outputBuffer+b64HeaderSize, b64DataSize+1);

  delete [] compressBuffer;
  delete [] headerData;

  outfile->write(outputBuffer, b64HeaderSize + b64DataSize);
  delete [] outputBuffer;
}
Пример #6
0
/*
 *		Certificate info:
 *				- id: requester identification
 *				- cname: common name
 *				- time: date on which the certificate has been generated
 *				- valid: date up to the certificate is valid
 *				- auth_key: key used in mutual authentication (SMQV)
 *				- token_key: key used to sign access token (MSS)
 *				- signature: signature under issuer's key
 *
 */
void generate_certificate(const unsigned char csr[CSR_MAX_SIZE], const char valid[TIME_BUFFER_SIZE], const unsigned char ca_skey[ECDSA_SKEY_SIZE], unsigned char certificate[CERTIFICATE_MAX_SIZE]) {
	unsigned int id;
	char cname[CNAME_MAX_SIZE], time[TIME_BUFFER_SIZE];
	unsigned char auth_key[SMQV_PKEY_SIZE], token_key[MSS_PKEY_SIZE], cert_signature[ECDSA_SIGNATURE_SIZE], csr_signature[MSS_SIGNATURE_SIZE];
	unsigned char buffer[CERTIFICATE_MAX_SIZE];
	memset(buffer, 0, CERTIFICATE_MAX_SIZE);

	now(&time);

	if(compare_dates(valid, time) == -1 && read_csr(&id, cname, time, auth_key, token_key, csr_signature, csr)) {
		unsigned int index = 0;

		index += cert_append_info(buffer, id, cname, time, valid, auth_key, token_key);

		unsigned char cert_digest[2 * MSS_SEC_LVL];
        	sponge_hash(buffer, index, cert_digest, 2 * MSS_SEC_LVL);
		ecdsa_sign(ca_skey, cert_digest, cert_signature);
		memcpy(buffer + index, cert_signature, ECDSA_SIGNATURE_SIZE);
		index += ECDSA_SIGNATURE_SIZE;

		base64encode(buffer, index, certificate, CSR_MAX_SIZE);
	}
	else{
    certificate[0] = '\0';
		if( compare_dates(valid, time) != -1)
			printf("Authentication ERROR: !(valid > t_now)\n");
		else
			printf("Authentication ERROR: !mss_verify\n");
  }
}
Пример #7
0
//=============================================================================
// WebSocketAcceptKey()
// 1) взять строковое значение из заголовка Sec-WebSocket-Key и объединить со
//	строкой 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
// 2) вычислить бинарный хеш SHA-1 (бинарная строка из 20 символов) от полученной
//	в первом пункте строки
// 3) закодировать хеш в Base64
//=============================================================================
bool ICACHE_FLASH_ATTR WebSocketAcceptKey(uint8* dkey, uint8* skey)
{
	uint8 keybuf[sizeWebSocketAddKey];
	SHA1_CTX cha;
	int len = 0;
	{
		uint8 *pcmp = skey;
		while(*pcmp >= '+' && len < sizeWebSocketKey) {
			pcmp++;
			len++;
		};
		if(len != sizeWebSocketKey) return false;
		ets_memcpy(keybuf, WebSocketAddKey, sizeWebSocketAddKey);
	};
	SHA1Init(&cha);
	SHA1Update(&cha, skey, len);
	SHA1Update(&cha, keybuf, sizeWebSocketAddKey);
	SHA1Final(keybuf, &cha);
	len = base64encode(dkey, 31, keybuf, SHA1_HASH_LEN);
#if DEBUGSOO > 2
	os_printf("\ncha:'");
	print_hex_dump(keybuf, SHA1_HASH_LEN, '\0');
	os_printf("'\n");
	os_printf("key[%u]:'%s'\n", len, dkey);
#endif
   	return true;
}
Пример #8
0
void test_base64(void)
{
	/* The string "Hello, world" should encode as "SGVsbG8sIHdvcmxk" */
  const unsigned char	*input = (const unsigned char *)"Hello, world";
	unsigned char	 output[100];
	unsigned char	 decode[100];
	unsigned int	 i;

	for (i = 0; i < 100; i++) {
		output[i] = '\0';
	}

	printf("Base64 encode.......................... "); fflush(stdout);
	i = base64encode(input, strlen((char *)input), output, 100);
	if ((i != 16) || (strncmp((char *)output, "SGVsbG8sIHdvcmxk", i) != 0)) {
		printf("fail\n");
		return;
	}
	printf("pass\n");

	printf("Base64 decode.......................... "); fflush(stdout);
	i = base64decode(output, i, decode, 100);
	if ((i != 12) || (strncmp((char *)decode, "Hello, world", i) != 0)) {
		printf("fail\n");
		return;
	}
	printf("pass\n");
}
Пример #9
0
static std::string b64encode(const std::string &s) {
  std::string result;
  result.resize(s.size() * 2 + 4);
  auto n = base64encode(s.data(), s.size(), &result[0], result.size());
  result.resize(n);
  return result;
}
Пример #10
0
/* **********************************
 * Websocket
 * **********************************/
static int do_ws_handshake(evhtp_request_t *req) {
    const char *upgrade = evhtp_header_find(req->headers_in, "Upgrade");
    const char *connection = evhtp_header_find(req->headers_in, "Connection");
    const char *ws_key = evhtp_header_find(req->headers_in, "Sec-WebSocket-Key");

    if (upgrade && connection && ws_key) {
        if (!strstrcase(upgrade, "websocket") ||
            !strstrcase(connection, "Upgrade")){
            return EVHTP_RES_ERROR;
        }
        static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        unsigned char *str = calloc(strlen(ws_key)+strlen(magic)+1, sizeof(unsigned char));

        strcpy((char *)str, ws_key);
        strcat((char *)str, magic);

        unsigned char hash[SHA_DIGEST_LENGTH];
        SHA1(str, strlen((char *)str), hash);

        free(str);

        char ws_accept[29];
        ws_accept[28] = '\0';
        base64encode(&hash[0], sizeof(hash), &ws_accept[0], sizeof(ws_accept)-1);

        ws_headers_add_header(req->headers_out, "Connection", "Upgrade" );
        ws_headers_add_header(req->headers_out, "Sec-WebSocket-Accept", &ws_accept[0]);
        ws_headers_add_header(req->headers_out, "Upgrade", "websocket");
        evhtp_send_reply(req, EVHTP_RES_SWITCH_PROTO);
        return EVHTP_RES_SWITCH_PROTO;
    }
    return EVHTP_RES_OK;
}
Пример #11
0
	void web_connection_base::add_headers(std::string& request
		, proxy_settings const& ps, bool using_proxy) const
	{
		request += "Host: ";
		request += m_host;
		if (m_first_request || m_ses.settings().always_send_user_agent) {
			request += "\r\nUser-Agent: ";
			request += m_ses.settings().user_agent;
		}
		if (!m_external_auth.empty()) {
			request += "\r\nAuthorization: ";
			request += m_external_auth;
		} else if (!m_basic_auth.empty()) {
			request += "\r\nAuthorization: Basic ";
			request += m_basic_auth;
		}
		if (ps.type == proxy_settings::http_pw) {
			request += "\r\nProxy-Authorization: Basic ";
			request += base64encode(ps.username + ":" + ps.password);
		}
		for (web_seed_entry::headers_t::const_iterator it = m_extra_headers.begin();
		     it != m_extra_headers.end(); ++it) {
		  request += "\r\n";
		  request += it->first;
		  request += ": ";
		  request += it->second;
		}
		if (using_proxy) {
			request += "\r\nProxy-Connection: keep-alive";
		}
		if (m_first_request || using_proxy) {
			request += "\r\nConnection: keep-alive";
		}
	}
Пример #12
0
	void web_connection_base::add_headers(std::string& request
		, aux::session_settings const& sett, bool using_proxy) const
	{
		request += "Host: ";
		request += m_host;
		if (m_first_request || m_settings.get_bool(settings_pack::always_send_user_agent)) {
			request += "\r\nUser-Agent: ";
			request += m_settings.get_str(settings_pack::user_agent);
		}
		if (!m_external_auth.empty()) {
			request += "\r\nAuthorization: ";
			request += m_external_auth;
		} else if (!m_basic_auth.empty()) {
			request += "\r\nAuthorization: Basic ";
			request += m_basic_auth;
		}
		if (sett.get_int(settings_pack::proxy_type) == settings_pack::http_pw) {
			request += "\r\nProxy-Authorization: Basic ";
			request += base64encode(sett.get_str(settings_pack::proxy_username)
				+ ":" + sett.get_str(settings_pack::proxy_password));
		}
		for (web_seed_entry::headers_t::const_iterator it = m_extra_headers.begin();
		     it != m_extra_headers.end(); ++it) {
		  request += "\r\n";
		  request += it->first;
		  request += ": ";
		  request += it->second;
		}
		if (using_proxy) {
			request += "\r\nProxy-Connection: keep-alive";
		}
		if (m_first_request || using_proxy) {
			request += "\r\nConnection: keep-alive";
		}
	}
Пример #13
0
void calc_accept_key(char* s, char* r)
{
  const char* magicKey="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  char sInput[64]={0x00,};
  char tmpBuf[32]={0x00,};
  strcpy(sInput,s);
  strcpy(sInput+strlen(s),magicKey);
  printf("input: %s\r\n",sInput);
  SHA1Context sha;
  SHA1Reset(&sha);
  SHA1Input(&sha, (const unsigned char *)sInput, strlen(sInput));
  if (!SHA1Result(&sha)){
    printf("ERROR-- could not compute message digest\n");
  }else{
    for(unsigned char i = 0; i < 5 ; i++){
      tmpBuf[i*4+0]=*((char*)&sha.Message_Digest[i]+3);
      tmpBuf[i*4+1]=*((char*)&sha.Message_Digest[i]+2);
      tmpBuf[i*4+2]=*((char*)&sha.Message_Digest[i]+1);
      tmpBuf[i*4+3]=*((char*)&sha.Message_Digest[i]+0);
    }
    for(unsigned char i=0;i<20;i++)
      printf("%02X", tmpBuf[i]);
    printf("\r\n");
    base64encode(tmpBuf,r,20);
  }
}
Пример #14
0
int b64Encode(const uint8_t *binData, int32_t binLength, char *b64Data, size_t b64length)
{
    if (binLength == 0) {
        b64Data[0] = 0;
        return 0;
    }

    base64encode(binData, binLength, b64Data, b64length);
    return strlen(b64Data);
}
Пример #15
0
///////ENCODE///////
char * B64E(char *block)
{
 size_t block_size=getSize(block);
 char block_enc[SIZE];
 size_t block_enc_size=sizeof(block_enc);
  if( base64encode((void*)block, block_size, block_enc,block_enc_size )) //if there was an encoding error
  {
	printf("Unable to encode\n Exiting... \n");
	exit(1);
  }
  return block_enc;
 }
Пример #16
0
static void handle_auth_login_response(str* line, ssize_t offset)
{
  saw_auth_login = 0;
  if (!base64decode(line->s + offset, line->len + offset, &tmpstr))
    username.len = 0;
  else {
    make_username(tmpstr.s, tmpstr.len, "AUTH LOGIN ");
    line->len = offset;
    base64encode(username.s, username.len, line);
    str_catb(line, CRLF, 2);
  }
}
Пример #17
0
void
mbus_data_as_string( MObject * mdata, GString * buf )
{
  GByteArray * tmp = g_byte_array_new();

  M_OBJECT_ASSERT( mdata, MDATA );
  base64encode( M_DATA( mdata )->array, tmp );
  g_byte_array_prepend( tmp, ( guchar * ) "<", 1 );
  g_byte_array_append( tmp, ( guchar * ) ">", 1 );
  g_string_append_len( buf, ( gchar * ) tmp->data, tmp->len );

  g_byte_array_free( tmp, TRUE );
}
Пример #18
0
int dlg_th_encode_callid(struct sip_msg *msg)
{
	struct lump *del;
	str new_callid;
	int i;

	if (msg->callid == NULL) {
		LM_ERR("Message with no callid\n");
		return -1;
	}

	new_callid.len = calc_base64_encode_len(msg->callid->body.len);
	new_callid.len += topo_hiding_prefix.len;
	new_callid.s = pkg_malloc(new_callid.len);
	if (new_callid.s==NULL) {
		LM_ERR("Failed to allocate callid len\n");
		return -1;
	}

	if (new_callid.s == NULL) {
		LM_ERR("Failed to encode callid\n");
		return -1;
	}

	memcpy(new_callid.s,topo_hiding_prefix.s,topo_hiding_prefix.len);
	for (i=0;i<msg->callid->body.len;i++)
		msg->callid->body.s[i] ^= topo_hiding_seed.s[i%topo_hiding_seed.len]; 

	base64encode((unsigned char *)(new_callid.s+topo_hiding_prefix.len),
		     (unsigned char *)(msg->callid->body.s),msg->callid->body.len);

	/* reset the callid back to original value - some might still need it ( eg. post script )
	FIXME : use bigger buffer here ? mem vs cpu */
	for (i=0;i<msg->callid->body.len;i++)
		msg->callid->body.s[i] ^= topo_hiding_seed.s[i%topo_hiding_seed.len]; 

	del=del_lump(msg, msg->callid->body.s-msg->buf, msg->callid->body.len, HDR_CALLID_T);
	if (del==NULL) {               
		LM_ERR("Failed to delete old callid\n");
		pkg_free(new_callid.s);
		return -1;
	}

	if (insert_new_lump_after(del,new_callid.s,new_callid.len,HDR_CALLID_T)==NULL) {
		LM_ERR("Failed to insert new callid\n");
		pkg_free(new_callid.s);
		return -1;
	}

	return 0;
}
Пример #19
0
static int
clear_atnet(const int s, struct arguments *args)
{

	char *b64user;
	char message[BUFLEN];
        
	if(strlen(args->login) > 128) {
		ret_msg(NONE, "username is too long");
		return RET_ERROR;
	}
	memset(message,0,sizeof(message));
	
	b64user = (char *)malloc((2 * strlen(args->login) + 1));
	if(b64user == NULL) {
		ret_msg(PERR, "malloc() failed");
		return RET_WARNING;
	}
	(void)memset(b64user, 0, 2 * strlen(args->login) + 1);
        
	base64encode(args->login, b64user);
        
	{
		char buffer[1024];
                
		(void)snprintf(buffer, 1024,
                               " GET /DynDNS/clear.cgi HTTP/1.1\r\n"
                               "Host: %s\r\n"
                               "Authorization: Basic %s\r\n"
                               "User-Agent: %s %s - %s\r\n"
                               "Connection: close\r\n"
                               "Pragma: no-cache\r\n\r\n",
                               DYNDNSHOST, b64user, PNAME, VERSION, HOMEPAGE);
		(void)strncat(message, buffer, BUFLEN - 1 - strlen(message));
	}
	print_debug("\n\nMessage:"
		    "\n--------------------------------------\n"
		    "%s--------------------------------------\n\n",
                    message);
	
	if(write(s, message, strlen(message)) == -1) {
		ret_msg(PERR, "write() failed");
		return RET_WARNING;
	}
        
	free(b64user);
	return RET_OK;
        
}
Пример #20
0
	web_connection_base::web_connection_base(
		session_impl& ses
		, boost::weak_ptr<torrent> t
		, boost::shared_ptr<socket_type> s
		, tcp::endpoint const& remote
		, std::string const& url
		, policy::peer* peerinfo
		, std::string const& auth
		, web_seed_entry::headers_t const& extra_headers)
		: peer_connection(ses, t, s, remote, peerinfo)
		, m_parser(http_parser::dont_parse_chunks)
		, m_external_auth(auth)
		, m_extra_headers(extra_headers)
		, m_first_request(true)
		, m_ssl(false)
		, m_body_start(0)
	{
		INVARIANT_CHECK;

		// we only want left-over bandwidth
		set_priority(1);
		
		// since this is a web seed, change the timeout
		// according to the settings.
		set_timeout(ses.settings().urlseed_timeout);

		std::string protocol;
		error_code ec;
		boost::tie(protocol, m_basic_auth, m_host, m_port, m_path)
			= parse_url_components(url, ec);
		TORRENT_ASSERT(!ec);

		if (m_port == -1 && protocol == "http")
			m_port = 80;

#ifdef TORRENT_USE_OPENSSL
		if (protocol == "https")
		{
			m_ssl = true;
			if (m_port == -1) m_port = 443;
		}
#endif

		if (!m_basic_auth.empty())
			m_basic_auth = base64encode(m_basic_auth);

		m_server_string = "URL seed @ ";
		m_server_string += m_host;
	}
Пример #21
0
const char* websocket_derive_key(const char* key){
	static char hex[512] = {0,};
	static char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

	/* compute concaternated hash */
	sha1_t sha = sha1_new();
	sha1_update(sha, key, strlen(key));
	sha1_update(sha, magic, strlen(magic));

	/* encode hash as base64 */
	base64encode(sha1_hash_bytes(sha), 20, hex, sizeof(hex));

	sha1_free(sha);
	return hex;
}
char* pckcnt_to_spade_json(struct pckcnt_struct* n) {
  char* cntenc;
  NODE_START("Entity");
  cntenc = malloc( encode64Bound(n->length) );
  base64encode(n->content, n->length, cntenc, encode64Bound(n->length));
  __add_string_attribute("content", cntenc, true);
  free(cntenc);
  __add_uint32_attribute("length", n->length, true);
  if(n->truncated==PROV_TRUNCATED)
    __add_string_attribute("truncated", "true", true);
  else
    __add_string_attribute("truncated", "false", true);
  NODE_END();
  return buffer;
}
// Encode the message in net_scratchpad and start the send process
void net_msg_encode_puts(void)
  {
  int k;
  char code;

  if (net_state == NET_STATE_DIAGMODE)
    {
    net_puts_ram(net_scratchpad);
    }
  else
    {
    if ((ptokenmade==1)&&
        (net_scratchpad[5]!='E')&&
        (net_scratchpad[5]!='A')&&
        (net_scratchpad[5]!='a')&&
        (net_scratchpad[5]!='g')&&
        (net_scratchpad[5]!='P'))
      {
      // We must convert the message to a paranoid one...
      // The message in net_scratchpad is of the form MP-0 X...
      // Where X is the code and ... is the (optional) data
      // Let's rebuild it in the net_msg_scratchpad...
      code = net_scratchpad[5];
      strcpy(net_msg_scratchpad,net_scratchpad+6);

      // Paranoid encrypt the message part of the transaction
      RC4_setup(&pm_crypto1, &pm_crypto2, pdigest, MD5_SIZE);
      for (k=0;k<1024;k++)
        {
        net_scratchpad[0] = 0;
        RC4_crypt(&pm_crypto1, &pm_crypto2, net_scratchpad, 1);
        }
      k=strlen(net_msg_scratchpad);
      RC4_crypt(&pm_crypto1, &pm_crypto2, net_msg_scratchpad, k);

      strcpypgm2ram(net_scratchpad,(char const rom far*)"MP-0 EM");
      net_scratchpad[7] = code;
      base64encode(net_msg_scratchpad,k,net_scratchpad+8);
      // The messdage is now in paranoid mode...
      }

    k=strlen(net_scratchpad);
    RC4_crypt(&tx_crypto1, &tx_crypto2, net_scratchpad, k);
    base64encodesend(net_scratchpad,k);
    }

  net_puts_rom("\r\n");
  }
Пример #24
0
char *generate_answer(stralloc *answer, uint32 uid, 
		      char *lip, uint16 lport, char *rip, uint16 rport)
{
  char *problem = "ok";
  char *x;
  char buf[5];
  stralloc out = {0};
  stralloc tmp = {0};
  stralloc key = {0};

  /* get key from enviroment */
  x = env_get("KEY");
  if (!x)
    {
      problem = "$KEY not set";
      strerr_warn1("didentd warning: $KEY not set using 'snakeoilkey'", NULL);
      x = "snakeoilkey";
    }
  
  /* initialize rijndael with $KEY */
  stralloc_copys(&key, x);
  txtparse(&key);
  pad(&key, 32);
  rijndaelKeySched(6, 8, key.s);
    
  /* build answer */
  stralloc_cats(answer, " : USERID : OTHER : ");

  uint32_pack(buf, uid); stralloc_catb(&tmp, buf, 4);
  uint16_pack(buf, lport); stralloc_catb(&tmp, buf, 2);
  uint16_pack(buf, rport); stralloc_catb(&tmp, buf, 2);
  uint32_pack(buf, time(NULL)); stralloc_catb(&tmp, buf, 4);
  stralloc_catb(&tmp, lip, 4);
  stralloc_catb(&tmp, rip, 8);

  /* encrypt last part of answer with rijndael */
  rijndaelEncrypt(tmp.s);
  
  stralloc_readyplus(&out, 32);
  base64encode(out.s, tmp.s, 24);
  
  stralloc_catb(answer, out.s, 32); 
  stralloc_cats(answer, "\r\n");
  stralloc_0(answer);
  
  return problem;
}
Пример #25
0
	web_connection_base::web_connection_base(
		aux::session_interface& ses
		, aux::session_settings& sett
		, buffer_allocator_interface& allocator
		, disk_interface& disk_thread
		, io_service& ios
		, boost::weak_ptr<torrent> t
		, boost::shared_ptr<socket_type> s
		, tcp::endpoint const& remote
		, std::string const& url
		, policy::peer* peerinfo
		, std::string const& auth
		, web_seed_entry::headers_t const& extra_headers)
		: peer_connection(ses, sett, allocator, disk_thread, ios
			, t, s, remote, peerinfo)
		, m_parser(http_parser::dont_parse_chunks)
		, m_external_auth(auth)
		, m_extra_headers(extra_headers)
		, m_first_request(true)
		, m_ssl(false)
		, m_body_start(0)
	{
		INVARIANT_CHECK;

		// we only want left-over bandwidth
		// TODO: introduce a web-seed default class which has a low download priority
		
		// since this is a web seed, change the timeout
		// according to the settings.
		set_timeout(m_settings.get_int(settings_pack::urlseed_timeout));

		std::string protocol;
		error_code ec;
		boost::tie(protocol, m_basic_auth, m_host, m_port, m_path)
			= parse_url_components(url, ec);
		TORRENT_ASSERT(!ec);

#ifdef TORRENT_USE_OPENSSL
		if (protocol == "https") m_ssl = true;
#endif

		if (!m_basic_auth.empty())
			m_basic_auth = base64encode(m_basic_auth);

		m_server_string = "URL seed @ ";
		m_server_string += m_host;
	}
Пример #26
0
static int pv_topo_callee_callid(struct sip_msg *msg, pv_param_t *param, pv_value_t *res)
{
	struct dlg_cell *dlg;
	int req_len = 0,i;
	char *p;

	if(res==NULL)
		return -1;

	if ( (dlg=dlg_api.get_dlg())==NULL || 
	(!dlg_api.is_mod_flag_set(dlg,TOPOH_HIDE_CALLID))) {
		return pv_get_null( msg, param, res);
	}


	req_len = calc_base64_encode_len(dlg->callid.len) + topo_hiding_prefix.len;

	if (req_len*2 > callid_buf_len) {
		callid_buf = pkg_realloc(callid_buf,req_len*2);
		if (callid_buf == NULL) {
			LM_ERR("No more pkg\n");
			return pv_get_null( msg, param, res);
		}

		callid_buf_len = req_len*2;
	}

	memcpy(callid_buf+req_len,topo_hiding_prefix.s,topo_hiding_prefix.len);
	for (i=0;i<dlg->callid.len;i++)
		callid_buf[i] = dlg->callid.s[i] ^ topo_hiding_seed.s[i%topo_hiding_seed.len];

	base64encode((unsigned char *)(callid_buf+topo_hiding_prefix.len+req_len),
		     (unsigned char *)(callid_buf),dlg->callid.len);

	p = callid_buf+ 2*req_len - 1;
	while (*p == '=') {
		*p = '-';
		p--;
	}

	res->rs.s = callid_buf+req_len;
	res->rs.len = req_len;
	res->flags = PV_VAL_STR;

	return 0;
}
Пример #27
0
	web_connection_base::web_connection_base(
		peer_connection_args const& pack
		, web_seed_t& web)
		: peer_connection(pack)
		, m_first_request(true)
		, m_ssl(false)
		, m_external_auth(web.auth)
		, m_extra_headers(web.extra_headers)
		, m_parser(http_parser::dont_parse_chunks)
		, m_body_start(0)
	{
		TORRENT_ASSERT(&web.peer_info == pack.peerinfo);
		// when going through a proxy, we don't necessarily have an endpoint here,
		// since the proxy might be resolving the hostname, not us
		TORRENT_ASSERT(web.endpoints.empty() || web.endpoints.front() == pack.endp);

		INVARIANT_CHECK;

		TORRENT_ASSERT(is_outgoing());

		// we only want left-over bandwidth
		// TODO: introduce a web-seed default class which has a low download priority

		std::string protocol;
		error_code ec;
		boost::tie(protocol, m_basic_auth, m_host, m_port, m_path)
			= parse_url_components(web.url, ec);
		TORRENT_ASSERT(!ec);

		if (m_port == -1 && protocol == "http")
			m_port = 80;

#ifdef TORRENT_USE_OPENSSL
		if (protocol == "https")
		{
			m_ssl = true;
			if (m_port == -1) m_port = 443;
		}
#endif

		if (!m_basic_auth.empty())
			m_basic_auth = base64encode(m_basic_auth);

		m_server_string = "URL seed @ ";
		m_server_string += m_host;
	}
Пример #28
0
static void handle_auth_plain_response(str* line, ssize_t offset)
{
  int start;
  int end;

  saw_auth_plain = 0;
  if (base64decode(line->s + offset, line->len - offset, &tmpstr)) {
    /* tmpstr should now contain "AUTHORIZATION\0AUTHENTICATION\0PASSWORD" */
    if ((start = str_findfirst(&tmpstr, NUL)) >= 0
	&& (end = str_findnext(&tmpstr, NUL, ++start)) > start) {
      make_username(tmpstr.s + start, end - start, "AUTH PLAIN ");
      str_splice(&tmpstr, start, end - start, &username);
      line->len = offset;
      base64encode(tmpstr.s, tmpstr.len, line);
      str_catb(line, CRLF, 2);
    }
  }
}
Пример #29
0
/*
 *	CSR stands for certificate request, which is sent by the client (or gateway) in order to provide the info needed by the AAAS to generate the certificate.
 *
 *		CSR info:
 *				- id: requester identification
 *				- cname: common name
 *				- time: date on which the csr has been generated
 *				- auth_key: key used in mutual authentication (SMQV)
 *				- token_key: key used to sign access token (MSS)
 *				- csr_signature: CSR signature under token_key
 *
 */
void generate_csr(unsigned int id, char *cname, unsigned char auth_key[SMQV_PKEY_SIZE], unsigned char token_key[MSS_PKEY_SIZE], unsigned char mss_skey[MSS_SKEY_SIZE], char csr[CSR_MAX_SIZE]) {
	// append byte array of (id || cname || time || auth_key || token_key)
	unsigned int index = 0;
	unsigned char buffer[CSR_MAX_SIZE];
	memset(buffer, 0, CSR_MAX_SIZE);
	memset(csr, 0, CSR_MAX_SIZE);
	char time[TIME_BUFFER_SIZE];
	now(&time);
	index += csr_append_info(buffer, id, cname, time, auth_key, token_key);

	// sign (id || cname || time || auth_key || token_key)
	sponge_state sponge;
        unsigned char digest[2 * MSS_SEC_LVL];

        sponge_hash(buffer, index, digest, 2 * MSS_SEC_LVL);
	memcpy(buffer + index, mss_sign(mss_skey, digest), MSS_SIGNATURE_SIZE);
	index += MSS_SIGNATURE_SIZE;

	base64encode(buffer, index, csr, CSR_MAX_SIZE);
}
Пример #30
0
void http_connection::get(std::string const& url, time_duration timeout
	, bool handle_redirect)
{
	m_redirect = handle_redirect;
	std::string protocol;
	std::string auth;
	std::string hostname;
	std::string path;
	int port;
	boost::tie(protocol, auth, hostname, port, path) = parse_url_components(url);
	std::stringstream headers;
	headers << "GET " << path << " HTTP/1.0\r\n"
		"Host:" << hostname <<
		"\r\nConnection: close\r\n";
	if (!auth.empty())
		headers << "Authorization: Basic " << base64encode(auth) << "\r\n";
	headers << "\r\n";
	sendbuffer = headers.str();
	start(hostname, boost::lexical_cast<std::string>(port), timeout);
}