Example #1
0
int messagediffieHellmanClientParam(
	char *sessionId, char* seqNumber,
	char* g, char* p, char* pub_key,
	char* message, int messageMaxSize)
{
    int result;
    xmlChar *s;
	xmlDocPtr doc = NULL;       /* document pointer */
    xmlNodePtr root_node = NULL;/* node pointers */

	int messageSize;
	char *gBase64, *pBase64, *pub_keyBase64;

	gBase64 = b64encode((unsigned char*) g, strlen(g) + 1);
	pBase64 = b64encode((unsigned char*) p, strlen(p) + 1);
	pub_keyBase64 = b64encode((unsigned char*) pub_key, strlen(pub_key) + 1);


    LIBXML_TEST_VERSION;

	doc = xmlNewDoc(BAD_CAST "1.0");
    root_node = xmlNewNode(NULL, BAD_CAST "diffie-hellman");
    xmlDocSetRootElement(doc, root_node);

    xmlSetProp(root_node, BAD_CAST "seqNumber",BAD_CAST seqNumber);
    xmlSetProp(root_node, BAD_CAST "session", BAD_CAST sessionId);
    xmlSetProp(root_node, BAD_CAST "type", BAD_CAST "clientParam");

    xmlNewChild(root_node, NULL, BAD_CAST "g",BAD_CAST gBase64);
    xmlNewChild(root_node, NULL, BAD_CAST "p",BAD_CAST pBase64);
    xmlNewChild(root_node, NULL, BAD_CAST "A",BAD_CAST pub_keyBase64);

    xmlDocDumpMemory(doc, &s, &messageSize);

    if( messageSize + 1 <= messageMaxSize)
    {
        strcpy((char *) message, (char *) s);
        result = messageSize + 1;
    }       
    else
        result = -1;

    free(gBase64);
    free(pBase64);
    free(pub_keyBase64);
    xmlFree(s);

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return result;
}
Example #2
0
int
messageCreateEncryptedMessage(
            char *sessionId, 
            unsigned char *iv, int ivSize,
            char *seqNumber,int seqNumberSize,
            unsigned char *encMessage, int encMessageSize,
            char *message, int messageMaxSize)
{
    xmlChar *s;
    xmlDocPtr doc = NULL;       /* document pointer */
    xmlNodePtr root_node = NULL;/* node pointers */
    int result;
    int messageSize;
    char *ivBase64, *encBase64, *seqBase64;

    seqBase64 = b64encode((unsigned char *)seqNumber, seqNumberSize);
    ivBase64 = b64encode(iv, ivSize);
    encBase64 = b64encode(encMessage, encMessageSize);

    LIBXML_TEST_VERSION;

    doc = xmlNewDoc(BAD_CAST "1.0");
    root_node = xmlNewNode(NULL, BAD_CAST "encryptedMessage");
    xmlDocSetRootElement(doc, root_node);

    xmlNodeSetContent(root_node, BAD_CAST encBase64);

    xmlSetProp(root_node, BAD_CAST "seqNumber",BAD_CAST seqBase64);
    xmlSetProp(root_node, BAD_CAST "session", BAD_CAST sessionId);
    xmlSetProp(root_node, BAD_CAST "iv", BAD_CAST ivBase64);

    xmlDocDumpMemory(doc, &s, &messageSize);

    if( messageSize + 1 <= messageMaxSize)
    {
        strcpy((char *) message, (char *) s);
        result = messageSize + 1;
    }       
    else
        result = -1;

    free(seqBase64);
    free(ivBase64);
    free(encBase64);
    xmlFree(s);

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return result;
}
Example #3
0
static int32_t _ghttp_http_get(struct s_client *client, uint32_t hash, int odd)
{
  uchar req[128], auth[64];
  char* encauth = NULL;
  int32_t ret;
  s_ghttp* context = (s_ghttp*)client->ghttp;

  if(!context->session_id && strlen(client->reader->r_usr) > 0) {
    cs_debug_mask(D_CLIENT, "%s: username specified and no existing session, adding basic auth", client->reader->label);
    ret = snprintf((char*)auth, sizeof(auth), "%s:%s", client->reader->r_usr, client->reader->r_pwd);
    ret = b64encode((char*)auth, ret, &encauth);
  }

  if(encauth) { // basic auth login
    ret = snprintf((char*)req, sizeof(req), "GET /api/c/%d/%x HTTP/1.1\r\nHost: %s\r\nAuthorization: Basic %s\r\n\r\n", odd ? 81 : 80, hash, client->reader->device, encauth);
  } else {
    if(context->session_id) { // session exists
      ret = snprintf((char*)req, sizeof(req), "GET /api/c/%s/%d/%x HTTP/1.1\r\nHost: %s\r\n\r\n", context->session_id, odd ? 81 : 80, hash, client->reader->device);
    } else { // no credentials configured, assume no session required
      ret = snprintf((char*)req, sizeof(req), "GET /api/c/%d/%x HTTP/1.1\r\nHost: %s\r\n\r\n", odd ? 81 : 80, hash, client->reader->device);
    }
  }

  ret = ghttp_send(client, req, ret);

  return ret;
}
Example #4
0
static int32_t _ghttp_post_ecmdata(struct s_client *client, ECM_REQUEST* er)
{
  uchar req[640], auth[64];
  uchar* end;
  char* encauth = NULL;
  int32_t ret;
  s_ghttp* context = (s_ghttp*)client->ghttp;

  if(!context->session_id && strlen(client->reader->r_usr) > 0) {
    cs_debug_mask(D_CLIENT, "%s: username specified and no existing session, adding basic auth", client->reader->label);
    ret = snprintf((char*)auth, sizeof(auth), "%s:%s", client->reader->r_usr, client->reader->r_pwd);
    ret = b64encode((char*)auth, ret, &encauth);
  }

  if(encauth) { // basic auth login
    ret = snprintf((char*)req, sizeof(req), "POST /api/e/%x/%x/%x/%x/%x/%x HTTP/1.1\r\nHost: %s\r\nAuthorization: Basic %s\r\nContent-Length: %d\r\n\r\n", er->onid, er->tsid, er->pid, er->srvid, er->caid, er->prid, client->reader->device, encauth, er->ecmlen);
  } else {
    if(context->session_id) { // session exists
      ret = snprintf((char*)req, sizeof(req), "POST /api/e/%s/%x/%x/%x/%x/%x/%x HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\n\r\n", context->session_id, er->onid, er->tsid, er->pid, er->srvid, er->caid, er->prid, client->reader->device, er->ecmlen);
    } else { // no credentials configured, assume no session required
      ret = snprintf((char*)req, sizeof(req), "POST /api/e/%x/%x/%x/%x/%x/%x HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\n\r\n", er->onid, er->tsid, er->pid, er->srvid, er->caid, er->prid, client->reader->device, er->ecmlen);
    }
  }
  end = req + ret;
  memcpy(end, er->ecm, er->ecmlen);
  
  cs_debug_mask(D_CLIENT, "%s: sending full ecm - /api/e/%x/%x/%x/%x/%x/%x", client->reader->label, er->onid, er->tsid, er->pid, er->srvid, er->caid, er->prid);

  ret = ghttp_send(client, req, ret + er->ecmlen);

  return ret;
}
Example #5
0
int
main(int argc, char* argv[]) {
  int i;
  for(i = 1; i < argc; ++i) {
    b64encode(argv[i], str_len(argv[i]));
  }
  if(argc < 2) {
    char src[1024];
    int len;
    while((len = read(0, src, sizeof(src) - 1)) > 0) {
      if(len == -1)
        return (1);
      b64encode(src, len);
    }
  }
  return 0;
}
Example #6
0
char * rpmPubkeyBase64(rpmPubkey key)
{
    char *enc = NULL;

    if (key) {
	enc = b64encode(key->pkt, key->pktlen, -1);
    }
    return enc;
}
Example #7
0
static char *
pdkim_encode_base64(blob * b)
{
char * ret;
int old_pool = store_pool;

store_pool = POOL_PERM;
ret = CS b64encode(b->data, b->len);
store_pool = old_pool;
return ret;
}
Example #8
0
int
messageCreateClientAuthentication(
        unsigned char *masterkeySignature, int signatureSize,
        char *name, int nameSize,
        char *numBI, int numBISize,
        char *userName, int userNameSize,
        char *hostName, int hostNameSize,
        char *message, int messageMaxSize)
{
    xmlChar *s;
    xmlDocPtr doc = NULL;       /* document pointer */
    xmlNodePtr root_node = NULL;/* node pointers */
    int result;
    int messageSize;
    char *sigBase64;

    sigBase64 = b64encode(masterkeySignature, signatureSize);

    LIBXML_TEST_VERSION;

    doc = xmlNewDoc(BAD_CAST "1.0");
    root_node = xmlNewNode(NULL, BAD_CAST "authentication");
    xmlDocSetRootElement(doc, root_node);

    xmlSetProp(root_node, BAD_CAST "type", BAD_CAST "clientAuthentication");

    xmlNewChild(root_node, NULL, BAD_CAST "secretSignature",BAD_CAST sigBase64);

    root_node = xmlNewChild(root_node, NULL,BAD_CAST "clientInfo", NULL);

    xmlNewTextChild(root_node, NULL, BAD_CAST "nBI",BAD_CAST numBI);
    xmlNewTextChild(root_node, NULL, BAD_CAST "name",BAD_CAST name);
    xmlNewTextChild(root_node, NULL, BAD_CAST "userName",BAD_CAST userName);
    xmlNewTextChild(root_node, NULL, BAD_CAST "hostName",BAD_CAST hostName);
    

    xmlDocDumpMemory(doc, &s, &messageSize);

    if( messageSize + 1 <= messageMaxSize)
    {
        strcpy((char *) message, (char *) s);
        result = messageSize + 1;
    }       
    else
        result = -1;
    free(sigBase64);
   xmlFree(s);
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return result;
}
CFDictionaryRef
SecWrapRecoveryPasswordWithAnswers(CFStringRef password, CFArrayRef questions, CFArrayRef answers)
{
    uint32_t 	vers = 1;
    CFDataRef	iv;
	CFDataRef	wrappedPassword;
	CFMutableDictionaryRef retval = NULL;
	CFLocaleRef theLocale = CFLocaleCopyCurrent();
    CFStringRef theLocaleString = CFLocaleGetIdentifier(theLocale);
    
    CFIndex ix, limit;
    
    if (!password || !questions || !answers)
		return NULL;
    
    limit = CFArrayGetCount(answers);
    if (limit != CFArrayGetCount(questions))
		return NULL; // Error
	CFTypeRef chkval;
    for (ix=0; ix<limit; ix++)
	{
		chkval =  CFArrayGetValueAtIndex(answers, ix);
        if (!chkval || CFGetTypeID(chkval)!=CFStringGetTypeID() || CFEqual((CFStringRef)chkval, CFSTR(""))) 
			return NULL;
        chkval = CFArrayGetValueAtIndex(questions, ix);
        if (!chkval || CFGetTypeID(chkval)!=CFStringGetTypeID() || CFEqual((CFStringRef)chkval, CFSTR(""))) 
			return NULL;
    }
	
    iv = createIVFromPassword(password);
    
	SecKeyRef wrapKey = secDeriveKeyFromAnswers(answers, theLocale);
	
    if((wrappedPassword = encryptString(wrapKey, iv, password)) != NULL) {
        retval = CFDictionaryCreateMutable(kCFAllocatorDefault, 5, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		CFDictionaryAddValue(retval, kSecRecVersionNumber, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vers));
		CFDictionaryAddValue(retval, kSecRecQuestions, questions);
		CFDictionaryAddValue(retval, kSecRecLocale, theLocaleString);
		CFDictionaryAddValue(retval, kSecRecIV, b64encode(iv));
		CFDictionaryAddValue(retval, kSecRecWrappedPassword, wrappedPassword);
	}
	
 	if(wrappedPassword) CFRelease(wrappedPassword);
 	CFRelease(iv);
 	CFRelease(wrapKey);
 	CFRelease(theLocale);
 	CFRelease(theLocaleString);
	
  	return retval;
}
/** encode a message for sending via the f2f IM channel in the
 * sendIMBuffer ignore localpeerids */
static F2FError encodeIMMessage( const char * message,
		const F2FSize size, F2FAdapterReceiveMessage *dest )
{
	F2FSize currentsize, newsize;

	/* Encode message for sending in f2f framework */
	strcpy( dest->buffer, F2FMessageMark ); /* header */
	currentsize = F2FMessageMarkLength;
	newsize = b64encode( message, dest->buffer + currentsize,
				size, F2FMaxEncodedMessageSize - currentsize );
	if(newsize == 0) return F2FErrMessageTooLong;
	currentsize += newsize;	/* prepare sending of the new message */
	dest->buffersize = currentsize;
	return F2FErrOK;
}
Example #11
0
static char *_ghttp_basic_auth(struct s_client *client)
{
	uchar auth[64];
	char *encauth = NULL;
	int32_t ret;
	s_ghttp *context = (s_ghttp *)client->ghttp;

	if(!context->session_id && strlen(client->reader->r_usr) > 0)
	{
		cs_debug_mask(D_CLIENT, "%s: username specified and no existing session, adding basic auth", client->reader->label);
		ret = snprintf((char *)auth, sizeof(auth), "%s:%s", client->reader->r_usr, client->reader->r_pwd);
		ret = b64encode((char *)auth, ret, &encauth);
	}
	return encauth;
}
Example #12
0
char *aes_encrypt(char *str_plaintext, int *ptr_int_plaintext_length) {
	DEFINE_VAR_ALL(str_output);
	char *str_return = NULL;
	
	//initialize
	set_aes_key_iv();
	AES_KEY AESkey;
	//int int_new_length = *ptr_int_plaintext_length;
	*ptr_int_plaintext_length = ((*ptr_int_plaintext_length + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
	int int_aes_length = *ptr_int_plaintext_length;
	//*ptr_int_plaintext_length = (*ptr_int_plaintext_length) - ((*ptr_int_plaintext_length) % 16) + 16;
	ERROR_SALLOC(str_output, int_aes_length + 1);
    memset(str_output, 0, int_aes_length);
	
	AES_set_encrypt_key((const unsigned char *) str_global_aes_key, 256, &AESkey);
	
	AES_cbc_encrypt((const unsigned char *)str_plaintext, (unsigned char *)str_output,
		int_aes_length, &AESkey, (unsigned char *)str_global_aes_iv, AES_ENCRYPT);
	/*
	AES_cbc_encrypt((const unsigned char *)str_plaintext, (unsigned char *)str_output,
		int_new_length, &AESkey, (unsigned char *)str_global_aes_iv, AES_ENCRYPT);
	*/
	
	//int int_original_length = int_new_length;
	//int_new_length = (int_new_length & 0xFFFFFFF0) + ((int_new_length & 0x0F) ? 16 : 0);
	//*(str_output + int_new_length) = (int_new_length - int_original_length);
	
	//printf("str_output: %s\n", str_output);
	
	//encrypt
	//aes_setkey_enc(&aes, (unsigned char *)key, 256);
	//aes_crypt_cbc(&aes, AES_ENCRYPT, *plaintext_len, (unsigned char *)iv, (unsigned char *)plaintext, (unsigned char *)str_output);
	
	//base64
	str_return = b64encode(str_output, ptr_int_plaintext_length);
	
	SFREE_ALL();
	
	return str_return;
error:
	SFREE_ALL();
	
	SFREE_PWORD(str_return);
	return NULL;
}
Example #13
0
int
auth_get_data(uschar **aptr, uschar *challenge, int challen)
{
int c;
int p = 0;
smtp_printf("334 %s\r\n", b64encode(challenge, challen));
while ((c = receive_getc()) != '\n' && c != EOF)
  {
  if (p >= big_buffer_size - 1) return BAD64;
  big_buffer[p++] = c;
  }
if (p > 0 && big_buffer[p-1] == '\r') p--;
big_buffer[p] = 0;
DEBUG(D_receive) debug_printf("SMTP<< %s\n", big_buffer);
if (Ustrcmp(big_buffer, "*") == 0) return CANCELLED;
*aptr = big_buffer;
return OK;
}
Example #14
0
File: tkey.c Project: avokhmin/RPM5
static int doit(const char *sig, pgpDig dig, int printing)
{
    const char *s, *t;
    unsigned char * dec;
    size_t declen;
    char * enc;
    int rc;
    int i;

if (_debug)
fprintf(stderr, "*** before\n%s\n", sig);

    if ((rc = b64decode(sig, (void **)&dec, &declen)) != 0) {
	fprintf(stderr, "*** b64decode returns %d\n", rc);
	return rc;
    }
    rc = pgpPrtPkts(dec, declen, dig, printing);
    if (rc < 0) {
	fprintf(stderr, "*** pgpPrtPkts returns %d\n", rc);
	return rc;
    }

    if ((enc = b64encode(dec, declen)) == NULL) {
	fprintf(stderr, "*** b64encode failed\n");
	return rc;
    }
    dec = _free(dec);

if (_debug)
fprintf(stderr, "***  after\n%s\n", enc);

rc = 0;
for (i = 0, s = sig, t = enc; *s & *t; i++, s++, t++) {
    if (*s == '\n') s++;
    if (*t == '\n') t++;
    if (*s == *t) continue;
if (_debug)
fprintf(stderr, "??? %5d %02x != %02x '%c' != '%c'\n", i, (*s & 0xff), (*t & 0xff), *s, *t);
    rc = 5;
}
    enc = _free(enc);

    return rc;
}
Example #15
0
static RC_TYPE get_encoded_user_passwd(DYN_DNS_CLIENT *p_self)
{
	RC_TYPE rc = RC_OK;
	const char* format = "%s:%s";
	char *p_tmp_buff = NULL;
	int size = strlen(p_self->info.credentials.my_password) + 
			   strlen(p_self->info.credentials.my_username) + 
			   strlen(format) + 1;
	int actual_len;

	do
	{
		p_tmp_buff = (char *) malloc(size);
		if (p_tmp_buff == NULL)
		{
			rc = RC_OUT_OF_MEMORY;
			break;
		}

		actual_len = sprintf(p_tmp_buff, format, 
				p_self->info.credentials.my_username, 
				p_self->info.credentials.my_password);
		if (actual_len >= size)
		{
			rc = RC_OUT_BUFFER_OVERFLOW;
			break;
		}

		/*encode*/
		p_self->info.credentials.p_enc_usr_passwd_buffer = b64encode(p_tmp_buff);	
		p_self->info.credentials.encoded = 
			(p_self->info.credentials.p_enc_usr_passwd_buffer != NULL);
		p_self->info.credentials.size = strlen(p_self->info.credentials.p_enc_usr_passwd_buffer);
	}
	while(0);

	if (p_tmp_buff != NULL)
	{
		free(p_tmp_buff);
	}
	return rc;	
}
bool WSClientParser::GetHandShakeRespond(char** buffer, int& len) {
	if( mState == WSClientState_Handshake ) {
		mState = WSClientState_Data;

		char input[256] = "";
		unsigned char output[SHA1_HASH_SIZE] = "";
		char b64[256] = "";

		snprintf(input, sizeof(input), "%s%s", mWebSocketKey, WEBSOCKET_GUID);
		sha1_digest(output, input);
		b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64));

		char* temp = switch_core_sprintf(
				mpPool,
				"HTTP/1.1 101 Switching Protocols\r\n"
				"Upgrade: websocket\r\n"
				"Connection: Upgrade\r\n"
				"Sec-WebSocket-Accept: %s\r\n"
				"\r\n",
				b64
				);

		*buffer = temp;
		len = strlen(temp);

		switch_log_printf(
				SWITCH_CHANNEL_UUID_LOG(this->uuid),
				SWITCH_LOG_INFO,
				"WSClientParser::GetHandShakeRespond( "
				"this : %p, "
				"len : %d, "
				"buffer : \n%s\n"
				") \n",
				this,
				len,
				*buffer
				);

		return true;
	}
	return false;
}
Example #17
0
/*****************************************************
*  Certificate operator routines
*****************************************************/
uschar *
tls_cert_der_b64(void * cert)
{
    size_t len = 0;
    uschar * cp = NULL;
    int fail;

    if (  (fail = gnutls_x509_crt_export((gnutls_x509_crt_t)cert,
                                         GNUTLS_X509_FMT_DER, cp, &len)) != GNUTLS_E_SHORT_MEMORY_BUFFER
            || !(cp = store_get((int)len))
            || (fail = gnutls_x509_crt_export((gnutls_x509_crt_t)cert,
                       GNUTLS_X509_FMT_DER, cp, &len))
       )
    {
        log_write(0, LOG_MAIN, "TLS error in certificate export: %s",
                  gnutls_strerror(fail));
        return NULL;
    }
    return b64encode(cp, (int)len);
}
Example #18
0
int testBase64() {
    ASSERT(b64encode("any") == std::string("YW55"));
    ASSERT(b64encode("anyany") == std::string("YW55YW55"));
    ASSERT(b64encode("a") == std::string("YQ=="));
    ASSERT(b64encode("aa") == std::string("YWE="));
    ASSERT(b64encode("aaa") == std::string("YWFh"));
    ASSERT(b64encode("aaaa") == std::string("YWFhYQ=="));
    ASSERT(b64encode("aaaaa") == std::string("YWFhYWE="));
    
    ASSERT(std::string("any") == b64decode_s("YW55"));
    ASSERT(std::string("anyany") == b64decode_s("YW55YW55"));
    ASSERT(std::string("a") == b64decode_s("YQ=="));
    ASSERT(std::string("aa") == b64decode_s("YWE="));
    ASSERT(std::string("aaa") == b64decode_s("YWFh"));
    ASSERT(std::string("aaaa") == b64decode_s("YWFhYQ=="));
    ASSERT(std::string("aaaaa") == b64decode_s("YWFhYWE="));
    
    ASSERT(std::string("any") == b64decode_s("YW55\x5"));
    
    
    return 0;
}
Example #19
0
int main( int argc, char *argv[] )
{
	std::string inputfile  = "";
	std::string outputfile = "";
	std::string passphrase = "";
	std::string publicKey  = "";
	bool encrypt = false,
	     decrypt = false,
	     keygen  = false;

	// set up command line options and
	// check for help requests and usage errors
	po::variables_map var_map;

	try
	{
		init_program_options(argc, argv, &var_map);
	}
	catch( po::multiple_occurrences m )
	{
		std::cerr << "Error: Please use each options at most once."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}
	catch( ... )
	{
		std::cerr << "Error: unknown error in command line options."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}

	// no options -> print usage message
	if( argc == 1 )
	{
		print_usage( argv[0] );
		exit( 1 );
	}

	// check command line options
	if( var_map.count("test") > 0 )
	{
		exit( run_tests() );
	}

	encrypt = (var_map.count("encrypt")    > 0);
	decrypt = (var_map.count("decrypt")    > 0);
	keygen  = (var_map.count("create-key") > 0);

	// check that the user only request one out of decrypt/encrypt/keygen
	if( (int)decrypt + (int)encrypt + (int)keygen > 1 )
	{
		std::cerr << "You need to chose one of encrypt, decrypt and key-gen."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}

	if (var_map.count("pass")   > 0) passphrase = var_map["pass"].as<std::string>();
	if (var_map.count("input")  > 0) inputfile  = var_map["input"].as<std::string>();
	if (var_map.count("output") > 0) outputfile = var_map["output"].as<std::string>();
	if (var_map.count("key")    > 0) publicKey  = var_map["key"].as<std::string>();
	quiet = (var_map.count("quiet") > 0);

	// here comes the program logic
	if( keygen )
	{
		if( passphrase == "" )
			passphrase = prompt_password( "passphrase", true );
	
		uint8_t publicKey[32];
		if( generate_key( publicKey, passphrase ) )
			std::cerr << "Public key: " << b64encode( publicKey );
		else
			std::cerr << "Failed to generate public key" << std::endl;
	}
	else if( encrypt )
	{
		if( inputfile == "" && publicKey == "" )
		{
			std::cerr << "Error: Public key needs to be given on "
				  << "commandline when encrypting from stdin" << std::endl;
			exit( 1 );
		}

		if( publicKey == "" )
			publicKey  = prompt_password( "public key" );

		encryptFile( outputfile, inputfile, passphrase, publicKey );
	}
	else if( decrypt )
	{
		if( inputfile == "" && passphrase == "" )
		{
			std::cerr << "Error: passphrase needs to be given on "
				  << "commandline when decrypting from stdin" << std::endl;
			exit( 1 );
		}

		if( passphrase == "" )
			passphrase = prompt_password( "passphrase", true );

		decryptFile( outputfile, inputfile, passphrase );
	}
	else
	{
		print_usage( argv[0] );
		exit( 0 );
	}

	return 0;
}
Example #20
0
static ModuleRec newModule(const char *path, const char *name,
			   const char *types, uint32_t flags)
{
    ModuleRec mod;
    uint8_t *raw = NULL;
    ssize_t rawlen = 0;
    const char *buildDir = "%{_builddir}/%{?buildsubdir}/";

    if (!path) {
	rpmlog(RPMLOG_ERR, _("%%semodule requires a file path\n"));
	return NULL;
    }

    mod = xcalloc(1, sizeof(*mod));

    mod->path = rpmGenPath(buildDir, NULL, path);

    if ((rpmioSlurp(mod->path, &raw, &rawlen)) != 0 || raw == NULL) {
	rpmlog(RPMLOG_ERR, _("Failed to read  policy file: %s\n"),
	       mod->path);
	goto err;
    }

    mod->data = b64encode(raw, rawlen, -1);
    if (!mod->data) {
	rpmlog(RPMLOG_ERR, _("Failed to encode policy file: %s\n"),
	       mod->path);
	goto err;
    }

    if (name) {
	mod->name = xstrdup(name);
    } else {
	/* assume base name (minus extension) if name is not given */
	char *tmp = xstrdup(mod->path);
	char *bname = basename(tmp);
	char *end = strchr(bname, '.');
	if (end)
	    *end = '\0';
	if (strlen(bname) > 0) {
	    mod->name = xstrdup(bname);
	} else {
	    rpmlog(RPMLOG_ERR, _("Failed to determine a policy name: %s\n"),
		   mod->path);
	    _free(tmp);
	    goto err;
	}
	_free(tmp);
    }

    if (types) {
	mod->types = argvSplitString(types, ",", ARGV_SKIPEMPTY);
	argvSort(mod->types, NULL);
	if (argvSearch(mod->types, RPMPOL_TYPE_DEFAULT, NULL) && argvCount(mod->types) > 1) {
	    rpmlog(RPMLOG_WARNING, _("'%s' type given with other types in %%semodule %s. Compacting types to '%s'.\n"),
		   RPMPOL_TYPE_DEFAULT, mod->path, RPMPOL_TYPE_DEFAULT);
	    mod->types = argvFree(mod->types);
	    argvAdd(&mod->types, RPMPOL_TYPE_DEFAULT);
	}
    } else {
	argvAdd(&mod->types, RPMPOL_TYPE_DEFAULT);
    }

    mod->flags = flags;

    return mod;

  err:
    freeModule(mod);
    return NULL;
}
Example #21
0
int
auth_cram_md5_client(
  auth_instance *ablock,                 /* authenticator block */
  smtp_inblock *inblock,                 /* input connection */
  smtp_outblock *outblock,               /* output connection */
  int timeout,                           /* command timeout */
  uschar *buffer,                        /* for reading response */
  int buffsize)                          /* size of buffer */
{
auth_cram_md5_options_block *ob =
  (auth_cram_md5_options_block *)(ablock->options_block);
uschar *secret = expand_string(ob->client_secret);
uschar *name = expand_string(ob->client_name);
uschar *challenge, *p;
int i;
uschar digest[16];

/* If expansion of either the secret or the user name failed, return CANCELLED
or ERROR, as approriate. */

if (!secret || !name)
  {
  if (expand_string_forcedfail)
    {
    *buffer = 0;           /* No message */
    return CANCELLED;
    }
  string_format(buffer, buffsize, "expansion of \"%s\" failed in "
    "%s authenticator: %s",
    !secret ? ob->client_secret : ob->client_name,
    ablock->name, expand_string_message);
  return ERROR;
  }

/* Initiate the authentication exchange and read the challenge, which arrives
in base 64. */

if (smtp_write_command(outblock, FALSE, "AUTH %s\r\n", ablock->public_name) < 0)
  return FAIL_SEND;
if (!smtp_read_response(inblock, buffer, buffsize, '3', timeout))
  return FAIL;

if (b64decode(buffer + 4, &challenge) < 0)
  {
  string_format(buffer, buffsize, "bad base 64 string in challenge: %s",
    big_buffer + 4);
  return ERROR;
  }

/* Run the CRAM-MD5 algorithm on the secret and the challenge */

compute_cram_md5(secret, challenge, digest);

/* Create the response from the user name plus the CRAM-MD5 digest */

string_format(big_buffer, big_buffer_size - 36, "%s", name);
for (p = big_buffer; *p; ) p++;
*p++ = ' ';

for (i = 0; i < 16; i++)
  {
  sprintf(CS p, "%02x", digest[i]);
  p += 2;
  }

/* Send the response, in base 64, and check the result. The response is
in big_buffer, but b64encode() returns its result in working store,
so calling smtp_write_command(), which uses big_buffer, is OK. */

buffer[0] = 0;
if (smtp_write_command(outblock, FALSE, "%s\r\n", b64encode(big_buffer,
  p - big_buffer)) < 0) return FAIL_SEND;

return smtp_read_response(inblock, (uschar *)buffer, buffsize, '2', timeout)
  ? OK : FAIL;
}
void CurvedSalsaDialog::slot_generateKey( const QString &key )
{
	uint8_t pubKey[32];
	generate_key( pubKey, key.toStdString()  );
	pubKeyLine->setText( b64encode(pubKey).c_str() );
}
Example #23
0
int ws_handshake(wsh_t *wsh)
{
	char key[256] = "";
	char version[5] = "";
	char proto[256] = "";
	char proto_buf[384] = "";
	char input[256] = "";
	unsigned char output[SHA1_HASH_SIZE] = "";
	char b64[256] = "";
	char respond[512] = "";
	ssize_t bytes;
	char *p, *e = 0;

	if (wsh->sock == ws_sock_invalid) {
		return -3;
	}

	while((bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, wsh->buflen - wsh->datalen, WS_BLOCK)) > 0) {
		wsh->datalen += bytes;
		if (strstr(wsh->buffer, "\r\n\r\n") || strstr(wsh->buffer, "\n\n")) {
			break;
		}
	}

	if (bytes > sizeof(wsh->buffer) -1) {
		goto err;
	}

	*(wsh->buffer + wsh->datalen) = '\0';
	
	if (strncasecmp(wsh->buffer, "GET ", 4)) {
		goto err;
	}
	
	p = wsh->buffer + 4;
	
	e = strchr(p, ' ');
	if (!e) {
		goto err;
	}

	wsh->uri = malloc((e-p) + 1);
	strncpy(wsh->uri, p, e-p);
	*(wsh->uri + (e-p)) = '\0';

	cheezy_get_var(wsh->buffer, "Sec-WebSocket-Key", key, sizeof(key));
	cheezy_get_var(wsh->buffer, "Sec-WebSocket-Version", version, sizeof(version));
	cheezy_get_var(wsh->buffer, "Sec-WebSocket-Protocol", proto, sizeof(proto));
	
	if (!*key) {
		goto err;
	}
		
	snprintf(input, sizeof(input), "%s%s", key, WEBSOCKET_GUID);
	sha1_digest(output, input);
	b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64));

	if (*proto) {
		snprintf(proto_buf, sizeof(proto_buf), "Sec-WebSocket-Protocol: %s\r\n", proto);
	}

	snprintf(respond, sizeof(respond), 
			 "HTTP/1.1 101 Switching Protocols\r\n"
			 "Upgrade: websocket\r\n"
			 "Connection: Upgrade\r\n"
			 "Sec-WebSocket-Accept: %s\r\n"
			 "%s\r\n",
			 b64,
			 proto_buf);
	respond[511] = 0;

	if (ws_raw_write(wsh, respond, strlen(respond)) != (ssize_t)strlen(respond)) {
		goto err;
	}

	wsh->handshake = 1;

	return 0;

 err:

	if (!wsh->stay_open) {

		snprintf(respond, sizeof(respond), "HTTP/1.1 400 Bad Request\r\n"
				 "Sec-WebSocket-Version: 13\r\n\r\n");
		respond[511] = 0;

		ws_raw_write(wsh, respond, strlen(respond));

		ws_close(wsh, WS_NONE);
	}

	return -1;

}
Example #24
0
  result.resize(s.size() * 2 + 4);
  auto n = base64encode(s.data(), s.size(), &result[0], result.size());
  result.resize(n);
  return result;
}

static std::string b64decode(const std::string &s) {
  std::string result;
  result.resize(s.size() * 2 + 3);
  auto n = base64decode(s.data(), s.size(), &result[0], result.size());
  result.resize(n);
  return result;
}

TEST_CASE("encode strings", "[base64]") {
  REQUIRE(b64encode("fuxedo.io") == "ZnV4ZWRvLmlv");
  REQUIRE(b64encode("a") == "YQ==");
  REQUIRE(b64encode("ab") == "YWI=");
  REQUIRE(b64encode("abc") == "YWJj");
  REQUIRE(b64encode("") == "");
  REQUIRE(b64encode("abcdefghijklmnopqrstuvwxyz"
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    "0123456789!@#0^&*();:<>==. []{}") ==
          "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
          "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
          "Y3ODkhQCMwXiYqKCk7Ojw+PT0uIFtde30=");
}

TEST_CASE("decode strings", "[base64]") {
  REQUIRE(b64decode("ZnV4ZWRvLmlv") == "fuxedo.io");
  REQUIRE(b64decode("YQ==") == "a");
Example #25
0
File: pdkim.c Project: ytrezq/exim
static uschar *
pdkim_encode_base64(blob * b)
{
return b64encode(b->data, b->len);
}
Example #26
0
void VSTEffectDialog::OnSave(wxCommandEvent & evt)
{
   int i = mProgram->GetCurrentSelection();
   wxString fn;

   // Ask the user for the real name
   fn = FileSelector(_("Save VST Program As:"),
                     FileNames::DataDir(),
                     mProgram->GetValue() + wxT(".xml"),
                     wxT("xml"),
                     wxT("*.xml"),
                     wxFD_SAVE | wxFD_OVERWRITE_PROMPT | wxRESIZE_BORDER,
                     this);

   // User canceled...
   if (fn.IsEmpty()) {
      return;
   }

   XMLFileWriter xmlFile;

   // Create/Open the file
   xmlFile.Open(fn, wxT("wb"));

   xmlFile.StartTag(wxT("vstprogrampersistence"));
   xmlFile.WriteAttr(wxT("version"), wxT("1"));

   i = mEffect->callDispatcher(effGetVendorVersion, 0, 0, NULL, 0.0);
   xmlFile.StartTag(wxT("effect"));
   xmlFile.WriteAttr(wxT("name"), mEffect->GetEffectIdentifier());
   xmlFile.WriteAttr(wxT("version"), i);

   xmlFile.StartTag(wxT("program"));
   xmlFile.WriteAttr(wxT("name"), mProgram->GetValue());

   long clen = 0;
   if (mAEffect->flags & effFlagsProgramChunks) {
      void *chunk = NULL;

      clen = mEffect->callDispatcher(effGetChunk, 1, 0, &chunk, 0.0);
      if (clen != 0) {
         xmlFile.StartTag(wxT("chunk"));
         xmlFile.WriteSubTree(b64encode(chunk, clen) + wxT('\n'));
         xmlFile.EndTag(wxT("chunk"));
      }
   }

   if (clen == 0) {
      for (i = 0; i < mAEffect->numParams; i++) {
         xmlFile.StartTag(wxT("param"));

         xmlFile.WriteAttr(wxT("index"), i);
         xmlFile.WriteAttr(wxT("name"),
                           mEffect->GetString(effGetParamName, i));
         xmlFile.WriteAttr(wxT("value"),
                           wxString::Format(wxT("%f"),
                           mEffect->callGetParameter(i)));

         xmlFile.EndTag(wxT("param"));
      }
   }

   xmlFile.EndTag(wxT("program"));

   xmlFile.EndTag(wxT("effect"));

   xmlFile.EndTag(wxT("vstprogrampersistence"));

   // Close the file
   xmlFile.Close();
}