コード例 #1
0
ファイル: zio.c プロジェクト: trws/flux-core
char *zio_json_encode (void *data, int len, bool eof)
{
    char *json_str = NULL;
    char *s_data = NULL;
    json_t *o = NULL;
    int s_len;

    s_len = base64_encode_length (len);
    s_data = calloc (1, s_len);
    if (!s_data) {
        errno = ENOMEM;
        goto error;
    }
    if (base64_encode_block (s_data, &s_len, data, len) < 0) {
        errno = EINVAL;
        goto error;
    }
    if (!(o = json_pack ("{s:b s:s}", "eof", eof, "data", s_data))) {
        errno = ENOMEM;
        goto error;
    }
    if (!(json_str = json_dumps (o, 0))) {
        errno = ENOMEM;
        goto error;
    }
    free (s_data);
    json_decref (o);
    return json_str;
error:
    free (s_data);
    json_decref (o);
    return NULL;
}
コード例 #2
0
ファイル: msgpack2json.c プロジェクト: dybekm/msgpack-tools
// Converts MessagePack bin/ext bytes to JSON base64 string
static bool base64(mpack_reader_t* reader, yajl_gen gen, options_t* options, uint32_t len, char* output, char* p, bool prefix) {
    if (prefix) {
        memcpy(p, b64_str, strlen(b64_str));
        p += strlen(b64_str);
    }

    base64_encodestate state;
    base64_init_encodestate(&state);

    while (len > 0) {
        char buf[4096];
        uint32_t count = (len < sizeof(buf)) ? len : sizeof(buf);
        len -= count;
        mpack_read_bytes(reader, buf, count);
        if (mpack_reader_error(reader) != mpack_ok) {
            fprintf(stderr, "%s: error reading base64 bytes\n", options->command);
            return false;
        }
        p += base64_encode_block(buf, (int)count, p, &state);
    }
    p += base64_encode_blockend(p, &state);

    bool ret = yajl_gen_string(gen, (const unsigned char*)output, p - output) == yajl_gen_status_ok;
    return ret;
}
コード例 #3
0
ファイル: shotgun_utils.c プロジェクト: Naruto/shotgun
char *
shotgun_base64_encode(const unsigned char *string, double len, size_t *size)
{
   base64_encodestate s;
   char *ret = NULL;
   int retlen[2];

   if ((len < 1) || (!string)) return NULL;

   if (!(ret = malloc(sizeof(char) * ((((len + 2) - ((int)(len + 2) % 3)) / 3) * 4) + 4)))
     return NULL;
   base64_init_encodestate(&s);
   retlen[0] = base64_encode_block((char*)string, len, ret, &s);
   retlen[1] = base64_encode_blockend(ret + retlen[0], &s);
   ret[retlen[0] + retlen[1]] = '\0';
   if (ret[retlen[0] + retlen[1] - 1] == '\n')
     {
        ret[retlen[0] + retlen[1] - 1] = '\0';
        *size = retlen[0] + retlen[1] - 2;
     }
   else
     *size = retlen[0] + retlen[1] - 1;

   return ret;
}
コード例 #4
0
ファイル: c-example2.c プロジェクト: MakerCollider/upm
void encode(FILE* inputFile, FILE* outputFile)
{
	/* set up a destination buffer large enough to hold the encoded data */
	int size = SIZE;
	char* input = (char*)malloc(size);
	char* encoded = (char*)malloc(2*size); /* ~4/3 x input */
	/* we need an encoder and decoder state */
	base64_encodestate es;
	/* store the number of bytes encoded by a single call */
	int cnt = 0;
	
	/*---------- START ENCODING ----------*/
	/* initialise the encoder state */
	base64_init_encodestate(&es);
	/* gather data from the input and send it to the output */
	while (1)
	{
		cnt = fread(input, sizeof(char), size, inputFile);
		if (cnt == 0) break;
		cnt = base64_encode_block(input, cnt, encoded, &es);
		/* output the encoded bytes to the output file */
		fwrite(encoded, sizeof(char), cnt, outputFile);
	}
	/* since we have reached the end of the input file, we know that 
	   there is no more input data; finalise the encoding */
	cnt = base64_encode_blockend(encoded, &es);
	/* write the last bytes to the output file */
	fwrite(encoded, sizeof(char), cnt, outputFile);
	/*---------- STOP ENCODING  ----------*/
	
	free(encoded);
	free(input);
}
コード例 #5
0
ファイル: b64enc.c プロジェクト: certego/limacharlie
int main(void)
{
	const int readsize = 4096;
	char* plaintext = 0;
	char* code = 0;
	int plainlength;
	int codelength;
	base64_encodestate state;
	
	code = (char*)malloc(sizeof(char)*readsize*2);
	plaintext = (char*)malloc(sizeof(char)*readsize);
	
	base64_init_encodestate(&state);
	
	do
	{
		plainlength = fread((void*)plaintext, sizeof(char), readsize, stdin);
		codelength = base64_encode_block(plaintext, plainlength, code, &state);
		fwrite((void*)code, sizeof(char), codelength, stdout);
	}
	while (!feof(stdin) && plainlength > 0);
	
	codelength = base64_encode_blockend(code, &state);
	fwrite((void*)code, sizeof(char), codelength, stdout);
	
	free(code);
	free(plaintext);
	
	return 0;
}
コード例 #6
0
ファイル: fromcard.c プロジェクト: Fedict/eid-test-ca
char* pem_csr(struct derdata* csr) {
	size_t b64len = (csr->len / 3 + 1) * 4;
	size_t newlines = b64len / 65 + 2;
#ifdef _WIN32
	char header[] = "-----BEGIN CERTIFICATE REQUEST-----\n\r";
	char footer[] = "-----END CERTIFICATE REQUEST-----\n\r";
	char *encoded = malloc(b64len + newlines * 2 + 1 + sizeof header + sizeof footer);
#else
	char header[] = "-----BEGIN CERTIFICATE REQUEST-----\n";
	char footer[] = "-----END CERTIFICATE REQUEST-----\n";
	char *encoded = malloc(b64len + newlines + 1 + sizeof header + sizeof footer);
#endif
	char *retval = encoded;
	base64_encodestate state;
	int count;

	strcpy(encoded, header);
	encoded += sizeof header - 1;
	base64_init_encodestate(&state);
	count = base64_encode_block((char*)csr->data, csr->len, encoded, &state);
	encoded += count;
	count = base64_encode_blockend(encoded, &state);
	encoded += count - 1;
	if(*encoded != '\n' && *encoded != '\r') {
		*(++encoded) = '\n';
#ifdef _WIN32
		*(++encoded) = '\r';
#endif
	}
	encoded++;
	strcpy(encoded, footer);
	return retval;
}
コード例 #7
0
	void ReadWriteXMLBinary::WriteValue(XMLWritingMachine& writer, const TreeValue* value) const
	{ 
		// binary object
		const TreeBinary* binary = static_cast<const TreeBinary*>( value );

		// binary data
		writer.OS() << "\n";

		if (binary->SizeBytes())
		{
			// init library
			base64_encodestate state;
			base64_init_encodestate(&state);

			// text buffer
			std::string encoded_data(2*binary->SizeBytes(), ' ');

			// convert
			int numchars = base64_encode_block((const char*)binary->Data(), binary->SizeBytes(), &encoded_data[0], &state);
			numchars += base64_encode_blockend(&encoded_data[0] + numchars, &state);

			// shrink to fit
			encoded_data.resize(numchars);

			// write
			writer.OS() << encoded_data;
		}
	}
コード例 #8
0
ファイル: cencode.c プロジェクト: ZiTAL/arduino
int base64_encode_chars(const char* plaintext_in, int length_in, char* code_out)
{
    base64_encodestate _state;
    base64_init_encodestate(&_state);
    int len = base64_encode_block(plaintext_in, length_in, code_out, &_state);
    return len + base64_encode_blockend((code_out + len), &_state);
}
コード例 #9
0
ファイル: selftest.c プロジェクト: grant-roy3/yubico-c-client
void
test_base64 (void)
{
  base64_encodestate encode;
  base64_decodestate decode;
  char b64dig[64];
  char buf[64];
  int size1, size2;
  int ret;

  TEST(("test base64 encoding"));
  base64_init_encodestate(&encode);
  size1 = base64_encode_block("foo", 3, b64dig, &encode);
  size2 = base64_encode_blockend(&b64dig[size1], &encode);
  b64dig[size1 + size2 - 1] = '\0';

  printf("b64 encode: %s, expected: Zm9v\n", b64dig);
  ret = strcmp(b64dig, "Zm9v");
  assert(ret == 0);

  TEST(("test base64 decoding"));
  base64_init_decodestate(&decode);
  base64_decode_block ("YmxhaG9uZ2E=", 12, buf, &decode);

  printf("b64 decode: %s, expexted: blahonga\n", buf);
  ret = strcmp(buf, "blahonga");
  assert(ret == 0);
}
コード例 #10
0
char* encode(const char* input) {
	/* set up a destination buffer large enough to hold the encoded data */
	char* output = (char*) malloc(SIZE);
	/* keep track of our encoded position */
	char* c = output;
	/* store the number of bytes encoded by a single call */
	int cnt = 0;
	/* we need an encoder state */
	base64_encodestate s;

	/*---------- START ENCODING ----------*/
	/* initialise the encoder state */
	base64_init_encodestate(&s);
	/* gather data from the input and send it to the output */
	cnt = base64_encode_block(input, strlen(input), c, &s);
	c += cnt;
	/* since we have encoded the entire input string, we know that
	 there is no more input data; finalise the encoding */
	cnt = base64_encode_blockend(c, &s);
	c += cnt;
	/*---------- STOP ENCODING  ----------*/

	/* we want to print the encoded data, so null-terminate it: */
	*c = 0;

	return output;
}
コード例 #11
0
ファイル: NDataEncoder.cpp プロジェクト: refnum/nano
//============================================================================
//		NDataEncoder::B64_Encode : Encode to Base64.
//----------------------------------------------------------------------------
NString NDataEncoder::B64_Encode(const NData &theValue)
{	NData					theBuffer;
	NString					theString;
	base64_encodestate		theState;
	char					*dataPtr;
	NIndex					dataSize;



	// Get the state we need
	base64_init_encodestate(&theState);

	if (theValue.IsEmpty() || !theBuffer.SetSize(theValue.GetSize() * 2))
		return(theString);



	// Encode the value
	dataPtr   = (char *) theBuffer.GetData();
	dataSize  = base64_encode_block((const char *) theValue.GetData(), theValue.GetSize(), dataPtr, &theState);
	theString = NString(dataPtr, dataSize);

	dataSize = base64_encode_blockend(dataPtr, &theState);
	if (dataSize != 0)
		theString += NString(dataPtr, dataSize);



	// Remove the trailing newline
	NN_ASSERT(theString.GetRight(1) == "\n");
	theString.TrimRight(1);

	return(theString);
}
コード例 #12
0
ファイル: CCCrypto.cpp プロジェクト: joshfeng/quick-cocos2d-x
int CCCrypto::encodeBase64(unsigned char* input,
                           int inputLength,
                           char* output,
                           int outputBufferLength)
{
    int bufferSize = 2 * inputLength;
    char* buffer = (char*)malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    base64_encodestate state;
    base64_init_encodestate(&state);
    int r1 = base64_encode_block((const char*)input, inputLength, buffer, &state);
    int r2 = base64_encode_blockend(buffer+ r1, &state);
    
    int dataUsed = r1 + r2;
    memset(output, 0, outputBufferLength);
    int cp = dataUsed < outputBufferLength ? dataUsed : outputBufferLength - 1;
    memcpy(output, buffer, cp);

    for (int e = outputBufferLength - 1; e >= 0; --e)
    {
        if (output[e] == '\n')
        {
            output[e] = '\0';
        }
    }

    free(buffer);
    return cp;
}
コード例 #13
0
ファイル: sc_io.c プロジェクト: aseyboldt/libsc
int
sc_vtk_write_binary (FILE * vtkfile, char *numeric_data, size_t byte_length)
{
  size_t              chunks, chunksize, remaining, writenow;
  size_t              code_length, base_length;
  uint32_t            int_header;
  char               *base_data;
  base64_encodestate  encode_state;

  /* VTK format used 32bit header info */
  SC_ASSERT (byte_length <= (size_t) UINT32_MAX);

  chunksize = (size_t) 1 << 15; /* 32768 */
  int_header = (uint32_t) byte_length;

  code_length = 2 * chunksize;
  base_data = SC_ALLOC (char, code_length);

  base64_init_encodestate (&encode_state);
  base_length =
    base64_encode_block ((char *) &int_header, sizeof (int_header), base_data,
                         &encode_state);
  base_data[base_length] = '\0';
  (void) fwrite (base_data, 1, base_length, vtkfile);

  chunks = 0;
  remaining = byte_length;
  while (remaining > 0) {
    writenow = SC_MIN (remaining, chunksize);
    base_length = base64_encode_block (numeric_data + chunks * chunksize,
                                       writenow, base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
    remaining -= writenow;
    ++chunks;
  }

  base_length = base64_encode_blockend (base_data, &encode_state);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  SC_FREE (base_data);
  if (ferror (vtkfile)) {
    return -1;
  }
  return 0;
}
コード例 #14
0
static char* base64_encode_block_encodes_3_bytes()
{
    char output[5] = { 0 };

    base64_encode_block((uint8_t*)"Man", output);
    mu_assert("Encoding", compare_string("TWFu", output, 4));

    return 0;
}
コード例 #15
0
ファイル: base64.c プロジェクト: DarkDare/tarantool
int
base64_encode(const char *in_bin, int in_len,
	      char *out_base64, int out_len)
{
	struct base64_encodestate state;
	base64_encodestate_init(&state);
	int res = base64_encode_block(in_bin, in_len, out_base64,
				      out_len, &state);
	return res + base64_encode_blockend(out_base64 + res, out_len - res,
					    &state);
}
コード例 #16
0
ファイル: base64.c プロジェクト: cwnga/ygloo-yosal
char*
Ybase64_encode(const char *buf, int buflen)
{
  base64_encodestate bstate;
  const char *ibuf;
  int ilen, olen;
  char *result;
  char obuf[20];
  Ybuffer *ybuf;

  if (buf == NULL) {
    return NULL;
  }

  if (buflen < 0) {
    buflen = strlen(buf);
  }

  /* Output should be (buflen / 3) * 4 + 4 + 1 */
  ybuf = Ybuffer_init(16);
  if (ybuf == NULL) {
    return NULL;
  }

  base64_init_encodestate(&bstate);

  ibuf = buf;
  while (buflen > 0) {
    if (buflen < 12) {
      ilen = buflen;
    } else {
      ilen = 12;
    }

    olen = base64_encode_block(ibuf, ilen, obuf, &bstate);
    Ybuffer_append(ybuf, obuf, olen);

    ibuf += ilen;
    buflen -= ilen;
  }

  olen = base64_encode_blockend(obuf, &bstate);
  Ybuffer_append(ybuf, obuf, olen);

  /* Get sure output buffer is a valid null terminated string */
  Ybuffer_append(ybuf, "\0", 1);

  /* Extract string and release Ybuffer container */
  result = Ybuffer_detach(ybuf, NULL);

  return result;
}
コード例 #17
0
ファイル: b64.c プロジェクト: shawnpresser/b64
size_t
b64_encode( const char* in, size_t insize, char* out )
{
  const char* start = out;
  size_t len = 0;
  base64_encodestate state;
  base64_init_encodestate( &state );
  len = base64_encode_block( in, insize, out, &state );
  out += len;
  len = base64_encode_blockend( out, &state );
  out += len;
  return out - start;
}
コード例 #18
0
ファイル: base64_json.c プロジェクト: cigolabs/flux-core
json_object *base64_json_encode (uint8_t *dat, int len)
{
    char *buf;
    int dstlen;
    json_object *o;
    int size = base64_encode_length (len);

    buf = xzmalloc (size);
    (void) base64_encode_block (buf, &dstlen, dat, len);
    if (!(o = json_object_new_string (buf)))
        oom ();
    free (buf);
    return o;
}
コード例 #19
0
ファイル: register.c プロジェクト: ar45/libu2f-host
static int
prepare_response (const unsigned char *buf, int len, const char *bd,
		  char **response, size_t * response_len)
{
  base64_encodestate b64ctx;
  char b64resp[2048];
  char bdstr[2048];
  int cnt;

  if (len > 2048)
    return U2FH_MEMORY_ERROR;
  if (strlen (bd) > 2048)
    return U2FH_MEMORY_ERROR;

  base64_init_encodestate (&b64ctx);
  cnt = base64_encode_block (buf, len, b64resp, &b64ctx);
  base64_encode_blockend (b64resp + cnt, &b64ctx);

  base64_init_encodestate (&b64ctx);
  cnt = base64_encode_block (bd, strlen (bd), bdstr, &b64ctx);
  base64_encode_blockend (bdstr + cnt, &b64ctx);

  return prepare_response2 (b64resp, bdstr, response, response_len);
}
コード例 #20
0
ファイル: core.c プロジェクト: Yubico/libu2f-server-dpkg
static u2fs_rc encode_b64u(const char *data, size_t data_len, char *output)
{
  base64_encodestate b64;
  int cnt;

  if ((data_len * 4) >= (_B64_BUFSIZE * 3) || output == NULL)	//base64 is 75% efficient (4 characters encode 3 bytes)
    return U2FS_MEMORY_ERROR;

  base64_init_encodestate(&b64);
  cnt = base64_encode_block(data, data_len, output, &b64);
  cnt += base64_encode_blockend(output + cnt, &b64);

  output[cnt] = '\0';

  return U2FS_OK;
}
コード例 #21
0
ファイル: plist_helpers_edk2.c プロジェクト: queer1/bareBoot
char*
_plb64encode(char* idat, unsigned int ilen, unsigned int* olen) {
	unsigned int osiz;
	unsigned int csiz;
	unsigned int tsiz;
	char* odat;
	base64_encodestate b64state;

	if (idat == NULL || ilen == 0) { return NULL; }
	osiz = (((ilen + 2) / 3) + 1 ) * 4; 
	odat = _plzalloc(osiz);
	if (odat == NULL) { return NULL; }
	base64_init_encodestate(&b64state);
	csiz = base64_encode_block(idat, ilen, odat, &b64state);
	tsiz = base64_encode_blockend(&odat[csiz], &b64state);
	if (olen != NULL) { *olen = csiz + tsiz; }
	return odat;
}
コード例 #22
0
ファイル: websocket.c プロジェクト: JonMerlevede/webdis
static int
ws_compute_handshake(struct http_client *c, char *out, size_t *out_sz) {

	unsigned char *buffer, sha1_output[20];
	char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
	SHA1Context ctx;
	base64_encodestate b64_ctx;
	int pos, i;

	// websocket handshake
	const char *key = client_get_header(c, "Sec-WebSocket-Key");
	size_t key_sz = key?strlen(key):0, buffer_sz = key_sz + sizeof(magic) - 1;
	buffer = calloc(buffer_sz, 1);

	// concatenate key and guid in buffer
	memcpy(buffer, key, key_sz);
	memcpy(buffer+key_sz, magic, sizeof(magic)-1);

	// compute sha-1
	SHA1Reset(&ctx);
	SHA1Input(&ctx, buffer, buffer_sz);
	SHA1Result(&ctx);
	for(i = 0; i < 5; ++i) {	// put in correct byte order before memcpy.
		ctx.Message_Digest[i] = ntohl(ctx.Message_Digest[i]);
	}
	memcpy(sha1_output, (unsigned char*)ctx.Message_Digest, 20);

	// encode `sha1_output' in base 64, into `out'.
	base64_init_encodestate(&b64_ctx);
	pos = base64_encode_block((const char*)sha1_output, 20, out, &b64_ctx);
	base64_encode_blockend(out + pos, &b64_ctx);

	// compute length, without \n
	*out_sz = strlen(out);
	if(out[*out_sz-1] == '\n')
		(*out_sz)--;

	free(buffer);

	return 0;
}
コード例 #23
0
ファイル: Crypto.cpp プロジェクト: akehoyayoi/WkCocos
	int Crypto::encodeBase64(const void* input,
		int inputLength,
		char* output,
		int outputBufferLength)
	{
		int bufferSize = 2 * inputLength;
		char* buffer = (char*)malloc(bufferSize);
		memset(buffer, 0, bufferSize);

		base64_encodestate state;
		base64_init_encodestate(&state);
		int r1 = base64_encode_block(static_cast<const char*>(input), inputLength, buffer, &state);
		int r2 = base64_encode_blockend(buffer + r1, &state);

		int dataUsed = r1 + r2;
		memset(output, 0, outputBufferLength);
		int cp = dataUsed < outputBufferLength ? dataUsed : outputBufferLength - 1;
		memcpy(output, buffer, cp);
		free(buffer);
		return cp;
	}
コード例 #24
0
ファイル: Y64.cpp プロジェクト: MoonActive/chronotext-toolkit
 string toBase64(const void *input, int inputSize)
 {
     if (inputSize == 0)
     {
         return string();
     }
     
     char *buffer = new char[inputSize * 4 / 3 + 4];
     
     base64_encodestate state;
     base64_init_encodestate(&state);
     
     int resultSize = base64_encode_block(reinterpret_cast<const char*>(input), inputSize, &buffer[0], &state);
     resultSize += base64_encode_blockend(&buffer[resultSize], &state);
     buffer[resultSize] = 0; // NULL TERMINATE THE STRING
     
     string result(buffer);
     delete[] buffer;
     
     return result;
 }
コード例 #25
0
ファイル: sc_io.c プロジェクト: aseyboldt/libsc
int
sc_vtk_write_compressed (FILE * vtkfile, char *numeric_data,
                         size_t byte_length)
{
  int                 retval, fseek1, fseek2;
  size_t              iz;
  size_t              blocksize, lastsize;
  size_t              theblock, numregularblocks, numfullblocks;
  size_t              header_entries;
  size_t              code_length, base_length;
  long                header_pos, final_pos;
  char               *comp_data, *base_data;
  uint32_t           *compression_header;
  uLongf              comp_length;
  base64_encodestate  encode_state;

  /* compute block sizes */
  blocksize = (size_t) (1 << 15);       /* 32768 */
  lastsize = byte_length % blocksize;
  numregularblocks = byte_length / blocksize;
  numfullblocks = numregularblocks + (lastsize > 0 ? 1 : 0);

  /* allocate compression and base64 arrays */
  code_length = 2 * blocksize;
  comp_data = SC_ALLOC (char, code_length);
  base_data = SC_ALLOC (char, code_length);

  /* figure out the size of the header and write a dummy */
  header_entries = 3 + numfullblocks;
  compression_header = SC_ALLOC (uint32_t, header_entries);
  compression_header[0] = (uint32_t) numfullblocks;
  compression_header[1] = (uint32_t) blocksize;
  compression_header[2] = (uint32_t)
    (lastsize > 0 || byte_length == 0 ? lastsize : blocksize);
  for (iz = 3; iz < header_entries; ++iz) {
    compression_header[iz] = 0;
  }
  base64_init_encodestate (&encode_state);
  base_length = base64_encode_block ((char *) compression_header,
                                     sizeof (*compression_header) *
                                     header_entries, base_data,
                                     &encode_state);
  base_length +=
    base64_encode_blockend (base_data + base_length, &encode_state);
  base_data[base_length] = '\0';
  SC_ASSERT (base_length < code_length);
  header_pos = ftell (vtkfile);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  /* write the regular data blocks */
  base64_init_encodestate (&encode_state);
  for (theblock = 0; theblock < numregularblocks; ++theblock) {
    comp_length = code_length;
    retval = compress2 ((Bytef *) comp_data, &comp_length,
                        (const Bytef *) (numeric_data + theblock * blocksize),
                        (uLong) blocksize, Z_BEST_COMPRESSION);
    SC_ASSERT (retval == Z_OK);
    compression_header[3 + theblock] = comp_length;
    base_length = base64_encode_block (comp_data, comp_length,
                                       base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
  }

  /* write odd-sized last block if necessary */
  if (lastsize > 0) {
    comp_length = code_length;
    retval = compress2 ((Bytef *) comp_data, &comp_length,
                        (const Bytef *) (numeric_data + theblock * blocksize),
                        (uLong) lastsize, Z_BEST_COMPRESSION);
    SC_ASSERT (retval == Z_OK);
    compression_header[3 + theblock] = comp_length;
    base_length = base64_encode_block (comp_data, comp_length,
                                       base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
  }

  /* write base64 end block */
  base_length = base64_encode_blockend (base_data, &encode_state);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  /* seek back, write header block, seek forward */
  final_pos = ftell (vtkfile);
  base64_init_encodestate (&encode_state);
  base_length = base64_encode_block ((char *) compression_header,
                                     sizeof (*compression_header) *
                                     header_entries, base_data,
                                     &encode_state);
  base_length +=
    base64_encode_blockend (base_data + base_length, &encode_state);
  base_data[base_length] = '\0';
  SC_ASSERT (base_length < code_length);
  fseek1 = fseek (vtkfile, header_pos, SEEK_SET);
  (void) fwrite (base_data, 1, base_length, vtkfile);
  fseek2 = fseek (vtkfile, final_pos, SEEK_SET);

  /* clean up and return */
  SC_FREE (compression_header);
  SC_FREE (comp_data);
  SC_FREE (base_data);
  if (fseek1 != 0 || fseek2 != 0 || ferror (vtkfile)) {
    return -1;
  }
  return 0;
}
コード例 #26
0
ファイル: base64_test.c プロジェクト: JakeMick/munge
int
encode_block (unsigned char *dst, int *dstlen,
              const unsigned char *src, int srclen)
{
    return (base64_encode_block (dst, dstlen, src, srclen));
}
コード例 #27
0
ファイル: ykclient.c プロジェクト: tfheen/yubico-c-client
int
ykclient_request (ykclient_t *ykc,
		  const char *yubikey)
{
  const char *url_template = ykc->url_template;
  char *user_agent = NULL;
  char *status;
  int out;

  if (!url_template)
    url_template = "http://api.yubico.com/wsapi/verify?id=%d&otp=%s";

  free (ykc->curl_chunk);
  ykc->curl_chunk_size = 0;
  ykc->curl_chunk = NULL;

  {
    size_t len = strlen (url_template) + strlen (yubikey) + 20;
    size_t wrote;

    free (ykc->url);
    ykc->url = malloc (len);
    if (!ykc->url)
      return YKCLIENT_OUT_OF_MEMORY;
    wrote = snprintf (ykc->url, len, url_template,
		      ykc->client_id, yubikey);
    if (wrote < 0 || wrote > len)
      return YKCLIENT_FORMAT_ERROR;
  }

  if (ykc->key && ykc->keylen)
    {
      uint8_t digest[USHAMaxHashSize];
      char b64dig[3*4*SHA1HashSize+1];
      base64_encodestate b64;
      char *text;
      int res, res2;

      /* Find parameters to sign. */
      text = strchr (ykc->url, '?');
      if (!text)
	return YKCLIENT_PARSE_ERROR;
      text++;

      /* HMAC data. */
      res = hmac (SHA1, (unsigned char*) text, strlen (text),
		  (unsigned char*) ykc->key, ykc->keylen, digest);
      if (res != shaSuccess)
	return YKCLIENT_HMAC_ERROR;

      /* Base64 signature. */
      base64_init_encodestate(&b64);
      res = base64_encode_block((char*)digest, SHA1HashSize, b64dig, &b64);
      res2 = base64_encode_blockend(&b64dig[res], &b64);
      b64dig[res+res2-1] = '\0';

      /* Escape + into %2B. */
      {
	char *p;

	while ((p = strchr (b64dig, '+')))
	  {
	    memmove (p+3, p+1, strlen (p));
	    memcpy (p, "%2B", 3);
	  }
      }

      /* Create new URL. */
      {
	char *url;
	size_t len;
	int wrote;

#define ADD_HASH "&h="
	len = strlen (ykc->url) + strlen (ADD_HASH) + strlen (b64dig) + 1;
	url = malloc (len);
	if (!url)
	  return YKCLIENT_OUT_OF_MEMORY;

	wrote = snprintf (url, len, "%s" ADD_HASH "%s", ykc->url, b64dig);
	if (wrote + 1 != len)
	  return YKCLIENT_FORMAT_ERROR;
	free (ykc->url);
	ykc->url = url;
      }
    }

  if (ykc->nonce)
    {
      /* Create new URL. */
      char *url;
      size_t len;
      int wrote;

#define ADD_NONCE "&nonce="
      len = strlen (ykc->url) + strlen (ADD_NONCE) + strlen (ykc->nonce) + 1;
      url = malloc (len);
      if (!url)
        return YKCLIENT_OUT_OF_MEMORY;

      wrote = snprintf (url, len, "%s" ADD_NONCE "%s", ykc->url, ykc->nonce);
      if (wrote + 1 != len)
        return YKCLIENT_FORMAT_ERROR;
      free (ykc->url);
      ykc->url = url;
    }

  if(ykc->ca_path)
    {
      curl_easy_setopt (ykc->curl, CURLOPT_CAPATH, ykc->ca_path);
    }

  curl_easy_setopt (ykc->curl, CURLOPT_URL, ykc->url);
  curl_easy_setopt (ykc->curl, CURLOPT_WRITEFUNCTION, curl_callback);
  curl_easy_setopt (ykc->curl, CURLOPT_WRITEDATA, (void *) ykc);

  {
    size_t len = strlen (PACKAGE) + 1 + strlen (PACKAGE_VERSION) + 1;
    user_agent = malloc (len);
    if (!user_agent)
      return YKCLIENT_OUT_OF_MEMORY;
    if (snprintf (user_agent, len, "%s/%s", PACKAGE, PACKAGE_VERSION) > 0)
      curl_easy_setopt(ykc->curl, CURLOPT_USERAGENT, user_agent);
  }

  curl_easy_perform (ykc->curl);

  if (ykc->curl_chunk_size == 0 || ykc->curl_chunk == NULL)
    {
      out = YKCLIENT_PARSE_ERROR;
      goto done;
    }

  status = strstr (ykc->curl_chunk, "status=");
  if (!status)
    {
      out = YKCLIENT_PARSE_ERROR;
      goto done;
    }

  while (status[strlen (status) - 1] == '\r'
	 || status[strlen (status) - 1] == '\n')
    status[strlen (status) - 1] = '\0';

  if (strcmp (status, "status=OK") == 0)
    {
      out = YKCLIENT_OK;
      goto done;
    }
  else if (strcmp (status, "status=BAD_OTP") == 0)
    {
      out = YKCLIENT_BAD_OTP;
      goto done;
    }
  else if (strcmp (status, "status=REPLAYED_OTP") == 0)
    {
      out = YKCLIENT_REPLAYED_OTP;
      goto done;
    }
  else if (strcmp (status, "status=REPLAYED_REQUEST") == 0)
    {
      out = YKCLIENT_REPLAYED_REQUEST;
      goto done;
    }
  else if (strcmp (status, "status=BAD_SIGNATURE") == 0)
    {
      out = YKCLIENT_BAD_SIGNATURE;
      goto done;
    }
  else if (strcmp (status, "status=MISSING_PARAMETER") == 0)
    {
      out = YKCLIENT_MISSING_PARAMETER;
      goto done;
    }
  else if (strcmp (status, "status=NO_SUCH_CLIENT") == 0)
    {
      out = YKCLIENT_NO_SUCH_CLIENT;
      goto done;
    }
  else if (strcmp (status, "status=OPERATION_NOT_ALLOWED") == 0)
    {
      out = YKCLIENT_OPERATION_NOT_ALLOWED;
      goto done;
    }
  else if (strcmp (status, "status=BACKEND_ERROR") == 0)
    {
      out = YKCLIENT_BACKEND_ERROR;
      goto done;
    }
  else if (strcmp (status, "status=NOT_ENOUGH_ANSWERS") == 0)
    {
      out = YKCLIENT_NOT_ENOUGH_ANSWERS;
      goto done;
    }

  out = YKCLIENT_PARSE_ERROR;

 done:
  if (user_agent)
    free (user_agent);

  return out;
}
コード例 #28
0
ファイル: base64_test.c プロジェクト: dun/munge
int
encode_block (char *dst, int *dstlen, const void *src, int srclen)
{
    return (base64_encode_block (dst, dstlen, src, srclen));
}
コード例 #29
0
ファイル: json.c プロジェクト: farsightsec/axa
static axa_json_res_t
add_whit(axa_emsg_t *emsg, yajl_gen g, struct axa_strbuf *yajl_sb, nmsg_input_t nmsg_input, axa_p_whit_t *whit, size_t whit_len)
{
	axa_json_res_t json_res;

	json_res = add_channel(emsg, g, whit->hdr.ch);
	if (json_res != AXA_JSON_RES_SUCCESS)
		return (json_res);

	switch (whit->hdr.type) {
	case AXA_P_WHIT_NMSG: {
		struct axa_strbuf *sb;
		nmsg_message_t msg;
		axa_w2n_res_t wres;
		nmsg_res nres;
		const char *vname, *mname;
		char *nmsg_json = NULL;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_nmsg_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu", whit_len, sizeof(axa_p_whit_nmsg_t));
			return (AXA_JSON_RES_FAILURE);
		}

		wres = axa_whit2nmsg(emsg, nmsg_input, &msg, whit, whit_len);
		if (wres != AXA_W2N_RES_SUCCESS) {
			return (AXA_JSON_RES_FAILURE);
		}

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}

		if(AXA_P2H_IDX(whit->nmsg.hdr.field_idx) < AXA_NMSG_IDX_RSVD) {
			const char *field_name;
			nres = nmsg_message_get_field_name(msg, whit->nmsg.hdr.field_idx, &field_name);
			if (nres == nmsg_res_success) {
				add_yajl_string(g, "field");
				add_yajl_string(g, field_name);
			} else {
				add_yajl_string(g, "field_idx");
				add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.field_idx));
			}
		}

		if (AXA_P2H_IDX(whit->nmsg.hdr.val_idx) < AXA_NMSG_IDX_RSVD) {
			add_yajl_string(g, "val_idx");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.val_idx));
		}

		vname = nmsg_msgmod_vid_to_vname(AXA_P2H_IDX(whit->nmsg.hdr.vid));
		if (vname != NULL) {
			add_yajl_string(g, "vname");
			add_yajl_string(g, vname);
		} else {
			add_yajl_string(g, "vid");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.vid));
		}

		mname = nmsg_msgmod_msgtype_to_mname(
				AXA_P2H16(whit->nmsg.hdr.vid),
				AXA_P2H16(whit->nmsg.hdr.type));
		if (mname != NULL) {
			add_yajl_string(g, "mname");
			add_yajl_string(g, mname);
		} else {
			add_yajl_string(g, "msgtype");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.type));
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->nmsg.hdr.ts.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		axa_strbuf_reset(sb);
		axa_strbuf_append(sb, "%s.%09u", when,
				AXA_P2H32(whit->nmsg.hdr.ts.tv_nsec));
		add_yajl_string(g, sb->data);

		nres = nmsg_message_to_json(msg, &nmsg_json);
		if (nres == nmsg_res_success) {
			add_yajl_string(g, "nmsg");
			add_yajl_integer(g, 0);

			yajl_gen_clear(g);
			axa_strbuf_clip(yajl_sb, axa_strbuf_len(yajl_sb)-1);
			axa_strbuf_append(yajl_sb, "%s", nmsg_json);
			free(nmsg_json);
		}

		axa_strbuf_destroy(&sb);
		nmsg_message_destroy(&msg);

		return (AXA_JSON_RES_SUCCESS);
	}
	case AXA_P_WHIT_IP: {
		struct axa_strbuf *sb;
		struct nmsg_ipdg dg;
		nmsg_res res;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_ip_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu",
					whit_len, sizeof(axa_p_whit_ip_t));
			return (AXA_JSON_RES_FAILURE);
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->ip.hdr.tv.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}
		axa_strbuf_append(sb, "%s.%06u", when,
				AXA_P2H32(whit->ip.hdr.tv.tv_usec));
		add_yajl_string(g, sb->data);
		axa_strbuf_destroy(&sb);

		res = nmsg_ipdg_parse_pcap_raw(&dg, DLT_RAW, whit->ip.b, whit_len - offsetof(axa_p_whit_ip_t, b));
		if (res != nmsg_res_success || dg.len_network == 0) {
			add_yajl_string(g, "parse_error");
			add_yajl_bool(g, true);

			return (AXA_JSON_RES_SUCCESS);
		}

		add_yajl_string(g, "af");
		switch(dg.proto_network) {
		case AF_INET: {
			struct ip *ip_hdr;
			char addr_str[INET_ADDRSTRLEN];

			add_yajl_string(g, "IPv4");

			if (dg.network != NULL && dg.len_network >= sizeof(ip_hdr)) {
				ip_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_src, addr_str, sizeof(addr_str)));
				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip_hdr->ip_ttl);
			}
			break;
		}
		case AF_INET6: {
			struct ip6_hdr *ip6_hdr;
			char addr_str[INET6_ADDRSTRLEN];
			
			add_yajl_string(g, "IPv6");

			if (dg.network != NULL && dg.len_network >= sizeof(ip6_hdr)) {
				ip6_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_src, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip6_hdr->ip6_hlim);

			}
			break;
		}
		default:
			add_yajl_integer(g, dg.proto_network);
			return (AXA_JSON_RES_SUCCESS);
		} /* switch */

		add_yajl_string(g, "proto");
		switch(dg.proto_transport) {
		case IPPROTO_ICMP:
			add_yajl_string(g, "ICMP");
			break;
		case IPPROTO_ICMPV6:
			add_yajl_string(g, "ICMPv6");
			break;
		case IPPROTO_TCP:
			add_yajl_string(g, "TCP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct tcphdr)) {
				struct tcphdr *tcp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_dport));

				add_yajl_string(g, "flags");
				add_yajl_array(g);
				if ((tcp_hdr->th_flags & TH_FIN) != 0)
					add_yajl_string(g, "FIN");
				if ((tcp_hdr->th_flags & TH_SYN) != 0)
					add_yajl_string(g, "SYN");
				if ((tcp_hdr->th_flags & TH_ACK) != 0)
					add_yajl_string(g, "ACK");
				if ((tcp_hdr->th_flags & TH_RST) != 0)
					add_yajl_string(g, "RST");
				close_yajl_array(g);
			}
			break;
		case IPPROTO_UDP:
			add_yajl_string(g, "UDP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct udphdr)) {
				struct udphdr *udp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_dport));

			}
			break;
		default:
			add_yajl_integer(g, dg.proto_transport);
			break;
		} /* switch */

		if (dg.payload != NULL) {
			base64_encodestate b64;
			char *b64_str;
			size_t b64_str_len;

			base64_init_encodestate(&b64);
			b64_str = alloca(2 * dg.len_payload + 1);
			AXA_ASSERT(b64_str != NULL);

			b64_str_len = base64_encode_block((void*)dg.payload,
					dg.len_payload, b64_str, &b64);
			b64_str_len += base64_encode_blockend(b64_str + b64_str_len, &b64);

			add_yajl_string(g, "payload");
			add_yajl_string_len(g, b64_str, b64_str_len);
		}

		return (AXA_JSON_RES_SUCCESS);
	}
	default:
		axa_pemsg(emsg, "unknown whit hdr type: %d", whit->hdr.type);
		return (AXA_JSON_RES_FAILURE);
	}
}
コード例 #30
0
ファイル: encoding.cpp プロジェクト: DTidd/OpenRDAAPI
char *encode_base64_from_file(char *filename)
{
	base64_encodestate enstate;
	statstruct statb;	
	FILE *fp=NULL;
	size_t size=0,size1=0;
	char *temp=NULL;
	char *temp1=NULL;
	char *base64_result=NULL;

#if !defined(LINUX_SUSE6_1)
	if(stat(filename,&statb)!=(-1))
#else
	if(_xstat(_STAT_VER,filename,&statb)!=(-1))
#endif
	{
		if(statb.st_size>0)
		{
			fp=fopen(filename,"rb");
			if(fp!=NULL)
			{
				size=statb.st_size;
				temp=(char *)Rmalloc(size+1);
				memset(temp,0,size+1);
				printf("size [%d]\n",size);
				size=fread(temp,sizeof(char),size,fp);
				printf("size [%d]\n",size);
				if(ferror(fp))
				{
					prterr("Error:  Failed to read characters to the end of file [%s].",filename);
				}else if(size==0) {
					prterr("Error:  File [%s] is an empty or an error occurred.",filename);
				}else{
					/*
					size1=base64_encoded_size(temp,size);
					*/
					size1=(size*2);

					temp1=(char *)Rmalloc(size1+1);
					memset(temp1,0,size1+1);

					base64_result=(char *)Rmalloc(size1+1);
					memset(base64_result,0,size1+1);
					
					base64_init_encodestate(&enstate);
					base64_encode_block(temp,size,temp1,&enstate);
					sprintf(base64_result,"%s%s",base64_result,temp1);

					memset(temp1,0,size1+1);
					base64_encode_blockend(temp1,&enstate);
					sprintf(base64_result,"%s%s",base64_result,temp1);

					if(temp!=NULL) Rfree(temp);
					if(temp1!=NULL) Rfree(temp1);
					fclose(fp);
					return(base64_result);
				}
				if(temp!=NULL) Rfree(temp);
				fclose(fp);
			}else{
				prterr("Error:  Could not open file [%s] for encoding to base64.\n",filename);
			}
		}else{
			prterr("Error:  Zero sized file [%s] could not be used for encoding to base64.\n",filename);
		}
	}else{
		prterr("Error:  Could not stat file [%s], not attempting to open file.\n",filename);
	}
	return(NULL);
}