예제 #1
0
파일: xcbc.c 프로젝트: grivet/XCBC
int
XCBC_Init(XCBC_CTX *xctx,
	  const uint8_t const *k)
{
	int bl, outl;
	EVP_CIPHER_CTX *ctx;
	uint8_t k1[XCBC_MAX_BLOCK_LENGTH];

	ctx = xctx->ctx;

	EVP_CIPHER_CTX_init(ctx);
	OPENSSL_try(EVP_CipherInit_ex(ctx, EVP_aes_128_ecb(), NULL, k, NULL, 1),
		    "cipher init error", return0);
	bl = EVP_CIPHER_CTX_block_size((const EVP_CIPHER_CTX *)ctx);
	OPENSSL_try(EVP_CipherUpdate(ctx,       k1, &outl, ks1, bl),
		    "cipher update error (k1)", return0);
	OPENSSL_try(EVP_CipherUpdate(ctx, xctx->k2, &outl, ks2, bl),
		    "cipher update error (k2)", return0);
	OPENSSL_try(EVP_CipherUpdate(ctx, xctx->k3, &outl, ks3, bl),
		    "cipher update error (k3)", return0);

	OPENSSL_try(EVP_CipherInit_ex(ctx, NULL, NULL, k1, NULL, -1),
		    "cipher reset error", return0);
	memset(xctx->e, 0, bl);
	xctx->size = 0;

	return 1;

return0:
	return 0;
}
예제 #2
0
파일: encrypt.c 프로젝트: hynnet/ShadowWeb
void encrypt_buf(struct encryption_ctx *ctx, char *buf, int *len) {
    if (_method == EncryptionTable) {
        table_encrypt(buf, *len);
    } else {
        if (ctx->status == STATUS_EMPTY) {
            int iv_len = encryption_iv_len[_method];
            unsigned char iv[EVP_MAX_IV_LENGTH];
            memset(iv, 0, iv_len);
            RAND_bytes(iv, iv_len);
            init_cipher(ctx, iv, iv_len, 1);
            int out_len = *len + EVP_CIPHER_CTX_block_size(ctx->ctx);
            unsigned char *cipher_text = malloc(out_len);
            EVP_CipherUpdate(ctx->ctx, cipher_text, &out_len, buf, *len);
            memcpy(buf, iv, iv_len);
            memcpy(buf + iv_len, cipher_text, out_len);
            *len = iv_len + out_len;
            free(cipher_text);
        } else {
            int out_len = *len + EVP_CIPHER_CTX_block_size(ctx->ctx);
            unsigned char *cipher_text = malloc(out_len);
            EVP_CipherUpdate(ctx->ctx, cipher_text, &out_len, buf, *len);
            memcpy(buf, cipher_text, out_len);
            *len = out_len;
            free(cipher_text);
        }
    }
}
예제 #3
0
static int
ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr,
			const unsigned char *in, long in_len)
{
    int out_part_len;
    long out_len = 0;
#define UPDATE_LENGTH_LIMIT INT_MAX

#if SIZEOF_LONG > UPDATE_LENGTH_LIMIT
    if (in_len > UPDATE_LENGTH_LIMIT) {
	const int in_part_len = (UPDATE_LENGTH_LIMIT / 2 + 1) & ~1;
	do {
	    if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
				  &out_part_len, in, in_part_len))
		return 0;
	    out_len += out_part_len;
	    in += in_part_len;
	} while ((in_len -= in_part_len) > UPDATE_LENGTH_LIMIT);
    }
#endif
    if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
			  &out_part_len, in, (int)in_len))
	return 0;
    if (out_len_ptr) *out_len_ptr = out_len += out_part_len;
    return 1;
}
예제 #4
0
파일: testevp.c 프로젝트: GDXN/test
int main(int N, char ** S)
{
    unsigned char key[]= "helloworld" ;
    unsigned char iv[]= "12345678" ;
    char * destp ;
    int iuse, iuse2 ;

    EVP_CIPHER_CTX ctx;

    OpenSSL_add_all_ciphers() ;

    printf("test: (%s) len %zd.\n", test, strlen(test)) ;

    EVP_CIPHER_CTX_init(&ctx) ;

    // encode
    EVP_CipherInit_ex(&ctx, EVP_bf_cbc(), NULL, NULL, NULL, 1);
    EVP_CIPHER_CTX_set_key_length(&ctx, strlen(key));
    EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, -1);

    destp= buffer ;

    EVP_CipherUpdate(&ctx, destp, &iuse, test, strlen(test) +1) ;
    destp += iuse ;
    EVP_CipherFinal_ex(&ctx, destp, &iuse) ;
    destp += iuse ;
    iuse= ( destp - buffer ) ;

    EVP_CIPHER_CTX_cleanup(&ctx);

    // decode
    EVP_CipherInit_ex(&ctx, EVP_bf_cbc(), NULL, NULL, NULL, 0);
    EVP_CIPHER_CTX_set_key_length(&ctx, strlen(key));
    EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, -1);

    destp= buffer2 ;

    EVP_CipherUpdate(&ctx, destp, &iuse2, buffer, iuse ) ;
    destp += iuse2 ;
    EVP_CipherFinal_ex(&ctx, destp, &iuse2) ;
    destp += iuse2 ;
    iuse2= ( destp - buffer2 ) ;

    EVP_CIPHER_CTX_cleanup(&ctx);

    EVP_cleanup() ;

    encode_asc85(printbuf, sizeof(printbuf), test, strlen(test) +1) ;
    printf("SRC: %s\n", printbuf) ;
    encode_asc85(printbuf, sizeof(printbuf), buffer, iuse) ;
    printf("ENC: %s\n", printbuf) ;
    encode_asc85(printbuf, sizeof(printbuf), buffer2, iuse2) ;
    printf("DEC: %s\nout: %s\n", printbuf, buffer2) ;
}
예제 #5
0
static BUF_MEM *
cipher(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl,
        const unsigned char *key, const unsigned char *iv, int enc, const BUF_MEM * in)
{
    BUF_MEM * out = NULL;
    EVP_CIPHER_CTX * tmp_ctx = NULL;
    int i;
    unsigned long flags;

    check(in, "Invalid arguments");

    if (ctx)
        tmp_ctx = ctx;
    else {
        tmp_ctx = EVP_CIPHER_CTX_new();
        if (!tmp_ctx)
            goto err;
        EVP_CIPHER_CTX_init(tmp_ctx);
        if (!EVP_CipherInit_ex(tmp_ctx, type, impl, key, iv, enc))
            goto err;
    }

    flags = EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(tmp_ctx));

    if (flags & EVP_CIPH_NO_PADDING) {
        i = in->length;
        check((in->length % EVP_CIPHER_block_size(type) == 0), "Data is not of blocklength");
    } else
        i = in->length + EVP_CIPHER_block_size(type);

    out = BUF_MEM_create(i);
    if (!out)
        goto err;

    if (!EVP_CipherUpdate(tmp_ctx, (unsigned char *) out->data, &i,
            (unsigned char *) in->data, in->length))
        goto err;
    out->length = i;

    if (!EVP_CipherFinal_ex(tmp_ctx, (unsigned char *) (out->data + out->length),
            &i))
            goto err;

    if (!(flags & EVP_CIPH_NO_PADDING))
        out->length += i;

    if (!ctx)
        EVP_CIPHER_CTX_free(tmp_ctx);

    return out;

err:

    if (out)
        BUF_MEM_free(out);
    if (!ctx && tmp_ctx)
        EVP_CIPHER_CTX_free(tmp_ctx);

    return NULL;
}
예제 #6
0
파일: xcbc.c 프로젝트: grivet/XCBC
int
XCBC_Final(XCBC_CTX *xctx,
	   uint8_t  *out)
{
	int bl, n, outl;

	bl = EVP_CIPHER_CTX_block_size(xctx->ctx);

	/* xctx->r = M[n] */
	if (xctx->size == bl) {
		for (n = 0; n < bl; n++)
			xctx->m[n] = xctx->r[n] ^ xctx->e[n] ^ xctx->k2[n];
	} else {
		for (n = xctx->size; n < bl; n++)
			xctx->r[n] = (n == xctx->size) ? 0x80 : 0x00;
		for (n = 0; n < bl; n++) {
			xctx->m[n] = xctx->r[n] ^ xctx->e[n] ^ xctx->k3[n];
		}
	}
	OPENSSL_try(EVP_CipherUpdate(xctx->ctx,
				     xctx->e, &outl,
				     xctx->m, bl),
		    "cipher update error (finalizing)", return0);
	memcpy(out, xctx->e, bl);

	return 1;

return0:
	return 0;
}
예제 #7
0
	/*
		the size of outBuf must be larger than inBufSize + blockSize
		@retval positive or 0 : writeSize(+blockSize)
		@retval -1 : error
	*/
	int update(char *outBuf, const char *inBuf, int inBufSize)
	{
		int outLen = 0;
		int ret = EVP_CipherUpdate(&ctx_, cybozu::cast<uint8_t*>(outBuf), &outLen, cybozu::cast<const uint8_t*>(inBuf), inBufSize);
		if (ret != 1) return -1;
		return outLen;
	}
예제 #8
0
void encryptfile(FILE * fpin,FILE* fpout,unsigned char* key, unsigned char* iv)
{
	//Using openssl EVP to encrypt a file

	
	const unsigned bufsize = 4096;
	unsigned char* read_buf = malloc(bufsize);
	unsigned char* cipher_buf ;
	unsigned blocksize;
	int out_len;

	EVP_CIPHER_CTX ctx;

	EVP_CipherInit(&ctx,EVP_aes_256_cbc(),key,iv,1);
	blocksize = EVP_CIPHER_CTX_block_size(&ctx);
	cipher_buf = malloc(bufsize+blocksize);

	// read file and write encrypted file until eof
	while(1)
	{
		int bytes_read = fread(read_buf,sizeof(unsigned char),bufsize,fpin);
		EVP_CipherUpdate(&ctx,cipher_buf,&out_len,read_buf, bytes_read);
		fwrite(cipher_buf,sizeof(unsigned char),out_len,fpout);
		if(bytes_read < bufsize)
		{
			break;//EOF
		}
	}

	EVP_CipherFinal(&ctx,cipher_buf,&out_len);
	fwrite(cipher_buf,sizeof(unsigned char),out_len,fpout);

	free(cipher_buf);
	free(read_buf);
}
예제 #9
0
static int cipher_context_update(cipher_ctx_t *ctx, uint8_t *output, size_t *olen,
                                 const uint8_t *input, size_t ilen)
{
#ifdef USE_CRYPTO_APPLECC
    cipher_cc_t *cc = &ctx->cc;
    if (cc->valid == kCCContextValid) {
        CCCryptorStatus ret;
        ret = CCCryptorUpdate(cc->cryptor, input, ilen, output,
                              ilen, olen);
        return (ret == kCCSuccess) ? 1 : 0;
    }
#endif
    cipher_evp_t *evp = &ctx->evp;
#if defined(USE_CRYPTO_OPENSSL)
    int err = 0, tlen = *olen;
    err = EVP_CipherUpdate(evp, (uint8_t *)output, &tlen,
                           (const uint8_t *)input, ilen);
    *olen = tlen;
    return err;
#elif defined(USE_CRYPTO_POLARSSL)
    return !cipher_update(evp, (const uint8_t *)input, ilen,
                          (uint8_t *)output, olen);
#elif defined(USE_CRYPTO_MBEDTLS)
    return !mbedtls_cipher_update(evp, (const uint8_t *)input, ilen,
                                  (uint8_t *)output, olen);
#endif
}
예제 #10
0
파일: fun.c 프로젝트: jeffjee617/secureVPN
/********************do the cryption part*************************/
int do_crypt(unsigned char *key, unsigned char *iv, char *msg, int *l, int crypt) {
    unsigned char outbuf[BUFSIZE + EVP_MAX_BLOCK_LENGTH];
    int len = *l, outlen, tmplen, i;
    unsigned char input[BUFSIZE];
    
    memcpy(input, msg, len);
    if (DEBUG) {
   	 printf("\nbefore crypted payload: ");
   	 for(i = 0; i < len; i++) printf("%02x", *(input+i));
   	 putchar(10);
    }

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv, crypt);

    if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, input, len)) {
   	 EVP_CIPHER_CTX_cleanup(&ctx);
   	 return 0;
    }
    if(!EVP_CipherFinal_ex(&ctx, outbuf + outlen, &tmplen)) {
   	 EVP_CIPHER_CTX_cleanup(&ctx);
   	 return 0;
    }
    outlen += tmplen;
    if (DEBUG) {
   	 printf("\ncrypted payload: ");
   	 for(i = 0; i < outlen; i++) printf("%02x", *(outbuf+i));
   	 printf("\n");
    }
    memcpy(msg, outbuf, outlen);
    *l = outlen;
    EVP_CIPHER_CTX_cleanup(&ctx);
    return 1;    
}
예제 #11
0
void run(const char *name, unsigned char *buf, int len) {
	int pass = TOTAL_LEN / len;
	
	unsigned char key[32] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
		0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
	
	EVP_CIPHER_CTX ctx;
	EVP_CIPHER_CTX_init(&ctx);
	
	int outlen = 0;
	struct timeval start, end;
	double total_time, throughput;
	
	EVP_CIPHER *cipher = (EVP_CIPHER *) EVP_get_cipherbyname("aes-256-ecb");
	
	EVP_CipherInit_ex(&ctx, cipher, NULL, key, NULL, 1);
	
	gettimeofday(&start, NULL);
	for (int i = 0; i < pass; i++) {
		fprintf(stderr, "%s: Pass %d/%d\n", name, i + 1, pass);
		// note we cannot run multiple pass on the same buffer, the CPU will cache it! (smart bastards at Intel)
		EVP_CipherUpdate(&ctx, buf + i * len, &outlen, buf, len);
		if (len != outlen) {
			fprintf(stderr, "Fatal error: incorrect output size.\n");
		}
	}
	
	gettimeofday(&end, NULL);
	total_time = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec) / 1000000.0;
	throughput = TOTAL_LEN * 8 / total_time / 1000000;
	printf("%s: %u-byte blocks, %lubytes in %f s, Throughput: %fMbps\n", name, len, TOTAL_LEN, total_time, throughput);
	
	EVP_CIPHER_CTX_cleanup(&ctx);
}
예제 #12
0
int crypt(unsigned char *inbuf, int inlen, unsigned char *outbuf, unsigned char key[],unsigned char iv[], int do_encrypt)
        {

        int outlen, mlen;

	
	EVP_CIPHER_CTX ctx;
        EVP_CIPHER_CTX_init(&ctx);
        EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv, do_encrypt);
	outlen = 0;

        if(inlen <= 0) return 0;
        if(!EVP_CipherUpdate(&ctx, outbuf + outlen, &mlen, inbuf, inlen))
        {
                /* Error */
        	EVP_CIPHER_CTX_cleanup(&ctx);
        	return 0;
        }
	outlen += mlen;
        if(!EVP_CipherFinal_ex(&ctx, outbuf + outlen, &mlen))
                {
                /* Error */
                EVP_CIPHER_CTX_cleanup(&ctx);
                return 0;
                }
	outlen += mlen;
        EVP_CIPHER_CTX_cleanup(&ctx);
        return outlen;
        }
예제 #13
0
파일: gcm.c 프로젝트: 0359xiaodong/conceal
JNIEXPORT int JNICALL Java_com_facebook_crypto_cipher_NativeGCMCipher_nativeUpdate(
  JNIEnv* env,
  jobject obj,
  jbyteArray data,
  jint offset,
  jint dataLength,
  jbyteArray output) {

  int bytesWritten = 0;
  EVP_CIPHER_CTX* ctx = Get_Cipher_CTX(env, obj);
  if (!ctx) {
    return CRYPTO_NO_BYTES_WRITTEN;
  }

  jbyte* outputBytes = (*env)->GetByteArrayElements(env, output, NULL);
  if (!outputBytes) {
    return CRYPTO_NO_BYTES_WRITTEN;
  }

  jbyte* dataBytes = (*env)->GetByteArrayElements(env, data, NULL);
  if (!dataBytes) {
    (*env)->ReleaseByteArrayElements(env, output, outputBytes, 0);
    return CRYPTO_NO_BYTES_WRITTEN;
  }

  if (!EVP_CipherUpdate(ctx, outputBytes, &bytesWritten, dataBytes + offset, dataLength)) {
    bytesWritten = CRYPTO_NO_BYTES_WRITTEN;
  }

  (*env)->ReleaseByteArrayElements(env, data, dataBytes, JNI_ABORT);
  (*env)->ReleaseByteArrayElements(env, output, outputBytes, 0);

  return bytesWritten;
}
예제 #14
0
/*
 *  call-seq:
 *     cipher.update(data [, buffer]) -> string or buffer
 *
 *  === Parameters
 *  +data+ is a nonempty string.
 *  +buffer+ is an optional string to store the result.
 */
static VALUE 
ossl_cipher_update(int argc, VALUE *argv, VALUE self)
{
    EVP_CIPHER_CTX *ctx;
    char *in;
    int in_len, out_len;
    VALUE data, str;

    rb_scan_args(argc, argv, "11", &data, &str);

    StringValue(data);
    in = RSTRING_PTR(data);
    if ((in_len = RSTRING_LEN(data)) == 0)
        rb_raise(rb_eArgError, "data must not be empty");
    GetCipher(self, ctx);
    out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);

    if (NIL_P(str)) {
        str = rb_str_new(0, out_len);
    } else {
        StringValue(str);
        rb_str_resize(str, out_len);
    }

    if (!EVP_CipherUpdate(ctx, RSTRING_PTR(str), &out_len, in, in_len))
	ossl_raise(eCipherError, NULL);
    assert(out_len < RSTRING_LEN(str));
    rb_str_set_len(str, out_len);

    return str;
}
예제 #15
0
static int sb_aes_crypt(struct sb_image_ctx *ictx, uint8_t *in_data,
			uint8_t *out_data, int in_len)
{
	EVP_CIPHER_CTX *ctx = &ictx->cipher_ctx;
	int ret, outlen;
	uint8_t *outbuf;

	outbuf = malloc(in_len);
	if (!outbuf)
		return -ENOMEM;
	memset(outbuf, 0, sizeof(in_len));

	ret = EVP_CipherUpdate(ctx, outbuf, &outlen, in_data, in_len);
	if (!ret) {
		ret = -EINVAL;
		goto err;
	}

	if (out_data)
		memcpy(out_data, outbuf, outlen);

err:
	free(outbuf);
	return ret;
}
bool CryptoBuffer::doCrypt(const char *in, int inlen, bool isEncrypt, QByteArray &out)
{
  const int OUTBUF_SIZE = 8*1024;
  unsigned char outbuf[OUTBUF_SIZE + EVP_MAX_BLOCK_LENGTH];

  EVP_CIPHER_CTX ctx;
  EVP_CIPHER_CTX_init(&ctx);
  auto ctxGuard = makeGuard([&ctx] { EVP_CIPHER_CTX_cleanup(&ctx); });

  if (!EVP_CipherInit_ex(&ctx, d->cipher, NULL, d->key, d->iv, isEncrypt))
    return DEBUGRET(false, "EVP_CipherInit_Ex failed");

  const unsigned char *ptr = reinterpret_cast<const unsigned char*>(in);
  int restlen = inlen;
  int outlen;

  while (restlen > 0)
  {
    int readlen = std::min(restlen, OUTBUF_SIZE);
    if (!EVP_CipherUpdate(&ctx, outbuf, &outlen, ptr, readlen))
      return DEBUGRET(false, "EVP_CipherUpdate failed");

    out.append(reinterpret_cast<const char*>(outbuf), outlen);
    ptr += readlen;
    restlen -= readlen;
  }

  if (!EVP_CipherFinal_ex(&ctx, outbuf, &outlen))
    return DEBUGRET(false, "EVP_CipherFinal_ex failed");
  out.append(reinterpret_cast<const char*>(outbuf), outlen);

  return true;
}
예제 #17
0
파일: cipher.cpp 프로젝트: oudream/ucommon
size_t Cipher::put(const uint8_t *data, size_t size)
{
    int outlen;
    size_t count = 0;

    if(!bufaddr)
        return 0;

    if(size % keys.iosize())
        return 0;

    while(bufsize && size + bufpos > bufsize) {
        size_t diff = bufsize - bufpos;
        count += put(data, diff);
        data += diff;
        size -= diff;
    }

    if(!EVP_CipherUpdate((EVP_CIPHER_CTX *)context, bufaddr + bufpos, &outlen, data, (int)size)) {
        release();
        return count;
    }
    bufpos += outlen;
    count += outlen;
    if(bufsize && bufpos >= bufsize) {
        push(bufaddr, bufsize);
        bufpos = 0;
    }
    return count;
}
예제 #18
0
static int
do_cipher(EVP_CIPHER_CTX *cipher_ctx, const u8 *in, size_t in_len,
		u8 **out, size_t *out_len)
{
	const u8 *end;
	u8	*p;
	size_t	bl, done, left, total;

	*out = p = (u8 *) malloc(in_len + EVP_CIPHER_CTX_key_length(cipher_ctx));
	*out_len = total = 0;

	bl = EVP_CIPHER_CTX_block_size(cipher_ctx);
	end = in + in_len;
	while (in < end) {
		if ((left = end - in) > bl)
			left = bl;
		if (!EVP_CipherUpdate(cipher_ctx,
					p + total, (int *) &done,
					(u8 *) in, (int)left))
			goto fail;
		total += done;
		in += left;
	}
	if (1 || total < in_len) {
		if (!EVP_CipherFinal(cipher_ctx, p + total, (int *) &done))
			goto fail;
		total += done;
	}
	*out_len = total;
	return 0;

fail:	free(p);
	return SC_ERROR_INTERNAL;
}
예제 #19
0
파일: cipher.c 프로젝트: world100/11111
/* evp_cipher_ctx method */
static LUA_FUNCTION(openssl_evp_cipher_update)
{
  EVP_CIPHER_CTX* c = CHECK_OBJECT(1, EVP_CIPHER_CTX, "openssl.evp_cipher_ctx");
  size_t inl;
  const char* in = luaL_checklstring(L, 2, &inl);
  int outl = inl + EVP_MAX_BLOCK_LENGTH;
  char* out = OPENSSL_malloc(outl);
  CIPHER_MODE mode;
  int ret = 0;

  lua_rawgetp(L, LUA_REGISTRYINDEX, c);
  mode = lua_tointeger(L, -1);

  if (mode == DO_CIPHER)
    ret = EVP_CipherUpdate(c, (byte*)out, &outl, (const byte*)in, inl);
  else if (mode == DO_ENCRYPT)
    ret = EVP_EncryptUpdate(c, (byte*)out, &outl, (const byte*)in, inl);
  else if (mode == DO_DECRYPT)
    ret = EVP_DecryptUpdate(c, (byte*)out, &outl, (const byte*)in, inl);
  else
    luaL_error(L, "never go here");
  lua_pop(L, 1);

  if (ret == 1)
  {
    lua_pushlstring(L, out, outl);
  }
  OPENSSL_free(out);

  return (ret == 1 ? ret : openssl_pushresult(L, ret));
}
예제 #20
0
파일: bio_enc.c 프로젝트: Muffo/openssl
static int enc_write(BIO *b, const char *in, int inl)
{
    int ret = 0, n, i;
    BIO_ENC_CTX *ctx;
    BIO *next;

    ctx = BIO_get_data(b);
    next = BIO_next(b);
    if ((ctx == NULL) || (next == NULL))
        return 0;

    ret = inl;

    BIO_clear_retry_flags(b);
    n = ctx->buf_len - ctx->buf_off;
    while (n > 0) {
        i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
        if (i <= 0) {
            BIO_copy_next_retry(b);
            return (i);
        }
        ctx->buf_off += i;
        n -= i;
    }
    /* at this point all pending data has been written */

    if ((in == NULL) || (inl <= 0))
        return (0);

    ctx->buf_off = 0;
    while (inl > 0) {
        n = (inl > ENC_BLOCK_SIZE) ? ENC_BLOCK_SIZE : inl;
        if (!EVP_CipherUpdate(ctx->cipher,
                              ctx->buf, &ctx->buf_len,
                              (const unsigned char *)in, n)) {
            BIO_clear_retry_flags(b);
            ctx->ok = 0;
            return 0;
        }
        inl -= n;
        in += n;

        ctx->buf_off = 0;
        n = ctx->buf_len;
        while (n > 0) {
            i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
            if (i <= 0) {
                BIO_copy_next_retry(b);
                return (ret == inl) ? i : ret - inl;
            }
            n -= i;
            ctx->buf_off += i;
        }
        ctx->buf_len = 0;
        ctx->buf_off = 0;
    }
    BIO_copy_next_retry(b);
    return (ret);
}
int
cipher_ctx_update (EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len,
    uint8_t *src, int src_len)
{
  if (!EVP_CipherUpdate (ctx, dst, dst_len, src, src_len))
    crypto_msg(M_FATAL, "%s: EVP_CipherUpdate() failed", __func__);
  return 1;
}
예제 #22
0
파일: BCipher.cpp 프로젝트: 2Quico/netbox
HRESULT CBCipher::do_crypt(VARIANT varInput, VARIANT varOutput, VARIANT* pVal, int enc)
{
	if(!m_ctx.cipher)return SetErrorInfo(s_strAlgoError);

	if(m_iKeySize == EVP_CIPHER_key_length(m_ctx.cipher))
		EVP_CipherInit_ex(&m_ctx, m_ctx.cipher, NULL, m_pKey, m_pIV, enc);
	else
	{
		EVP_CipherInit_ex(&m_ctx, m_ctx.cipher, NULL, NULL, NULL, enc);
		EVP_CIPHER_CTX_set_key_length(&m_ctx, m_iKeySize);
		EVP_CipherInit_ex(&m_ctx, NULL, NULL, m_pKey, m_pIV, enc);
	}

	if(!m_bPadding)EVP_CIPHER_CTX_set_padding(&m_ctx, 0);

	HRESULT hr;
	CBComPtr<IStream> pSrcStream;
	CBComPtr<IStream> pDescStream1;
	IStream* pDescStream;
	CBTempStream mStream;

	hr = CBStream::GetStream(&varInput, &pSrcStream);
	if(FAILED(hr))return hr;

	if(varOutput.vt != VT_ERROR)
	{
		hr = CBStream::GetStream(&varOutput, &pDescStream1, FALSE);
		if(FAILED(hr))return hr;
		pDescStream = pDescStream1;
	}else pDescStream = &mStream;

	BYTE inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
	ULONG inlen, outlen, wrlen;

	while(1)
	{
		hr = pSrcStream->Read(inbuf, sizeof(inbuf), &inlen);
		if(FAILED(hr))return hr;
		if(inlen == 0)break;

		if(!EVP_CipherUpdate(&m_ctx, outbuf, (int*)&outlen, inbuf, inlen))
			return E_FAIL;

		hr = pDescStream->Write(outbuf, outlen, &wrlen);
		if(FAILED(hr))return hr;
	}

	if(!EVP_CipherFinal_ex(&m_ctx, outbuf, (int*)&outlen))
		return E_FAIL;

	hr = pDescStream->Write(outbuf, outlen, &wrlen);
	if(FAILED(hr))return hr;

	if(mStream.GetLength())
		return mStream.GetVariant(pVal);

	return S_OK;
}
예제 #23
0
int cipher_context_update(cipher_ctx_t *evp, uint8_t *output, int *olen, \
                          const uint8_t *input, int ilen) {
#if defined(USE_CRYPTO_OPENSSL)
        return EVP_CipherUpdate(evp, (uint8_t *) output, (size_t *) olen, \
                                (const uint8_t *) input, (size_t) ilen);
#elif defined(USE_CRYPTO_POLARSSL)
        return !cipher_update(evp, (const uint8_t *) input, (size_t) ilen, \
                              (uint8_t *) output, (size_t *) olen);
#endif
}
예제 #24
0
    //key:128
    //encrypt output:nonce(12)+tag(16)+cipher_text
    //no aad
    //
    int Encrypt_AesGcm128(const uint8_t * plain_text, uint32_t plain_text_len,
            const SecureString & key, string & cipher_text){

        cipher_text.clear();
        EVP_CIPHER_CTX ctx;
        EVP_CIPHER_CTX_init(&ctx);

        EVP_CIPHER * cipher=EVP_aes_128_gcm();

        if(1 != EVP_EncryptInit_ex(&ctx, cipher, NULL, NULL, NULL))
            return LIB_ERR;

        unsigned char  nonce[GCM_NONCE_LENGTH]={};
        RAND_bytes(nonce,4);

        struct timeval t={0,0};
        if(0==gettimeofday(&t,NULL)){
            memcpy(&nonce[4],&t.tv_sec,4);
            memcpy(&nonce[8],&t.tv_nsec,4);
        }else{
            RAND_bytes(&nonce[4],GCM_NONCE_LENGTH-4);
        }

        if(1 != EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_IVLEN, GCM_NONCE_LENGTH, NULL))
            return LIB_ERR;

        if(1 != EVP_EncryptInit_ex(&ctx, NULL, NULL, key.data(), &nonce[0]))
            return LIB_ERR;

        cipher_text.reserve(GCM_NONCE_LENGTH+GCM_TAG_LENGTH+plain_text_len);
        cipher_text.append(&nonce[0],GCM_NONCE_LENGTH);
        cipher_text.append(GCM_TAG_LENGTH,0);//fill tag later
        cipher_text.resize(GCM_NONCE_LENGTH+GCM_TAG_LENGTH+plain_text_len);

        //do the real encryption.
        int out_len=plain_text_len;
        const int ret = EVP_CipherUpdate(&ctx,&cipher_text[GCM_NONCE_LENGTH+GCM_TAG_LENGTH],&out_len, plain_text,plain_text_len);
        if(1!=ret){
            cipher_text.clear();
            return LIB_ERR;
        }

        out_len=0;
        if(1 != EVP_CipherFinal_ex(&ctx,cipher_text.end(),out_len) ){
            cipher_text.clear();
            return LIB_ERR;
        }

        /* Get the tag */
        if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, &cipher_text[GCM_NONCE_LENGTH])){
            cipher_text.clear();
            return LIB_ERR;
        }
        return OK;
    }
예제 #25
0
bool Crypto_t::symmetricCipher(const std::vector<unsigned char>& in_buffer, int nid, const std::string& key, const std::string& iv, bool encode, std::vector<unsigned char>& buffer)
{
	// load all cipher modules
	OpenSSL_add_all_ciphers();

	// Select the specific cipher module
	const EVP_CIPHER* cipher = EVP_get_cipherbynid(nid);
	if (!cipher) return false;

	// Each cipher has its own taste for the key and IV. So we need to check if the input key and IV is appropriate
	// for the specific cipher module
	if (key.size() < static_cast<size_t>(EVP_CIPHER_key_length(cipher)) || iv.size() < static_cast<size_t>(EVP_CIPHER_iv_length(cipher)))
	{
		return false;
	}

	EVP_CIPHER_CTX ctx;
	EVP_CIPHER_CTX_init(&ctx);
	EVP_CipherInit_ex(&ctx, cipher, NULL, (const unsigned char*)key.c_str(), (const unsigned char*)iv.c_str(), encode);
	size_t block_size = EVP_CIPHER_block_size(cipher);
	unsigned char* encrypt_buffer = (unsigned char*) malloc(block_size + in_buffer.size());

	// Read the raw buffer and convert to encrypt one. And then collect to the output buffer

	int out_count = 0;
	buffer.clear();
	bool fail = false;

	while (true)
	{
		if (!EVP_CipherUpdate(&ctx, encrypt_buffer, &out_count, &in_buffer[0], in_buffer.size()))
		{
			fail = true;
			break;
		}
		for (int i = 0; i < out_count; i++)
			buffer.push_back(encrypt_buffer[i]);

		// handling the last block
		unsigned char* block = encrypt_buffer + out_count;
		if (!EVP_CipherFinal_ex(&ctx, block, &out_count))
		{
			fail = true;
			break;
		}
		for (int i = 0; i < out_count; i++)
			buffer.push_back(block[i]);
		break;
	}

	// free resource
	free(encrypt_buffer);
	EVP_CIPHER_CTX_cleanup(&ctx);
	return (fail == true) ? (false) : (true);
}
예제 #26
0
파일: afalgtest.c 프로젝트: Vonage/openssl
static int test_afalg_aes_128_cbc(void)
{
    EVP_CIPHER_CTX *ctx;
    const EVP_CIPHER *cipher = EVP_aes_128_cbc();
    unsigned char key[] = "\x5F\x4D\xCC\x3B\x5A\xA7\x65\xD6\
                           \x1D\x83\x27\xDE\xB8\x82\xCF\x99";
    unsigned char iv[] = "\x2B\x95\x99\x0A\x91\x51\x37\x4A\
                          \xBD\x8F\xF8\xC5\xA7\xA0\xFE\x08";

    unsigned char in[BUFFER_SIZE];
    unsigned char ebuf[BUFFER_SIZE + 32];
    unsigned char dbuf[BUFFER_SIZE + 32];
    int encl, encf, decl, decf;
    int ret = 0;

    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
            return 0;
    RAND_bytes(in, BUFFER_SIZE);

    if (!TEST_true(EVP_CipherInit_ex(ctx, cipher, e, key, iv, 1))
            || !TEST_true(EVP_CipherUpdate(ctx, ebuf, &encl, in, BUFFER_SIZE))
            || !TEST_true(EVP_CipherFinal_ex(ctx, ebuf+encl, &encf)))
        goto end;
    encl += encf;

    if (!TEST_true(EVP_CIPHER_CTX_reset(ctx))
            || !TEST_true(EVP_CipherInit_ex(ctx, cipher, e, key, iv, 0))
            || !TEST_true(EVP_CipherUpdate(ctx, dbuf, &decl, ebuf, encl))
            || !TEST_true(EVP_CipherFinal_ex(ctx, dbuf+decl, &decf)))
        goto end;
    decl += decf;

    if (!TEST_int_eq(decl, BUFFER_SIZE)
            || !TEST_mem_eq(dbuf, BUFFER_SIZE, in, BUFFER_SIZE))
        goto end;

    ret = 1;

 end:
    EVP_CIPHER_CTX_free(ctx);
    return ret;
}
예제 #27
0
void Encrypt::write(Slice src, Slice target) {
  checkArgument(src.length() == target.length(), "Target slice is the same length as src slice");
  checkState(State::PROGRESS, State::PROGRESS, "Encryption not in progress");

  int bytesWritten;
  int code = EVP_CipherUpdate(ctx_, target.offset(0), &bytesWritten, src.offset(0), src.length());
  check(code == EVP_SUCCESS, "Chunk encryption failed");
  // GCM will output exactly the same amount of bytes
  check(bytesWritten == static_cast<int>(src.length()),
      "CipherUpdate didn't encrypt the exact chunk");
}
예제 #28
0
static int ber_write(BIO *b, char *in, int inl)
	{
	int ret=0,n,i;
	BIO_ENC_CTX *ctx;

	ctx=(BIO_ENC_CTX *)b->ptr;
	ret=inl;

	BIO_clear_retry_flags(b);
	n=ctx->buf_len-ctx->buf_off;
	while (n > 0)
		{
		i=BIO_write(b->next_bio,&(ctx->buf[ctx->buf_off]),n);
		if (i <= 0)
			{
			BIO_copy_next_retry(b);
			return(i);
			}
		ctx->buf_off+=i;
		n-=i;
		}
	/* at this point all pending data has been written */

	if ((in == NULL) || (inl <= 0)) return(0);

	ctx->buf_off=0;
	while (inl > 0)
		{
		n=(inl > ENC_BLOCK_SIZE)?ENC_BLOCK_SIZE:inl;
		EVP_CipherUpdate(&(ctx->cipher),
			(unsigned char *)ctx->buf,&ctx->buf_len,
			(unsigned char *)in,n);
		inl-=n;
		in+=n;

		ctx->buf_off=0;
		n=ctx->buf_len;
		while (n > 0)
			{
			i=BIO_write(b->next_bio,&(ctx->buf[ctx->buf_off]),n);
			if (i <= 0)
				{
				BIO_copy_next_retry(b);
				return(i);
				}
			n-=i;
			ctx->buf_off+=i;
			}
		ctx->buf_len=0;
		ctx->buf_off=0;
		}
	BIO_copy_next_retry(b);
	return(ret);
	}
예제 #29
0
파일: cms_kari.c 프로젝트: zakjan/openssl
static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
                          const unsigned char *in, size_t inlen,
                          CMS_KeyAgreeRecipientInfo *kari, int enc)
{
    /* Key encryption key */
    unsigned char kek[EVP_MAX_KEY_LENGTH];
    size_t keklen;
    int rv = 0;
    unsigned char *out = NULL;
    int outlen;
    keklen = EVP_CIPHER_CTX_key_length(kari->ctx);
    if (keklen > EVP_MAX_KEY_LENGTH)
        return 0;
    /* Derive KEK */
    if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
        goto err;
    /* Set KEK in context */
    if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc))
        goto err;
    /* obtain output length of ciphered key */
    if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen))
        goto err;
    out = OPENSSL_malloc(outlen);
    if (out == NULL)
        goto err;
    if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, inlen))
        goto err;
    *pout = out;
    *poutlen = (size_t)outlen;
    rv = 1;

 err:
    OPENSSL_cleanse(kek, keklen);
    if (!rv)
        OPENSSL_free(out);
    EVP_CIPHER_CTX_reset(kari->ctx);
    /* FIXME: WHY IS kari->pctx freed here?  /RL */
    EVP_PKEY_CTX_free(kari->pctx);
    kari->pctx = NULL;
    return rv;
}
int
cipher_ctx_update_ad (EVP_CIPHER_CTX *ctx, const uint8_t *src, int src_len)
{
#ifdef HAVE_AEAD_CIPHER_MODES
  int len;
  if (!EVP_CipherUpdate (ctx, NULL, &len, src, src_len))
    crypto_msg(M_FATAL, "%s: EVP_CipherUpdate() failed", __func__);
  return 1;
#else
  ASSERT (0);
#endif
}