コード例 #1
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);
        }
    }
}
コード例 #2
0
ファイル: soter_sym.c プロジェクト: josephwinston/themis
soter_status_t soter_sym_aead_decrypt_update(soter_sym_ctx_t *ctx, const void* cipher_data,  const size_t cipher_data_length, void* plain_data, size_t* plain_data_length){
  if(plain_data==NULL || (*plain_data_length)<(cipher_data_length+EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx))-1)){
    (*plain_data_length)=cipher_data_length+EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx))-1;
    return SOTER_BUFFER_TOO_SMALL;
  }
  return soter_sym_ctx_update(ctx, cipher_data,  cipher_data_length, plain_data, plain_data_length, false);
}
コード例 #3
0
ファイル: cmac.c プロジェクト: johnjohnsp1/opensgx
int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen,
              const EVP_CIPHER *cipher, ENGINE *impl)
{
    static unsigned char zero_iv[EVP_MAX_BLOCK_LENGTH];
#ifdef OPENSSL_FIPS
    if (FIPS_mode()) {
        /* If we have an ENGINE need to allow non FIPS */
        if ((impl || ctx->cctx.engine)
            && !(ctx->cctx.flags & EVP_CIPH_FLAG_NON_FIPS_ALLOW)) {
            EVPerr(EVP_F_CMAC_INIT, EVP_R_DISABLED_FOR_FIPS);
            return 0;
        }
        /*
         * Other algorithm blocking will be done in FIPS_cmac_init, via
         * FIPS_cipherinit().
         */
        if (!impl && !ctx->cctx.engine)
            return FIPS_cmac_init(ctx, key, keylen, cipher, NULL);
    }
#endif
    /* All zeros means restart */
    if (!key && !cipher && !impl && keylen == 0) {
        /* Not initialised */
        if (ctx->nlast_block == -1)
            return 0;
        if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, NULL, zero_iv))
            return 0;
        sgx_memset(ctx->tbl, 0, EVP_CIPHER_CTX_block_size(&ctx->cctx));
        ctx->nlast_block = 0;
        return 1;
    }
    /* Initialiase context */
    if (cipher && !EVP_EncryptInit_ex(&ctx->cctx, cipher, impl, NULL, NULL))
        return 0;
    /* Non-NULL key means initialisation complete */
    if (key) {
        int bl;
        if (!EVP_CIPHER_CTX_cipher(&ctx->cctx))
            return 0;
        if (!EVP_CIPHER_CTX_set_key_length(&ctx->cctx, keylen))
            return 0;
        if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, key, zero_iv))
            return 0;
        bl = EVP_CIPHER_CTX_block_size(&ctx->cctx);
        if (!EVP_Cipher(&ctx->cctx, ctx->tbl, zero_iv, bl))
            return 0;
        make_kn(ctx->k1, ctx->tbl, bl);
        make_kn(ctx->k2, ctx->k1, bl);
        OPENSSL_cleanse(ctx->tbl, bl);
        /* Reset context again ready for first data block */
        if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, NULL, zero_iv))
            return 0;
        /* Zero tbl so resume works */
        sgx_memset(ctx->tbl, 0, bl);
        ctx->nlast_block = 0;
    }
    return 1;
}
コード例 #4
0
ファイル: encrypt.c プロジェクト: pooingx2/SecretGarden
// 입력 파라미터: byte *msg; int msg_len; byte *key;
// 출력 파라미터: byte **enc_msg; int *enc_msg_len;
int encryptAES(byte *msg, int msg_len, byte *key, byte **enc_msg, int *enc_msg_len )
{

		int result = TRUE;
		int templen;

		// EVP 객체를 이용한 AES 암호화
		// ctx(암호화에 사용되는 데이터들이 저장되는 임시 저장소) 초기화
		EVP_CIPHER_CTX ctx;
		EVP_CIPHER_CTX_init(&ctx);

		// 초기화: 암호 알고리즘 할당, 키 할당, IV 할당
		EVP_EncryptInit_ex(&ctx, EVP_des_ofb(), NULL, key, IVseedConstant);

		// 초기화 끝난 후에 암호문 저장될 메모리 할당
		*enc_msg = malloc( msg_len + EVP_CIPHER_CTX_block_size(&ctx) );
		if( enc_msg == NULL )
				return FALSE;

		// 업데이트: 메시지 암호화(마지막 블록 제외)
		if(!EVP_EncryptUpdate(&ctx, *enc_msg, enc_msg_len, msg, msg_len))
				result = FALSE;

		// 종료: 마지막 블록 암호화
		if(!EVP_EncryptFinal_ex(&ctx, enc_msg+(*enc_msg_len), &templen))
				result = FALSE;

		EVP_CIPHER_CTX_cleanup(&ctx);

		return result;
}
コード例 #5
0
ファイル: ossl_cipher.c プロジェクト: hilben/ruby_test
/*
 *  call-seq:
 *     cipher.update(data [, buffer]) -> string or buffer
 *
 *  Encrypts data in a streaming fashion. Hand consecutive blocks of data
 *  to the +update+ method in order to encrypt it. Returns the encrypted
 *  data chunk. When done, the output of Cipher#final should be additionally
 *  added to the result.
 *
 *  === 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;
    unsigned char *in;
    long in_len, out_len;
    VALUE data, str;

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

    StringValue(data);
    in = (unsigned char *)RSTRING_PTR(data);
    if ((in_len = RSTRING_LEN(data)) == 0)
        ossl_raise(rb_eArgError, "data must not be empty");
    GetCipher(self, ctx);
    out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
    if (out_len <= 0) {
	ossl_raise(rb_eRangeError,
		   "data too big to make output buffer: %ld bytes", in_len);
    }

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

    if (!ossl_cipher_update_long(ctx, (unsigned char *)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;
}
コード例 #6
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;
}
コード例 #7
0
ファイル: AesPasswordCipher.cpp プロジェクト: glandu2/librzu
bool AesPasswordCipher::decrypt(const uint8_t* input, size_t input_size, std::vector<uint8_t>& output) {
	if(!evpCipher)
		evpCipher.reset(EVP_CIPHER_CTX_new());

	if(EVP_DecryptInit_ex(evpCipher.get(), EVP_aes_128_cbc(), nullptr, key, key + 16) <= 0)
		return false;

	int bytesWritten = 0;
	size_t totalLength = 0;
	int blockSize = EVP_CIPHER_CTX_block_size(evpCipher.get());
	output.resize(input_size + blockSize);

	if(EVP_DecryptUpdate(evpCipher.get(), &output[0], &bytesWritten, input, input_size) <= 0)
		return false;

	totalLength += bytesWritten;

	if(EVP_DecryptFinal_ex(evpCipher.get(), &output[0] + totalLength, &bytesWritten) <= 0)
		return false;

	totalLength += bytesWritten;
	output.resize(totalLength);

	return true;
}
コード例 #8
0
ファイル: encrypter.c プロジェクト: roothaxor/Ransom
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
ファイル: cmac.c プロジェクト: AndyPanda95/python-for-android
int CMAC_Final(CMAC_CTX *ctx, unsigned char *out, size_t *poutlen)
	{
	int i, bl, lb;
#ifdef OPENSSL_FIPS
	if (FIPS_mode() && !ctx->cctx.engine)
		return FIPS_cmac_final(ctx, out, poutlen);
#endif
	if (ctx->nlast_block == -1)
		return 0;
	bl = EVP_CIPHER_CTX_block_size(&ctx->cctx);
	*poutlen = (size_t)bl;
	if (!out)
		return 1;
	lb = ctx->nlast_block;
	/* Is last block complete? */
	if (lb == bl)
		{
		for (i = 0; i < bl; i++)
			out[i] = ctx->last_block[i] ^ ctx->k1[i];
		}
	else
		{
		ctx->last_block[lb] = 0x80;
		if (bl - lb > 1)
			memset(ctx->last_block + lb + 1, 0, bl - lb - 1);
		for (i = 0; i < bl; i++)
			out[i] = ctx->last_block[i] ^ ctx->k2[i];
		}
	if (!EVP_Cipher(&ctx->cctx, out, out, bl))
		{
		OPENSSL_cleanse(out, bl);	
		return 0;
		}
	return 1;
	}
コード例 #10
0
std::string problem07() {
    std::ifstream instream;
    instream.open(rootdir + "res/p7.txt", std::ios::in);
    if (!instream.is_open()) {
        std::cerr << "Can't open p7.txt\n";
        return std::string("p07 failed.\n");
    }
    std::string in{};
    std::string line;
    while(std::getline(instream, line)) {
        in += line;
    }
    BinaryBlob b7 = BinaryBlob(in, 64);
    int num_bytes = b7.size();
    int act_num_bytes = 0, tot_bytes = 0;
    unsigned char key[] = "YELLOW SUBMARINE";
    EVP_CIPHER_CTX* my_cipher_ctx = EVP_CIPHER_CTX_new();
    EVP_DecryptInit_ex(my_cipher_ctx, EVP_aes_128_ecb(), NULL, key, NULL);
    unsigned char* out = (unsigned char *) malloc(num_bytes * 2 + EVP_CIPHER_CTX_block_size(my_cipher_ctx));
    if (!out)
        return  "p7 - OOM\n";
    EVP_DecryptUpdate(my_cipher_ctx, out, &act_num_bytes, b7.getRawBuf(), num_bytes);
    tot_bytes += act_num_bytes;
    EVP_DecryptFinal_ex(my_cipher_ctx, out + act_num_bytes, &act_num_bytes);
    tot_bytes += act_num_bytes;
    EVP_CIPHER_CTX_free(my_cipher_ctx);
    BinaryBlob s7 = BinaryBlob(out, tot_bytes);
    return s7.ascii();
}
コード例 #11
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;
}
コード例 #12
0
ファイル: ossl_cipher.c プロジェクト: AdamDotCom/my-rvm
/*
 *  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;
}
コード例 #13
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;
}
コード例 #14
0
ファイル: aes_oneshot.c プロジェクト: cocagne/scratch
unsigned char * aes_oneshot_encrypt( unsigned char * key, int key_len,
                                     unsigned char * salt, int salt_len,
                                     unsigned char * data, int data_len,
                                     int * out_len)
{
   int             nalloc    = 0;
   int             npartial  = 0;
   int             nfinal    = 0;
   unsigned char * encrypted = 0;
   unsigned char   key_buff[SHA256_DIGEST_LENGTH];
   unsigned char   iv_buff[SHA256_DIGEST_LENGTH];

   *out_len = 0;
   
   SHA256( key, key_len, key_buff );
   SHA256( salt, salt_len, iv_buff );

   EVP_CIPHER_CTX ctx;

   EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key_buff, iv_buff);

   nalloc = data_len + EVP_CIPHER_CTX_block_size(&ctx);

   encrypted = malloc( nalloc );

   EVP_EncryptUpdate(&ctx, encrypted, &npartial, data, data_len);

   
   EVP_EncryptFinal_ex(&ctx, encrypted+npartial, &nfinal);

   *out_len = npartial + nfinal;
   
   return encrypted;
}
コード例 #15
0
ファイル: soter_sym.c プロジェクト: josephwinston/themis
soter_status_t soter_sym_ctx_final(soter_sym_ctx_t *ctx,
				   void* out_data,
				   size_t* out_data_length,
				   bool encrypt){
  if((ctx->alg&SOTER_SYM_PADDING_MASK)!=0){
    if((*out_data_length)<EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx))){
      (*out_data_length)=EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx));
      return SOTER_BUFFER_TOO_SMALL;
    }
  }
  if(encrypt){
    SOTER_CHECK(EVP_EncryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)out_data_length)!=0);
  } else {
    SOTER_CHECK(EVP_DecryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)out_data_length)!=0);
  }    
  return SOTER_SUCCESS;
}
コード例 #16
0
ファイル: BCipher.cpp プロジェクト: 2Quico/netbox
STDMETHODIMP CBCipher::get_BlockSize(short *pVal)
{
	if(!m_ctx.cipher)return SetErrorInfo(s_strAlgoError);

	*pVal = EVP_CIPHER_CTX_block_size(&m_ctx);

	return S_OK;
}
コード例 #17
0
ファイル: cmac.c プロジェクト: SylvestreG/bitrig
int
CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen,
    const EVP_CIPHER *cipher, ENGINE *impl)
{
	static unsigned char zero_iv[EVP_MAX_BLOCK_LENGTH];

	/* All zeros means restart */
	if (!key && !cipher && !impl && keylen == 0) {
		/* Not initialised */
		if (ctx->nlast_block == -1)
			return 0;
		if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, NULL, zero_iv))
			return 0;
		memset(ctx->tbl, 0, EVP_CIPHER_CTX_block_size(&ctx->cctx));
		ctx->nlast_block = 0;
		return 1;
	}
	/* Initialiase context */
	if (cipher && !EVP_EncryptInit_ex(&ctx->cctx, cipher, impl, NULL, NULL))
		return 0;
	/* Non-NULL key means initialisation complete */
	if (key) {
		int bl;

		if (!EVP_CIPHER_CTX_cipher(&ctx->cctx))
			return 0;
		if (!EVP_CIPHER_CTX_set_key_length(&ctx->cctx, keylen))
			return 0;
		if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, key, zero_iv))
			return 0;
		bl = EVP_CIPHER_CTX_block_size(&ctx->cctx);
		if (!EVP_Cipher(&ctx->cctx, ctx->tbl, zero_iv, bl))
			return 0;
		make_kn(ctx->k1, ctx->tbl, bl);
		make_kn(ctx->k2, ctx->k1, bl);
		OPENSSL_cleanse(ctx->tbl, bl);
		/* Reset context again ready for first data block */
		if (!EVP_EncryptInit_ex(&ctx->cctx, NULL, NULL, NULL, zero_iv))
			return 0;
		/* Zero tbl so resume works */
		memset(ctx->tbl, 0, bl);
		ctx->nlast_block = 0;
	}
	return 1;
}
コード例 #18
0
ファイル: llblowfishcipher.cpp プロジェクト: HizWylder/GIS
// virtual
U32 LLBlowfishCipher::encrypt(const U8* src, U32 src_len, U8* dst, U32 dst_len)
{
	if (!src || !src_len || !dst || !dst_len) return 0;
	if (src_len > dst_len) return 0;

	// OpenSSL uses "cipher contexts" to hold encryption parameters.
    EVP_CIPHER_CTX context;
    EVP_CIPHER_CTX_init(&context);

	// We want a blowfish cyclic block chain cipher, but need to set 
	// the key length before we pass in a key, so call EncryptInit 
	// first with NULLs.
	EVP_EncryptInit_ex(&context, EVP_bf_cbc(), NULL, NULL, NULL);
	EVP_CIPHER_CTX_set_key_length(&context, (int)mSecretSize);
	
	// Complete initialization.  Per EVP_EncryptInit man page, the
	// cipher pointer must be NULL.  Apparently initial_vector must
	// be 8 bytes for blowfish, as this is the block size.
    unsigned char initial_vector[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
	EVP_EncryptInit_ex(&context, NULL, NULL, mSecret, initial_vector);

    int blocksize = EVP_CIPHER_CTX_block_size(&context);
    int keylen = EVP_CIPHER_CTX_key_length(&context);
    int iv_length = EVP_CIPHER_CTX_iv_length(&context);
    lldebugs << "LLBlowfishCipher blocksize " << blocksize
		<< " keylen " << keylen
		<< " iv_len " << iv_length
		<< llendl;

	int output_len = 0;
	int temp_len = 0;
	if (!EVP_EncryptUpdate(&context,
			dst,
			&output_len,
			src,
			src_len))
	{
		llwarns << "LLBlowfishCipher::encrypt EVP_EncryptUpdate failure" << llendl;
		goto ERROR;
	}

	// There may be some final data left to encrypt if the input is
	// not an exact multiple of the block size.
	if (!EVP_EncryptFinal_ex(&context, (unsigned char*)(dst + output_len), &temp_len))
	{
		llwarns << "LLBlowfishCipher::encrypt EVP_EncryptFinal failure" << llendl;
		goto ERROR;
	}
	output_len += temp_len;

	EVP_CIPHER_CTX_cleanup(&context);
	return output_len;

ERROR:
	EVP_CIPHER_CTX_cleanup(&context);
	return 0;
}
コード例 #19
0
ファイル: crypto-evp.c プロジェクト: DavidMulder/heimdal
int
_krb5_evp_encrypt_iov(krb5_context context,
		      struct _krb5_key_data *key,
		      struct krb5_crypto_iov *iov,
		      int niov,
		      krb5_boolean encryptp,
		      int usage,
		      void *ivec)
{
    size_t blocksize, blockmask, wholeblocks;
    struct _krb5_evp_schedule *ctx = key->schedule->data;
    unsigned char tmp[EVP_MAX_BLOCK_LENGTH];
    EVP_CIPHER_CTX *c;
    struct _krb5_evp_iov_cursor cursor;

    c = encryptp ? &ctx->ectx : &ctx->dctx;

    blocksize = EVP_CIPHER_CTX_block_size(c);

    blockmask = ~(blocksize - 1);

    if (ivec)
	EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1);
    else
	EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1);

    _krb5_evp_iov_cursor_init(&cursor, iov, niov);

    while (!_krb5_evp_iov_cursor_done(&cursor)) {

	/* Number of bytes of data in this iovec that are in whole blocks */
        wholeblocks = cursor.current.length & ~blockmask;

        if (wholeblocks != 0) {
            EVP_Cipher(c, cursor.current.data,
                       cursor.current.data, wholeblocks);
            _krb5_evp_iov_cursor_advance(&cursor, wholeblocks);
        }

        /* If there's a partial block of data remaining in the current
         * iovec, steal enough from subsequent iovecs to form a whole block */
        if (cursor.current.length > 0 && cursor.current.length < blocksize) {
	    /* Build up a block's worth of data in tmp, leaving the cursor
	     * pointing at where we started */
            _krb5_evp_iov_cursor_fillbuf(&cursor, tmp, blocksize, NULL);

            EVP_Cipher(c, tmp, tmp, blocksize);

            /* Copy the data in tmp back into the iovecs that it came from,
             * advancing the cursor */
            _krb5_evp_iov_cursor_fillvec(&cursor, tmp, blocksize);
        }
    }

    return 0;
}
コード例 #20
0
ファイル: cms_pwri.c プロジェクト: Acidburn0zzz/openssl
static int kek_unwrap_key(unsigned char *out, size_t *outlen,
		const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx)
	{
	size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
	unsigned char *tmp;
	int outl, rv = 0;
	if (inlen < 2 * blocklen)
		{
		/* too small */
		return 0;
		}
	if (inlen % blocklen)
		{
		/* Invalid size */
		return 0;
		}
	tmp = OPENSSL_malloc(inlen);
	/* setup IV by decrypting last two blocks */
	if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl,
			       in  + inlen - 2 * blocklen, blocklen * 2)
	/* Do a decrypt of last decrypted block to set IV to correct value
	 * output it to start of buffer so we don't corrupt decrypted block
	 * this works because buffer is at least two block lengths long.
	 */
	    || !EVP_DecryptUpdate(ctx, tmp, &outl,
				  tmp  + inlen - blocklen, blocklen)
	/* Can now decrypt first n - 1 blocks */
	    || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen)

	/* Reset IV to original value */
	    || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL)
	/* Decrypt again */
	    || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen))
		goto err;
	/* Check check bytes */
	if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff)
		{
		/* Check byte failure */
		goto err;
		}
	if (inlen < (size_t)(tmp[0] - 4 ))
		{
		/* Invalid length value */
		goto err;
		}
	*outlen = (size_t)tmp[0];
	memcpy(out, tmp + 4, *outlen);
	rv = 1;
	err:
	OPENSSL_cleanse(tmp, inlen);
	OPENSSL_free(tmp);
	return rv;

	}
コード例 #21
0
ファイル: OsEncryption.cpp プロジェクト: John-Chan/sipXtapi
/* //////////////////////////// PRIVATE/PROTECTED //////////////////////////////////// */
OsStatus OsEncryption::init(Direction direction)
{
    OsStatus retval = OS_FAILED;

#if defined(OSENCRYPTION)
    release();

    if (mKeyLen > 0 && mKey != NULL && mDataLen > 0 && mData != NULL)
    {
        ERR_clear_error();

        SSLeay_add_all_algorithms();
        mAlgorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
            PKCS5_DEFAULT_ITER, mSalt, mSaltLen);

        if (mAlgorithm != NULL)
        {
            EVP_CIPHER_CTX_init(&(mContext));
            if (EVP_PBE_CipherInit(mAlgorithm->algorithm, (const char *)mKey, mKeyLen,
                                   mAlgorithm->parameter, &(mContext), (int)direction))
            {
                int blockSize = EVP_CIPHER_CTX_block_size(&mContext);
                int allocLen = mDataLen + mHeaderLen + blockSize + 1; // plus 1 for null terminator on decrypt
                mResults = (unsigned char *)OPENSSL_malloc(allocLen);
                if (mResults == NULL)
                {
                    OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not allocate cryption buffer(size=%d)",
                                  allocLen);
                }
                else
                {
                    retval = OS_SUCCESS;
                }
            }
            else
            {
                OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not initialize cipher");
            }
        }
        else
        {
            OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not initialize cryption algorithm");
        }
    }
    else
    {
        OsSysLog::add(FAC_AUTH, PRI_ERR, "No encryption key(%d) or data(%d) set.\n",
            mKeyLen, mDataLen);
    }
#endif

    return retval;
}
コード例 #22
0
ファイル: p12_decr.c プロジェクト: ciz/openssl
/*
 * Encrypt/Decrypt a buffer based on password and algor, result in a
 * OPENSSL_malloc'ed buffer
 */
unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor,
                                const char *pass, int passlen,
                                const unsigned char *in, int inlen,
                                unsigned char **data, int *datalen, int en_de)
{
    unsigned char *out = NULL;
    int outlen, i;
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();

    if (ctx == NULL) {
        PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    /* Decrypt data */
    if (!EVP_PBE_CipherInit(algor->algorithm, pass, passlen,
                            algor->parameter, ctx, en_de)) {
        PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
                  PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR);
        goto err;
    }

    if ((out = OPENSSL_malloc(inlen + EVP_CIPHER_CTX_block_size(ctx)))
            == NULL) {
        PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    if (!EVP_CipherUpdate(ctx, out, &i, in, inlen)) {
        OPENSSL_free(out);
        out = NULL;
        PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_EVP_LIB);
        goto err;
    }

    outlen = i;
    if (!EVP_CipherFinal_ex(ctx, out + i, &i)) {
        OPENSSL_free(out);
        out = NULL;
        PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
                  PKCS12_R_PKCS12_CIPHERFINAL_ERROR);
        goto err;
    }
    outlen += i;
    if (datalen)
        *datalen = outlen;
    if (data)
        *data = out;
 err:
    EVP_CIPHER_CTX_free(ctx);
    return out;

}
コード例 #23
0
size_t get_ciphertext_size(size_t plaintext_len) {

    size_t block_size = 0;

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    if(!EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, NULL, NULL)) return 0;
    block_size = EVP_CIPHER_CTX_block_size(&ctx);
    EVP_CIPHER_CTX_cleanup(&ctx);

    return plaintext_len + block_size;
}
コード例 #24
0
ファイル: pkcs8.c プロジェクト: RobinWuDev/Qt
static int pbe_crypt(const X509_ALGOR *algor,
                     const uint8_t *pass_raw, size_t pass_raw_len,
                     const uint8_t *in, size_t in_len,
                     uint8_t **out, size_t *out_len,
                     int is_encrypt) {
  uint8_t *buf;
  int n, ret = 0;
  EVP_CIPHER_CTX ctx;
  unsigned block_size;

  EVP_CIPHER_CTX_init(&ctx);

  if (!pbe_cipher_init(algor->algorithm, pass_raw, pass_raw_len,
                       algor->parameter, &ctx, is_encrypt)) {
    OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_UNKNOWN_CIPHER_ALGORITHM);
    return 0;
  }
  block_size = EVP_CIPHER_CTX_block_size(&ctx);

  if (in_len + block_size < in_len) {
    OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_TOO_LONG);
    goto err;
  }

  buf = OPENSSL_malloc(in_len + block_size);
  if (buf == NULL) {
    OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_MALLOC_FAILURE);
    goto err;
  }

  if (!EVP_CipherUpdate(&ctx, buf, &n, in, in_len)) {
    OPENSSL_free(buf);
    OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB);
    goto err;
  }
  *out_len = n;

  if (!EVP_CipherFinal_ex(&ctx, buf + n, &n)) {
    OPENSSL_free(buf);
    OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB);
    goto err;
  }
  *out_len += n;
  *out = buf;
  ret = 1;

err:
  EVP_CIPHER_CTX_cleanup(&ctx);
  return ret;
}
コード例 #25
0
ファイル: cbcmac.c プロジェクト: BeyondChallenge/GmSSL
int CBCMAC_Update(CBCMAC_CTX *ctx, const void *data, size_t datalen)
{
	int block_size;
	int i, n, len;
	const unsigned char *in = (const unsigned char *)data;

	block_size = EVP_CIPHER_CTX_block_size(&ctx->cipher_ctx);

	
	if (ctx->worklen) {
		n = block_size - ctx->worklen;
		if (datalen < n) {
			for (i = 0; i < datalen; i++) {
				ctx->workspace[ctx->worklen + i] = in[i];
			}
			ctx->worklen += datalen;
			return 0;
		} else {
			for (i = 0; i < n; i++) {
				ctx->workspace[ctx->worklen + i] = in[i] ^ ctx->cbcstate[i];
			}
			if (!EVP_EncryptUpdate(&ctx->cipher_ctx, ctx->cbcstate, &len,
				ctx->workspace, block_size)) {
				return 0;
			}
		}

		while (n < datalen) {
			for (i = 0; i < block_size; i++) {
				ctx->workspace[i] = in[n + i] ^ ctx->cbcstate[i];
			}
			n += block_size;
		
			if (!EVP_EncryptUpdate(&ctx->cipher_ctx, ctx->cbcstate, &len,
				ctx->workspace, block_size)) {
				return 0;
			}
		}

		ctx->worklen = datalen - n;
		
		for (i = 0; i < ctx->worklen; i++) {
			ctx->workspace[i] = in[n + i];
		}

	}


	return 0;
}
コード例 #26
0
ファイル: aes-pipe.c プロジェクト: flihp/aes-pipe
int
aes_init (crypt_data_t* crypt_data, crypt_init_t crypt_init)
{
    const EVP_CIPHER* cipher = 0;

    switch (crypt_data->keysize) {
    case 16:
        cipher = EVP_aes_128_cbc ();
        break;
    case 24:
        cipher = EVP_aes_192_cbc ();
        break;
    case 32:
        cipher = EVP_aes_256_cbc ();
        break;
    default:
        fprintf (stderr, "Invalid key size.\n");
        return -1;
    }

    EVP_CIPHER_CTX_init (&crypt_data->ctx);
    if (!crypt_init (&crypt_data->ctx,
                     cipher,
                     NULL,
                     crypt_data->keybuf,
                     crypt_data->ivbuf)) {
        fprintf (stderr, "OpenSSL initialization failed.\n");
        return 1;
    }
    if (verbose) {
        fprintf (stderr,
                 "EVP Initialized\n  Algorithm: %s\n",
                 EVP_CIPHER_name (EVP_CIPHER_CTX_cipher (&crypt_data->ctx)));
        fprintf (stderr, "  IV:  ");
        pp_buf (stderr, crypt_data->ivbuf, crypt_data->ivsize, 16, 2);
        fprintf (stderr, "  Key: ");
        pp_buf (stderr, crypt_data->keybuf, crypt_data->keysize, 16, 2);
    }
    crypt_data->buf_size = INBUFSIZE;
    crypt_data->out_buf =
        (char*)malloc (crypt_data->buf_size +
                       EVP_CIPHER_CTX_block_size (&crypt_data->ctx));
    crypt_data->in_buf = (char*)malloc (crypt_data->buf_size);
    if (!crypt_data->out_buf || !crypt_data->in_buf) {
        fprintf (stderr, "Unable to allocate memory.\n");
        return 1;
    }
    return 0;
}
コード例 #27
0
ファイル: encrypt.c プロジェクト: hynnet/ShadowWeb
void decrypt_buf(struct encryption_ctx *ctx, char *buf, int *len) {
    if (_method == EncryptionTable) {
        table_decrypt(buf, *len);
    } else {
        if (ctx->status == STATUS_EMPTY) {
            int iv_len = encryption_iv_len[_method];
            init_cipher(ctx, buf, iv_len, 0);
            int out_len = *len + EVP_CIPHER_CTX_block_size(ctx->ctx);
            out_len -= iv_len;
            unsigned char *cipher_text = malloc(out_len);
            EVP_CipherUpdate(ctx->ctx, cipher_text, &out_len, buf + iv_len, *len - iv_len);
            memcpy(buf, cipher_text, out_len);
            *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);
        }
    }
}
コード例 #28
0
ファイル: cmac.c プロジェクト: AndyPanda95/python-for-android
int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in)
	{
	int bl;
	if (in->nlast_block == -1)
		return 0;
	if (!EVP_CIPHER_CTX_copy(&out->cctx, &in->cctx))
		return 0;
	bl = EVP_CIPHER_CTX_block_size(&in->cctx);
	memcpy(out->k1, in->k1, bl);
	memcpy(out->k2, in->k2, bl);
	memcpy(out->tbl, in->tbl, bl);
	memcpy(out->last_block, in->last_block, bl);
	out->nlast_block = in->nlast_block;
	return 1;
	}
コード例 #29
0
ファイル: cipher.c プロジェクト: world100/11111
static LUA_FUNCTION(openssl_cipher_ctx_info)
{
  EVP_CIPHER_CTX *ctx = CHECK_OBJECT(1, EVP_CIPHER_CTX, "openssl.evp_cipher_ctx");
  lua_newtable(L);
  AUXILIAR_SET(L, -1, "block_size", EVP_CIPHER_CTX_block_size(ctx), integer);
  AUXILIAR_SET(L, -1, "key_length", EVP_CIPHER_CTX_key_length(ctx), integer);
  AUXILIAR_SET(L, -1, "iv_length", EVP_CIPHER_CTX_iv_length(ctx), integer);
  AUXILIAR_SET(L, -1, "flags", EVP_CIPHER_CTX_flags(ctx), integer);
  AUXILIAR_SET(L, -1, "nid", EVP_CIPHER_CTX_nid(ctx), integer);
  AUXILIAR_SET(L, -1, "type", EVP_CIPHER_CTX_mode(ctx), integer);
  AUXILIAR_SET(L, -1, "mode", EVP_CIPHER_CTX_type(ctx), integer);

  AUXILIAR_SETOBJECT(L, EVP_CIPHER_CTX_cipher(ctx), "openssl.evp_cipher", -1, "cipher");
  return 1;
}
コード例 #30
0
ファイル: e_camellia.c プロジェクト: erbridge/openssl
static int camellia_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t len)
{
    size_t bl = EVP_CIPHER_CTX_block_size(ctx);
    size_t i;
    EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY,ctx);

    if (len < bl)
        return 1;

    for (i = 0, len -= bl; i <= len; i += bl)
        (*dat->block) (in + i, out + i, &dat->ks);

    return 1;
}