Example #1
0
//An encryption function that uses blowish and a variable length key to encrypt
//'size' bytes of data. This function is only really used to encrypt verification
//digests of files
unsigned char *blowfish_enc(unsigned char *key, unsigned char *data, int size)
{
	unsigned char* out = malloc(size);
	int outlen;
	int tmplen;
	unsigned char iv[] = {0}; //TODO maybe not this?
	EVP_CIPHER_CTX ctx;
	EVP_CIPHER_CTX_init(&ctx);
	EVP_EncryptInit_ex(&ctx, EVP_bf_ecb(), NULL, key, iv);
	EVP_CIPHER_CTX_set_padding(&ctx, 0);
	
	EVP_EncryptUpdate(&ctx, out, &outlen, data, size);

	if(!EVP_EncryptFinal_ex(&ctx, out + outlen, &tmplen)) {
		ssl_error("Didn't do encrypt final");
	}
	outlen += tmplen;
	EVP_CIPHER_CTX_cleanup(&ctx);

	return out;
}
Example #2
0
/*
 * aes_icm_set_iv(c, iv) sets the counter value to the exor of iv with
 * the offset
 */
static srtp_err_status_t srtp_aes_icm_openssl_set_iv (void *cv, uint8_t *iv, srtp_cipher_direction_t dir)
{
    srtp_aes_icm_ctx_t *c = (srtp_aes_icm_ctx_t *)cv;
    v128_t nonce;

    /* set nonce (for alignment) */
    v128_copy_octet_string(&nonce, iv);

    debug_print(srtp_mod_aes_icm, "setting iv: %s", v128_hex_string(&nonce));

    v128_xor(&c->counter, &c->offset, &nonce);

    debug_print(srtp_mod_aes_icm, "set_counter: %s", v128_hex_string(&c->counter));

    if (!EVP_EncryptInit_ex(c->ctx, NULL,
                            NULL, NULL, c->counter.v8)) {
        return srtp_err_status_fail;
    } else {
        return srtp_err_status_ok;
    }
}
/**
 * Create an 256 bit key and IV using the supplied key_data. salt can be added for taste.
 * Fills in the encryption and decryption ctx objects and returns 0 on success
 **/
int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP_CIPHER_CTX *e_ctx)
{
  int i, nrounds = 5;
  unsigned char key[32], iv[32];
  
  /*
   * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
   * nrounds is the number of times the we hash the material. More rounds are more secure but
   * slower.
   */
  i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
  if (i != 32) {
    printf("Key size is %d bits - should be 256 bits\n", i);
    return -1;
  }

  EVP_CIPHER_CTX_init(e_ctx);
  EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);

  return 0;
}
Example #4
0
/* 
 * Encrypts the plaintext and sets it to out
 * @param message: the plaintext string
 * @param length: the number of chars for the plaintext
 * @param encKey: the aes 256 key
 * @param encIv: the aes 128 iv
 * @param out: where the enc message is put
 */
unsigned int aes_encrypt_message(unsigned char *message, unsigned int length, unsigned char *encKey, unsigned char *encIv, unsigned char **out) {
    unsigned char *encMsg = (unsigned char *)malloc(length*(unsigned char) + AES_BLOCK_SIZE);
    EVP_CIPHER_CTX *ctx;
    int len;
    int ciphertext_len;

    if (!(ctx = EVP_CIPHER_CTX_new())) {
        printf ("EVP_CIPHER_CTX_new() failed\n");
        exit (EXIT_FAILURE);
    }

    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, encKey, encIv)) {
        printf ("EVP_EncryptInit_ex failed\n");
        exit (EXIT_FAILURE);
    }

    if (1 != EVP_EncryptUpdate(ctx, encMsg, &len, message, length)) {
        printf ("EVP_ENcryptUpdate failed\n");
        exit (EXIT_FAILURE);
    }

    ciphertext_len = len;

    if (1 != EVP_EncryptFinal_ex(ctx, encMsg + len, &len)) {
        printf ("EVP_EncryptFinal_ex() failed\n");
        exit (EXIT_FAILURE);
    }

    ciphertext_len += len;

    EVP_CIPHER_CTX_free(ctx);

    *(encMsg + ciphertext_len) = '\0';

    if (Base64Encode(encMsg, ciphertext_len, (char **)out) < 0) {
        printf ("Base64Encode in aes_encrypt_message failed\n");
    }

    return ciphertext_len;
}
Example #5
0
/**
 * AES-ECB-PKCS5Padding加密
 *
 * LUA示例:
 * local codec = require('codec')
 * local src = 'something'
 * local key = [[...]] --16位数字串
 * local bs = codec.aes_encrypt(src, key)
 * local dst = codec.base64_encode(bs) --BASE64密文
 */
static int codec_aes_encrypt(lua_State *L)
{
    size_t len;
    const char *src = luaL_checklstring(L, 1, &len);
    char *key = luaL_checkstring(L, 2);

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);

    int ret = EVP_EncryptInit_ex(&ctx, EVP_aes_128_ecb(), NULL, (unsigned char *)key, NULL);
    if(ret != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return luaL_error(L, "EVP encrypt init error");
    }

    int dstn = len + 128, n, wn;
    char dst[dstn];
    memset(dst, 0, dstn);

    ret = EVP_EncryptUpdate(&ctx, (unsigned char *)dst, &wn, (unsigned char *)src, len);
    if(ret != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return luaL_error(L, "EVP encrypt update error");
    }
    n = wn;

    ret = EVP_EncryptFinal_ex(&ctx, (unsigned char *)(dst + n), &wn);
    if(ret != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return luaL_error(L, "EVP encrypt final error");
    }
    EVP_CIPHER_CTX_cleanup(&ctx);
    n += wn;

    lua_pushlstring(L, dst, n);
    return 1;
}
Example #6
0
static int encrypt(void *plaintext, size_t plaintext_len, void *key, void *iv, void *ciphertext) {
	EVP_CIPHER_CTX *ctx;

	int len;
	int ciphertext_len;

	// initialize the CryptoExcreter
	if(!(ctx = EVP_CIPHER_CTX_new())) {
		secreteLibSSLError();
	}

	/* Initialise the encryption operation. IMPORTANT - ensure you use a key
	* and IV size appropriate for your cipher
	* In this example we are using 256 bit AES (i.e. a 256 bit key). The
	* IV size for *most* modes is the same as the block size. For AES this
	* is 128 bits */
	if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
		secreteLibSSLError();
	}

	// encrypt pls
	if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
		secreteLibSSLError();
	}

	ciphertext_len = len;

	// finalize
	if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
		secreteLibSSLError();
	}

	ciphertext_len += len;

	// Clean up
	EVP_CIPHER_CTX_free(ctx);

	return ciphertext_len;
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
  unsigned char *iv, unsigned char *ciphertext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int ciphertext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    handleErrors();

  /* Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */
  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    handleErrors();
  ciphertext_len = len;

  /* 
    Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */
  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}
Example #8
0
/**
* 功能描述:3DES解密
* @param pData:原始数据
* @param ilen: 原始数据长度
* @param ppDecryptData: 解密后数据
* @return -1: 失败, 其他: 解密数据长度
**/
int TripleDESDecrypt(const char* pData, int ilen, char** ppDecryptData)
{
    /*密钥*/
    unsigned char key[24] = {43,14,54,109,109,8,84,87,116,30,19,68,35,51,83,72,16,2,83,48,117,85,9,80};
    /*初始化向量*/
    unsigned char iv[8] = {111,121,47,42,75,34,33,124};

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    int rc = EVP_EncryptInit_ex(&ctx,EVP_des_ede3_cbc(),NULL,key,iv);
    if (rc != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return -1;
    }

    int outlen = ilen + 1;
    *ppDecryptData = (char*)malloc(outlen);
    memset(*ppDecryptData, 0 , outlen);

    rc = EVP_DecryptUpdate(&ctx, (unsigned char*)(*ppDecryptData), &outlen, (unsigned char*)pData, ilen);
    if(rc != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        free(*ppDecryptData);
        return -1;
    }
    int outlentmp = 0;
    rc = EVP_DecryptFinal_ex(&ctx, (unsigned char*)(*ppDecryptData) + outlen,&outlentmp);
    if(rc != 1)
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        free(*ppDecryptData);
        return -1;
    }
    outlen += outlentmp;
    EVP_CIPHER_CTX_cleanup(&ctx);
    return outlen;
}
Example #9
0
size32_t aesEncrypt(MemoryBuffer &out, size32_t inSz, const void *inBytes, size32_t keyLen, const char *key, const char iv[aesBlockSize])
{
    if (0 == inSz)
        return 0;
    OwnedEVPCipherCtx ctx(EVP_CIPHER_CTX_new());
    if (!ctx)
        throw makeEVPException(0, "Failed EVP_CIPHER_CTX_new");
    /* Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     * */
    if (!iv) iv = staticAesIV;
    if (1 != EVP_EncryptInit_ex(ctx, getAesCipher(keyLen), nullptr, (const unsigned char *)key, (const unsigned char *)iv))
        throw makeEVPException(0, "Failed EVP_EncryptInit_ex");

    /* Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */

    const size32_t cipherBlockSz = 128;
    size32_t outMaxSz = inSz + cipherBlockSz/8;
    size32_t startSz = out.length();
    byte *outPtr = (byte *)out.reserveTruncate(outMaxSz);
    int outSz;
    if (1 != EVP_EncryptUpdate(ctx, (unsigned char *)outPtr, &outSz, (unsigned char *)inBytes, inSz))
        throw makeEVPException(0, "Failed EVP_EncryptUpdate");
    int ciphertext_len = outSz;

    /* Finalise the encryption. Further ciphertext bytes may be written at
     * this stage.
     */
    if (1 != EVP_EncryptFinal_ex(ctx, outPtr + outSz, &outSz))
        throw makeEVPException(0, "Failed EVP_EncryptFinal_ex");
    ciphertext_len += outSz;
    out.setLength(startSz+ciphertext_len); // truncate length of 'out' to final size
    return (size32_t)ciphertext_len;
}
int Crypt::enc_data(uint8_t *plain_text, int plain_text_len, uint8_t *cipher_text, uint64_t k_nas_enc) {
	EVP_CIPHER_CTX *ctx;
	int len;
	int cipher_text_len;

	if (!(ctx = EVP_CIPHER_CTX_new())) {
		handle_crypt_error();
	}
	if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
		handle_crypt_error();
	}
	if (1 != EVP_EncryptUpdate(ctx, cipher_text, &len, plain_text, plain_text_len)) {
		handle_crypt_error();
	}
	cipher_text_len = len;
	if (1 != EVP_EncryptFinal_ex(ctx, cipher_text + len, &len)) {
		handle_crypt_error(); 
	}
	cipher_text_len += len;
	EVP_CIPHER_CTX_free(ctx);
	return cipher_text_len;
}
Example #11
0
int
encrypt_data(const void *in, int inlen, void *out, int *outlen,
             const void *iv, const void *key)
{
    int len;

    ERR_clear_error();

    cryptutil_init();

    /* In this we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits */
    if(EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
        log_crypt_err("Not able to initialize encrypt context for AES-256");
        return 0;
    }

    /* Provide the message to be encrypted, and obtain the encrypted output */
    if(EVP_EncryptUpdate(&ctx, out, &len, in, inlen) != 1) {
        log_crypt_err("Not able to encrypt using AES-256");
        return 0;
    }

    *outlen = len;

    /* Finalise the encryption. Further ciphertext bytes may be written at
     * this stage
     */
    if(EVP_EncryptFinal_ex(&ctx, out + len, &len) != 1) {
        log_crypt_err("Not able to finalize encryption using AES-256");
        return 0;
    }

    *outlen += len;

    return 1;
}
Example #12
0
/*
 * aes_icm_set_iv(c, iv) sets the counter value to the exor of iv with
 * the offset
 */
err_status_t aes_icm_openssl_set_iv (aes_icm_ctx_t *c, void *iv, int dir)
{
    const EVP_CIPHER *evp;
    v128_t nonce;

    /* set nonce (for alignment) */
    v128_copy_octet_string(&nonce, iv);

    debug_print(mod_aes_icm, "setting iv: %s", v128_hex_string(&nonce));

    v128_xor(&c->counter, &c->offset, &nonce);

    debug_print(mod_aes_icm, "set_counter: %s", v128_hex_string(&c->counter));

    switch (c->key_size) {
    case AES_256_KEYSIZE:
        evp = EVP_aes_256_ctr();
        break;
#ifndef BORINGSSL
    case AES_192_KEYSIZE:
        evp = EVP_aes_192_ctr();
        break;
#endif
    case AES_128_KEYSIZE:
        evp = EVP_aes_128_ctr();
        break;
    default:
        return err_status_bad_param;
        break;
    }

    if (!EVP_EncryptInit_ex(&c->ctx, evp,
                            NULL, c->key.v8, c->counter.v8)) {
        return err_status_fail;
    } else {
        return err_status_ok;
    }
}
bool CryptFileDevice::flush()
{
    if (!m_encrypted)
        return false;

    if (m_wasFlushed)
        return true;

    if (m_buffer.isEmpty())
        return false;

    m_wasFlushed = true;

    int len = m_buffer.length();
    int maxCipherLen = len + AES_BLOCK_SIZE - (len % AES_BLOCK_SIZE) + AES_BLOCK_SIZE;
    int finalLen = 0;
    unsigned char *cipherText = new unsigned char[maxCipherLen];

    EVP_EncryptInit_ex(&m_encCtx, NULL, NULL, NULL, NULL);
    EVP_EncryptUpdate(&m_encCtx, cipherText, &maxCipherLen, (unsigned char *)m_buffer.data(), len);
    EVP_EncryptFinal_ex(&m_encCtx, &cipherText[maxCipherLen], &finalLen);

    len = maxCipherLen;
    if (m_device->pos() >= m_device->size())
        len += finalLen;

    m_device->write((char *)cipherText, len);
    delete[] cipherText;

    m_blockFlush = true;
    seek(pos() + m_buffer.length());
    m_blockFlush = false;
    m_wasSought = false;

    m_buffer.clear();

    return true;
}
Example #14
0
int s3fs::Crypto::encrypt_block(const unsigned char plain[], int inlen, unsigned char outbuf[])
{
    int outlen;
    int tmplen;

    EVP_CIPHER_CTX_init(&ctx);
    EVP_CIPHER_CTX_set_padding(&ctx, 1L);
    EVP_EncryptInit_ex(&ctx, EVP_aes_256_ctr() , NULL, key, iv);    
    if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, plain, inlen))
    {
        cerr << "An error has occurred while encrypting the plain text." << endl;
        EVP_CIPHER_CTX_cleanup(&ctx);
    }
    if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen))
    {
        cerr << "An error has occurred while encrypting the plain text." << endl;
        EVP_CIPHER_CTX_cleanup(&ctx);
    }
    outlen += tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx);

    return outlen;
}
Example #15
0
       bool AESCipher::init2(unsigned char *key_data, int key_data_len)
    {
        int i, nrounds = 1;
        unsigned char key[32], iv[32];

        /*
        * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
        * nrounds is the number of times the we hash the material. More rounds are more secure but
        * slower.
        */
        i = EVP_BytesToKey(EVP_aes_256_cfb(), EVP_md5(), NULL, key_data, key_data_len, nrounds, key, iv);
        if (i != 32) {
            //printf("Key size is %d bits - should be 256 bits/n", i);
            return false;
        }

        EVP_CIPHER_CTX_init(&m_ectx);
        EVP_EncryptInit_ex(&m_ectx, EVP_aes_256_cfb(), NULL, key, iv);

        EVP_CIPHER_CTX_init(&m_dctx);
        EVP_DecryptInit_ex(&m_dctx, EVP_aes_256_cfb(), NULL, key, iv);
        return true;
    }
Example #16
0
/*
 * Encrypt *len bytes of data
 * All data going in & out is considered binary (unsigned char[])
 */
unsigned char *crypto_aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext,
		int *len)
{
	/* max ciphertext len for a n bytes of plaintext is
	 * n + AES_BLOCK_SIZE -1 bytes */
	int c_len = *len + AES_BLOCK_SIZE - 1, f_len = 0;
	unsigned char *ciphertext = (unsigned char *)malloc(c_len);

	if(ciphertext == NULL) {
		LM_ERR("no more system memory\n");
		return NULL;
	}
	/* allows reusing of 'e' for multiple encryption cycles */
	if(!EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL)){
		LM_ERR("failure in EVP_EncryptInit_ex \n");
		free(ciphertext);
		return NULL;
	}

	/* update ciphertext, c_len is filled with the length of ciphertext
	 * generated, *len is the size of plaintext in bytes */
	if(!EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len)){
		LM_ERR("failure in EVP_EncryptUpdate \n");
		free(ciphertext);
		return NULL;
	}

	/* update ciphertext with the final remaining bytes */
	if(!EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len)){
		LM_ERR("failure in EVP_EncryptFinal_ex \n");
		free(ciphertext);
		return NULL;
	}

	*len = c_len + f_len;
	return ciphertext;
}
Example #17
0
// General secure AES 256 CBC encryption routine
bool OldEncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext)
{
    // max ciphertext len for a n bytes of plaintext is
    // n + AES_BLOCK_SIZE - 1 bytes
    int nLen = sPlaintext.size();
    int nCLen = nLen + AES_BLOCK_SIZE;
    int nFLen = 0;

    // Verify key sizes
    if(sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) {
        LogPrintf("crypter EncryptAES256 - Invalid key or block size: Key: %d sIV:%d\n", sKey.size(), sIV.size());
        return false;
    }

    // Prepare output buffer
    sCiphertext.resize(nCLen);

    // Perform the encryption
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();

    if (!ctx) return false;

    bool fOk = true;

    EVP_CIPHER_CTX_init(ctx);
    if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*) &sKey[0], (const unsigned char*) &sIV[0]);
    if (fOk) fOk = EVP_EncryptUpdate(ctx, (unsigned char*) &sCiphertext[0], &nCLen, (const unsigned char*) &sPlaintext[0], nLen);
    if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (unsigned char*) (&sCiphertext[0])+nCLen, &nFLen);
    EVP_CIPHER_CTX_cleanup(ctx);

    EVP_CIPHER_CTX_free(ctx);

    if (!fOk) return false;

    sCiphertext.resize(nCLen + nFLen);
    return true;
}
Example #18
0
/**
 * Create an 256 bit key and IV using the supplied key_data and salt.
 * Fills in the encryption and decryption ctx objects and returns 0 on success
 */
int crypto_aes_init(unsigned char *key_data, int key_data_len,
		unsigned char *salt, EVP_CIPHER_CTX *e_ctx, EVP_CIPHER_CTX *d_ctx)
{
	int i, nrounds = 5;
	int x;
	unsigned char key[32], iv[32];

	/*
	 * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash
	 * the supplied key material.
	 * nrounds is the number of times the we hash the material. More rounds
	 * are more secure but slower.
	 */
	i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt,
			key_data, key_data_len, nrounds, key, iv);
	if (i != 32) {
		LM_ERR("key size is %d bits - should be 256 bits\n", i);
		return -1;
	}

	for(x = 0; x<32; ++x)
		LM_DBG("key: %x iv: %x \n", key[x], iv[x]);

	for(x = 0; x<8; ++x)
		LM_DBG("salt: %x\n", salt[x]);

	if(e_ctx) {
		EVP_CIPHER_CTX_init(e_ctx);
		EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
	}
	if(d_ctx) {
		EVP_CIPHER_CTX_init(d_ctx);
		EVP_DecryptInit_ex(d_ctx, EVP_aes_256_cbc(), NULL, key, iv);
	}

	return 0;
}
Example #19
0
int aes_encrypt(EVP_CIPHER_CTX *e,int in,int out )	 /* this function encryptes the  file:fd is passed as parameter */
{
	char inbuf [SIZE];
	char outbuf[SIZE+AES_BLOCK_SIZE];	
	int inlen = 0,flen=0,outlen =0;
	
		
	if(!EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL)) 				/* allows reusing of e for multiple cipher cycles */
	{
		perror("\n Error,ENCRYPR_INIT:");
		return 1;
	}
	while((inlen = read(in,inbuf,SIZE)) > 0)
	{
		if(!EVP_EncryptUpdate(e,(unsigned char*) outbuf, &outlen,(unsigned char*) inbuf,inlen)) 		/* Update cipher text */
		{
			perror("\n ERROR,ENCRYPR_UPDATE:");
			return 1;
		}
		if(write(out,outbuf,outlen) != outlen)	
		{
			perror("\n ERROR,Cant write encrypted bytes to outfile:");
			return 1;
		}	
	}
	if(!EVP_EncryptFinal_ex(e, (unsigned char*) outbuf, &flen)) 			/* updates the remaining bytes */
	{
		perror("\n ERROR,ENCRYPT_FINAL:");
		return 1;
	}
	if(write(out,outbuf,flen) != flen)
	{
		perror("\n ERROR,Wriring final bytes of data:");
		return 1;
	}
	return 0;	
}
Example #20
0
/*
 * AES encrypt plaintext
 */
unsigned char *oidc_crypto_aes_encrypt(request_rec *r, oidc_cfg *cfg,
		unsigned char *plaintext, int *len) {

	if (oidc_crypto_init(cfg, r->server) == FALSE)
		return NULL;

	/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
	int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
	unsigned char *ciphertext = apr_palloc(r->pool, c_len);

	/* allows reusing of 'e' for multiple encryption cycles */
	if (!EVP_EncryptInit_ex(cfg->encrypt_ctx, NULL, NULL, NULL, NULL)) {
		oidc_error(r, "EVP_EncryptInit_ex failed: %s",
				ERR_error_string(ERR_get_error(), NULL));
		return NULL;
	}

	/* update ciphertext, c_len is filled with the length of ciphertext generated, len is the size of plaintext in bytes */
	if (!EVP_EncryptUpdate(cfg->encrypt_ctx, ciphertext, &c_len, plaintext,
			*len)) {
		oidc_error(r, "EVP_EncryptUpdate failed: %s",
				ERR_error_string(ERR_get_error(), NULL));
		return NULL;
	}

	/* update ciphertext with the final remaining bytes */
	if (!EVP_EncryptFinal_ex(cfg->encrypt_ctx, ciphertext + c_len, &f_len)) {
		oidc_error(r, "EVP_EncryptFinal_ex failed: %s",
				ERR_error_string(ERR_get_error(), NULL));
		return NULL;
	}

	*len = c_len + f_len;

	return ciphertext;
}
Example #21
0
/**
 * Create an 256 bit key and IV using the supplied key_data. salt can be added for taste.
 * Fills in the encryption and decryption ctx objects and returns 0 on success
 **/
bool OpensslAES::init(const QByteArray &keyData,
                         const QByteArray &saltData)
{
    int i, nrounds = 5;
    unsigned char key[32], iv[32];

    const EVP_CIPHER *evpCipher = getEvpCipher();

    if (evpCipher == 0)
        return false;

    /* 8 bytes (required EVP_BytesToKey) to salt the key_data during key generation. */
    unsigned char salt[8] = {0xAD, 0x7E, 0xF8, 0x14, 0x92, 0x31,0x2B, 0x3F};
    QByteArray saltDataHash = QCryptographicHash::hash(saltData, QCryptographicHash::Md5);
    memcpy(salt, saltDataHash.constData(), 8);

    /*
     * Gen key & IV for choosen algoritm. A SHA1 digest is used to hash the supplied key material.
     * nrounds is the number of times the we hash the material. More rounds are more secure but
     * slower.
     */
    i = EVP_BytesToKey(evpCipher, EVP_sha1(), salt,
                       (const unsigned char*) keyData.constData(), keyData.size(),
                       nrounds, key, iv);
    if (i*8 != m_blockSize) { // i*8 = blocksize in bits
        printf("Key size is %d bytes - should be %d bits\n", i, m_blockSize);
        return false;
    }

    EVP_CIPHER_CTX_init(&m_encoder);
    EVP_EncryptInit_ex(&m_encoder, evpCipher, 0, key, iv);
    EVP_CIPHER_CTX_init(&m_decoder);
    EVP_DecryptInit_ex(&m_decoder, evpCipher, 0, key, iv);

    return true;
}
Example #22
0
QString UBCryptoUtils::symetricEncrypt(const QString& clear)
{
    QByteArray clearData = clear.toUtf8();

    int cipheredLength = clearData.length() + AES_BLOCK_SIZE;
    int paddingLength = 0;
    unsigned char *ciphertext = (unsigned char *)malloc(cipheredLength);

    if(!EVP_EncryptInit_ex(&mAesEncryptContext, NULL, NULL, NULL, NULL))
        return QString();

    if(!EVP_EncryptUpdate(&mAesEncryptContext, ciphertext, &cipheredLength, (unsigned char *)clearData.data(), clearData.length()))
        return QString();

    /* update ciphertext with the final remaining bytes */
    if(!EVP_EncryptFinal_ex(&mAesEncryptContext, ciphertext + cipheredLength, &paddingLength))
        return QString();

    QByteArray cipheredData((const char *)ciphertext, cipheredLength + paddingLength);

    free(ciphertext);

    return QString::fromAscii(cipheredData.toBase64());
}
Example #23
0
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
    if (!fKeySet)
        return false;

    // max ciphertext len for a n bytes of plaintext is
    // n + AES_BLOCK_SIZE - 1 bytes
    int nLen = vchPlaintext.size();
    int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
    vchCiphertext = std::vector<unsigned char> (nCLen);

    EVP_CIPHER_CTX ctx;

    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);

    EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
    EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);

    EVP_CIPHER_CTX_cleanup(&ctx);

    vchCiphertext.resize(nCLen + nFLen);
    return true;
}
Example #24
0
static int do_encrypt(EVP_CIPHER_CTX* aes256, pubnub_bymebl_t msg, uint8_t const* key, uint8_t const* iv, pubnub_bymebl_t *encrypted)
{
    int len = 0;

    if (!EVP_EncryptInit_ex(aes256, EVP_aes_256_cbc(), NULL, key, iv)) {
        ERR_print_errors_cb(print_to_pubnub_log, NULL);
        PUBNUB_LOG_ERROR("Failed to initialize AES-256 encryption\n");
        return -1;
    }
    if (!EVP_EncryptUpdate(aes256, encrypted->ptr, &len, msg.ptr, msg.size)) {
        ERR_print_errors_cb(print_to_pubnub_log, NULL);
        PUBNUB_LOG_ERROR("Failed to AES-256 encrypt the mesage\n");
        return -1;
    }
    encrypted->size = len;
    if (!EVP_EncryptFinal_ex(aes256, encrypted->ptr + len, &len)) {
        ERR_print_errors_cb(print_to_pubnub_log, NULL);
        PUBNUB_LOG_ERROR("Failed to finalize AES-256 encryption\n");
        return -1;
    }
    encrypted->size += len;
    
    return 0;
}
Example #25
0
int crypto_aes_encrypt (crypto_aes_t *crypto,
                        const void *src,
                        unsigned int src_size,
                        void *dst,
                        unsigned int *dst_size)
{
    EVP_CIPHER_CTX *e = &(crypto->enc);
    int psize = 0;
    int fsize = 0;

    /* allows reusing of 'e' for multiple encryption cycles */
    if (!EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL)) {
        pthread_mutex_unlock(&(crypto->lock));
        return(-1);
    }

    /* update ciphertext, c_len is filled with the length of ciphertext
     * generated, *len is the size of plaintext in bytes
     */
    if (!EVP_EncryptUpdate(e, dst, &psize, src, src_size)) {
        pthread_mutex_unlock(&(crypto->lock));
        return(-2);
    }

    /* update ciphertext with the final remaining bytes */
    if (!EVP_EncryptFinal_ex(e, dst + psize, &fsize)) {
        pthread_mutex_unlock(&(crypto->lock));
        return(-3);
    }

    if (dst_size != NULL)
        *dst_size = psize + fsize;

    pthread_mutex_unlock(&(crypto->lock));
    return(0);
}
        OpenSSLSymmetricCipherContext OpenSSLSymmetricCipher::start(OpenSSLSymmetricCipher::Method method, const SymmetricKey& key, const InitializationVector& iv, bool padding)
        {
            OpenSSLSymmetricCipherContext context(method);

            int r = 0;

            const EVP_CIPHER* evpCipher = getEVPCipher(key);

            EXCEPTION_ASSERT(evpCipher, std::invalid_argument, "No cipher found that can use the supplied key");

            switch (context.method())
            {
            case M_ENCRYPT:
            {
                r = EVP_EncryptInit_ex(context.ctx(), evpCipher, NULL, &key.data()[0], &iv.data()[0]);
                break;
            }
            case M_DECRYPT:
            {
                r = EVP_DecryptInit_ex(context.ctx(), evpCipher, NULL, &key.data()[0], &iv.data()[0]);
                break;
            }
            default:
            {
                THROW_EXCEPTION_WITH_LOG(std::runtime_error, "Unhandled method");
            }
            }

            EXCEPTION_ASSERT_WITH_LOG(r == 1, OpenSSLException, "");

            context.data().clear();

            context.setPadding(padding);

            return context;
        }
Example #27
0
/*
 * Encrypt *len bytes of data
 * All data going in & out is considered binary (unsigned char[])
 */
unsigned char *aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len, int *retlen)
{
  /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
	int rc=0;
  int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
	//fprintf(stderr, "Line: %d -- len: %d , c_len: %d , f_len: %d\n", __LINE__, *len, c_len, f_len);
  unsigned char *ciphertext = malloc(c_len);

  /* allows reusing of 'e' for multiple encryption cycles */
	rc=EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL);
//  rc=EVP_EncryptInit_ex(e, EVP_aes_256_cbc(), NULL, key, iv);
	assert(rc==1);
  /* update ciphertext, c_len is filled with the length of ciphertext generated,
    *len is the size of plaintext in bytes */
  rc=EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len);
	assert(rc==1);

  /* update ciphertext with the final remaining bytes */
	  rc=EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len);
		assert(rc==1);

  *len = c_len + f_len;
  return ciphertext;
}
Example #28
0
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
           char *x, const EVP_CIPHER *enc, unsigned char *kstr,
           int klen, pem_password_cb *callback, void *u)
  {
  EVP_CIPHER_CTX ctx;
  int dsize=0,i,j,ret=0;
  unsigned char *p,*data=NULL;
  const char *objstr=NULL;
  char buf[PEM_BUFSIZE];
  unsigned char key[EVP_MAX_KEY_LENGTH];
  unsigned char iv[EVP_MAX_IV_LENGTH];
  
  if (enc != NULL)
    {
    objstr=OBJ_nid2sn(EVP_CIPHER_nid(enc));
    if (objstr == NULL)
      {
      PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_UNSUPPORTED_CIPHER);
      goto err;
      }
    }

  if ((dsize=i2d(x,NULL)) < 0)
    {
    PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_ASN1_LIB);
    dsize=0;
    goto err;
    }
  /* dzise + 8 bytes are needed */
  /* actually it needs the cipher block size extra... */
  data=(unsigned char *)OPENSSL_malloc((unsigned int)dsize+20);
  if (data == NULL)
    {
    PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_MALLOC_FAILURE);
    goto err;
    }
  p=data;
  i=i2d(x,&p);

  if (enc != NULL)
    {
    if (kstr == NULL)
      {
      if (callback == NULL)
        klen=PEM_def_callback(buf,PEM_BUFSIZE,1,u);
      else
        klen=(*callback)(buf,PEM_BUFSIZE,1,u);
      if (klen <= 0)
        {
        PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_READ_KEY);
        goto err;
        }
#ifdef CHARSET_EBCDIC
      /* Convert the pass phrase from EBCDIC */
      ebcdic2ascii(buf, buf, klen);
#endif
      kstr=(unsigned char *)buf;
      }
    RAND_add(data,i,0);/* put in the RSA key. */
    OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
    if (RAND_pseudo_bytes(iv,enc->iv_len) < 0) /* Generate a salt */
      goto err;
    /* The 'iv' is used as the iv and as a salt.  It is
     * NOT taken from the BytesToKey function */
    EVP_BytesToKey(enc,EVP_md5(),iv,kstr,klen,1,key,NULL);

    if (kstr == (unsigned char *)buf) OPENSSL_cleanse(buf,PEM_BUFSIZE);

    OPENSSL_assert(strlen(objstr)+23+2*enc->iv_len+13 <= sizeof buf);

    buf[0]='\0';
    PEM_proc_type(buf,PEM_TYPE_ENCRYPTED);
    PEM_dek_info(buf,objstr,enc->iv_len,(char *)iv);
    /* k=strlen(buf); */

    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx,enc,NULL,key,iv);
    EVP_EncryptUpdate(&ctx,data,&j,data,i);
    EVP_EncryptFinal_ex(&ctx,&(data[j]),&i);
    EVP_CIPHER_CTX_cleanup(&ctx);
    i+=j;
    ret=1;
    }
  else
    {
    ret=1;
    buf[0]='\0';
    }
  i=PEM_write_bio(bp,name,buf,data,i);
  if (i <= 0) ret=0;
err:
  OPENSSL_cleanse(key,sizeof(key));
  OPENSSL_cleanse(iv,sizeof(iv));
  OPENSSL_cleanse((char *)&ctx,sizeof(ctx));
  OPENSSL_cleanse(buf,PEM_BUFSIZE);
  if (data != NULL)
    {
    OPENSSL_cleanse(data,(unsigned int)dsize);
    OPENSSL_free(data);
    }
  return(ret);
  }
Example #29
0
int
seafile_encrypt (char **data_out,
                 int *out_len,
                 const char *data_in,
                 const int in_len,
                 SeafileCrypt *crypt)
{
    *data_out = NULL;
    *out_len = -1;

    /* check validation */
    if ( data_in == NULL || in_len <= 0 || crypt == NULL) {
        g_warning ("Invalid params.\n");
        return -1;
    }

    EVP_CIPHER_CTX ctx;
    int ret;
    int blks;

    /* Prepare CTX for encryption. */
    EVP_CIPHER_CTX_init (&ctx);

    if (crypt->version >= 1)
        ret = EVP_EncryptInit_ex (&ctx,
                                  EVP_aes_128_cbc(), /* cipher mode */
                                  NULL, /* engine, NULL for default */
                                  crypt->key,  /* derived key */
                                  crypt->iv);  /* initial vector */
    else
        ret = EVP_EncryptInit_ex (&ctx,
                                  EVP_aes_128_ecb(), /* cipher mode */
                                  NULL, /* engine, NULL for default */
                                  crypt->key,  /* derived key */
                                  crypt->iv);  /* initial vector */

    if (ret == ENC_FAILURE)
        return -1;

    /* Allocating output buffer. */
    
    /*
      For EVP symmetric encryption, padding is always used __even if__
      data size is a multiple of block size, in which case the padding
      length is the block size. so we have the following:
    */
    
    blks = (in_len / BLK_SIZE) + 1;

    *data_out = (char *)g_malloc (blks * BLK_SIZE);

    if (*data_out == NULL) {
        g_warning ("failed to allocate the ouput buffer.\n");
        goto enc_error;
    }                

    int update_len, final_len;

    /* Do the encryption. */
    ret = EVP_EncryptUpdate (&ctx,
                             (unsigned char*)*data_out,
                             &update_len,
                             (unsigned char*)data_in,
                             in_len);

    if (ret == ENC_FAILURE)
        goto enc_error;


    /* Finish the possible partial block. */
    ret = EVP_EncryptFinal_ex (&ctx,
                               (unsigned char*)*data_out + update_len,
                               &final_len);

    *out_len = update_len + final_len;

    /* out_len should be equal to the allocated buffer size. */
    if (ret == ENC_FAILURE || *out_len != (blks * BLK_SIZE))
        goto enc_error;
    
    EVP_CIPHER_CTX_cleanup (&ctx);

    return 0;

enc_error:

    EVP_CIPHER_CTX_cleanup (&ctx);

    *out_len = -1;

    if (*data_out != NULL)
        g_free (*data_out);

    *data_out = NULL;

    return -1;
    
}
Example #30
0
static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
{
    int rv = 0;

    X509_ALGOR *alg, *kekalg = NULL;
    ASN1_OCTET_STRING *ukm;
    const unsigned char *p;
    unsigned char *dukm = NULL;
    size_t dukmlen = 0;
    int keylen, plen;
    const EVP_CIPHER *kekcipher;
    EVP_CIPHER_CTX *kekctx;

    if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
        goto err;

    /*
     * For DH we only have one OID permissible. If ever any more get defined
     * we will need something cleverer.
     */
    if (OBJ_obj2nid(alg->algorithm) != NID_id_smime_alg_ESDH) {
        DHerr(DH_F_DH_CMS_SET_SHARED_INFO, DH_R_KDF_PARAMETER_ERROR);
        goto err;
    }

    if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, EVP_PKEY_DH_KDF_X9_42) <= 0)
        goto err;

    if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, EVP_sha1()) <= 0)
        goto err;

    if (alg->parameter->type != V_ASN1_SEQUENCE)
        goto err;

    p = alg->parameter->value.sequence->data;
    plen = alg->parameter->value.sequence->length;
    kekalg = d2i_X509_ALGOR(NULL, &p, plen);
    if (!kekalg)
        goto err;
    kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
    if (!kekctx)
        goto err;
    kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
    if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
        goto err;
    if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
        goto err;
    if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
        goto err;

    keylen = EVP_CIPHER_CTX_key_length(kekctx);
    if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0)
        goto err;
    /* Use OBJ_nid2obj to ensure we use built in OID that isn't freed */
    if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx,
                                     OBJ_nid2obj(EVP_CIPHER_type(kekcipher)))
        <= 0)
        goto err;

    if (ukm) {
        dukmlen = ASN1_STRING_length(ukm);
        dukm = BUF_memdup(ASN1_STRING_data(ukm), dukmlen);
        if (!dukm)
            goto err;
    }

    if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
        goto err;
    dukm = NULL;

    rv = 1;
 err:
    if (kekalg)
        X509_ALGOR_free(kekalg);
    if (dukm)
        OPENSSL_free(dukm);
    return rv;
}