Ejemplo n.º 1
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;	
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
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);
}
Ejemplo n.º 4
0
/* INFO: Encrypting the message

         So now that we have set up the program we need to define the "encrypt"
         function. This will take as parameters the plaintext, the length of
         the plaintext, the key to be used, and the IV. We'll also take in a
         buffer to put the ciphertext in(which we assume to be long enough),
         and will return the length of the ciphertext that we have written. 

         Encrypting consists of the following stages:
         * Setting up a context
         * Initialising the encryption operation
         * Providing plaintext bytes to be encrypted
         * Finalising the encryption operation

         During initialisation we will provide an EVP_CIPHER object. In this
         case we are using EVP_aes_256_cbc(), which uses the AES algorithm with
         a 256-bit key in CBC mode. Refer to EVP#Working with Algorithms and
         Modes for further details. */
static 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;

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

	/* INFO: 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();

	/* INFO: 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;

	/* INFO: 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;

	/* info: Clean up */
	EVP_CIPHER_CTX_free(ctx);

	return ciphertext_len;
}
Ejemplo n.º 5
0
static bool aes_encrypt(void *dst, const void *src, size_t len,
			const struct enckey *enckey, const struct iv *iv)
{
	EVP_CIPHER_CTX evpctx;
	int outlen;

	/* Counter mode allows parallelism in future. */
	if (EVP_EncryptInit(&evpctx, EVP_aes_128_ctr(),
			    memcheck(enckey->k.u.u8, sizeof(enckey->k)),
			    memcheck(iv->iv, sizeof(iv->iv))) != 1)
		return false;

	/* No padding, we're a multiple of 128 bits. */
	if (EVP_CIPHER_CTX_set_padding(&evpctx, 0) != 1)
		return false;

	EVP_EncryptUpdate(&evpctx, dst, &outlen, memcheck(src, len), len);
	assert(outlen == len);
	/* Shouldn't happen (no padding) */
	if (EVP_EncryptFinal(&evpctx, dst, &outlen) != 1)
		return false;
	assert(outlen == 0);
	return true;
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
ndn_Error
ndn_AesAlgorithm_encrypt128Ecb
  (const uint8_t *key, size_t keyLength, const uint8_t *plainData,
   size_t plainDataLength, uint8_t *encryptedData, size_t *encryptedDataLength)
{
  EVP_CIPHER_CTX ctx;
  int outLength1, outLength2;

  if (keyLength != ndn_AES_128_BLOCK_SIZE)
    return NDN_ERROR_Incorrect_key_size;

  EVP_EncryptInit(&ctx, EVP_aes_128_ecb(), (const unsigned char*)key, 0);

  EVP_EncryptUpdate
    (&ctx, (unsigned char*)encryptedData, &outLength1,
     (const unsigned char*)plainData, plainDataLength);
  EVP_EncryptFinal
    (&ctx, (unsigned char*)encryptedData + outLength1, &outLength2);

  EVP_CIPHER_CTX_cleanup(&ctx);
  *encryptedDataLength = outLength1 + outLength2;

  return NDN_ERROR_success;
}
Ejemplo n.º 8
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;
}
CK_RV PKCS11_Encryption_OpenSSL::EncryptUpdate(Cryptoki_Session_Context* pSessionCtx, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen)   
{
    OPENSSL_HEADER();
    OpenSSLEncryptData *pEnc;
    
    if(pSessionCtx == NULL || pSessionCtx->EncryptionCtx == NULL) return CKR_SESSION_CLOSED;

    pEnc = (OpenSSLEncryptData*)pSessionCtx->EncryptionCtx;
    
    if(pEnc->IsSymmetric)
    {
        int outLen = *pulEncryptedPartLen;
        
        OPENSSL_CHECKRESULT(EVP_EncryptUpdate((EVP_CIPHER_CTX*)pEnc->Key->ctx, pEncryptedPart, &outLen, pPart, ulPartLen));
        
        *pulEncryptedPartLen = outLen;
    }
    else
    {
        size_t encLen = *pulEncryptedPartLen;
        
        OPENSSL_CHECKRESULT(EVP_PKEY_encrypt((EVP_PKEY_CTX*)pEnc->Key->ctx, pEncryptedPart, &encLen, pPart, ulPartLen));

        *pulEncryptedPartLen = encLen;
    }

    OPENSSL_CLEANUP();

    if(retVal != CKR_OK)
    {
        TINYCLR_SSL_FREE(pEnc);
        pSessionCtx->EncryptionCtx = NULL;
    }

    OPENSSL_RETURN();
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
static int
gen_ossl_encrypt(PX_Cipher *c, const uint8 *data, unsigned dlen,
				 uint8 *res)
{
	ossldata   *od = c->ptr;
	int			outlen;

	if (!od->init)
	{
		EVP_CIPHER_CTX_init(&od->evp_ctx);
		if (!EVP_EncryptInit_ex(&od->evp_ctx, od->evp_ciph, NULL, NULL, NULL))
			return PXE_CIPHER_INIT;
		if (!EVP_CIPHER_CTX_set_key_length(&od->evp_ctx, od->klen))
			return PXE_CIPHER_INIT;
		if (!EVP_EncryptInit_ex(&od->evp_ctx, NULL, NULL, od->key, od->iv))
			return PXE_CIPHER_INIT;
		od->init = true;
	}

	if (!EVP_EncryptUpdate(&od->evp_ctx, res, &outlen, data, dlen))
		return PXE_ERR_GENERIC;

	return 0;
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
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());
}
Ejemplo n.º 14
0
void Crypt::encrypt(unsigned char* plaintext, int plaintextLength, unsigned char *key, unsigned char* iv, unsigned char* ciphertext, int* ciphertextLength) {

	EVP_CIPHER_CTX *ctx;

	int 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))
	if (1 != EVP_EncryptInit_ex(ctx, EVP_des_ede3_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, plaintextLength))
		handleErrors();
	(*ciphertextLength) = len;

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

	/* Clean up */
	EVP_CIPHER_CTX_free(ctx);
}
Ejemplo n.º 15
0
void
PEM_SealUpdate(PEM_ENCODE_SEAL_CTX *ctx, unsigned char *out, int *outl,
    unsigned char *in, int inl)
{
	unsigned char buffer[1600];
	int i, j;

	*outl = 0;
	EVP_SignUpdate(&ctx->md, in, inl);
	for (;;) {
		if (inl <= 0)
			break;
		if (inl > 1200)
			i = 1200;
		else
			i = inl;
		EVP_EncryptUpdate(&ctx->cipher, buffer, &j, in, i);
		EVP_EncodeUpdate(&ctx->encode, out, &j, buffer, j);
		*outl += j;
		out += j;
		in += i;
		inl -= i;
	}
}
/**
 *
 * \brief Encrypt a BIGNUM data using AES-256 OFB mode.
 *
 * \param[in/out] number A pointer to the BIGNUM structure. The
 *       encrypted data replaces the plain text in this
 *       structure
 * \param[in] iv A pointer to a 16-byte IV buffer
 * \param[in] aes_key A pointer to a 32-byte AES key buffer
 * \return 1 for success
 */
int eccx08_BN_encrypt(BIGNUM *number, uint8_t *iv, uint8_t *aes_key)
{
    int ret = 0;
    int len;
    int cipher_len;
    uint8_t *plaintext = NULL;
    uint8_t *ciphertext = NULL;

    EVP_CIPHER_CTX *ctx = NULL;

    eccx08_debug("eccx08_BN_encrypt()\n");

    len = BN_num_bytes(number);
    plaintext = (char *)OPENSSL_malloc(len);
    if (!plaintext) {
        goto err;
    }
    ciphertext = (char *)OPENSSL_malloc(len);
    if (!ciphertext) {
        goto err;
    }
    BN_bn2bin(number, plaintext);

    /* Create and initialise the context */
    if (!(ctx = EVP_CIPHER_CTX_new())) {
        eccx08_debug("eccx08_BN_encrypt() context init failed\n");
        goto err;
    }

    /* Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher.
     * We are using 256 bit AES (i.e. a 256 bit key), OFB mode (plain_len == cipher_len). 
     * 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_ofb(), NULL, aes_key, iv)) {
        eccx08_debug("eccx08_BN_encrypt() encrypt init failed\n");
        goto err;
    }

    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, len)) {
        eccx08_debug("eccx08_BN_encrypt() encrypt update failed\n");
        goto err;
    }
    cipher_len = len;

    if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
        eccx08_debug("eccx08_BN_encrypt() encrypt final failed\n");
        goto err;
    }
    cipher_len += len;
    BN_bin2bn(ciphertext, cipher_len, number);
    ret = 1;

err:
    if (ctx) {
        EVP_CIPHER_CTX_free(ctx);
    }
    if (plaintext) {
        OPENSSL_free(plaintext);
    }
    if (ciphertext) {
        OPENSSL_free(ciphertext);
    }

    return ret;
}
Ejemplo n.º 17
0
bool client_write(User *user)
{
	//If there is data in the output buffer, crypt it before writing
	if (!user->buffer.getWriteEmpty()) {
		std::vector<char> buf;

		user->buffer.getWriteData(buf);

		//More glue - Fador
		if(user->crypted) {
			//We might have to write some data uncrypted ToDo: fix
			if(user->uncryptedLeft) {
				user->bufferCrypted.addToWrite((uint8_t *)buf.data(),user->uncryptedLeft);
			}
			int p_len = buf.size()-user->uncryptedLeft, f_len = 0;
			if(p_len) {
				uint8_t *buffer = (uint8_t *)malloc(p_len+1);
				EVP_EncryptUpdate(&user->en, (uint8_t *)buffer, &p_len, (const uint8_t *)buf.data()+user->uncryptedLeft, buf.size()-user->uncryptedLeft);
				int written = p_len + f_len;
				user->bufferCrypted.addToWrite((uint8_t *)buffer,written);
				free(buffer);
			}
			user->uncryptedLeft = 0;
		} else {
			user->bufferCrypted.addToWrite((uint8_t *)buf.data(),buf.size());
			user->uncryptedLeft = 0;
		}

		//free(outBuf);
		user->buffer.clearWrite(buf.size());
	}

	//We have crypted data ready to be written
	if(!user->bufferCrypted.getWriteEmpty()) {
		std::vector<char> buf;
		user->bufferCrypted.getWriteData(buf);

		//Try to write the whole buffer
		const int written = send(user->fd, buf.data(), buf.size(), 0);

		//Handle errors
		if (written == SOCKET_ERROR) {
#ifdef WIN32
#define ERROR_NUMBER WSAGetLastError()
			if ((ERROR_NUMBER != WSATRY_AGAIN && ERROR_NUMBER != WSAEINTR && ERROR_NUMBER != WSAEWOULDBLOCK))
#else
#define ERROR_NUMBER errno
			if ((errno != EAGAIN && errno != EINTR))
#endif
			{
				LOG2(ERROR, "Error writing to client, tried to write " + dtos(buf.size()) + " bytes, code: " + dtos(ERROR_NUMBER));
				//delete user;
				user->logged = false;
				ServerInstance->usersToRemove().insert(user);
				return false;
			}
		} else {
			//Remove written amount from the buffer
			user->bufferCrypted.clearWrite(written);
		}

		//If we couldn't write everything at once, add EV_WRITE event calling this function again..
		if (!user->bufferCrypted.getWriteEmpty()) {
			event_add(user->getWriteEvent(), nullptr);
			return false;
		}
	}
	return true;
}
Ejemplo n.º 18
0
void ARC4::UpdateData(int len, uint8 *data)
{
    int outlen = 0;
    EVP_EncryptUpdate(&m_ctx, data, &outlen, data, len);
    EVP_EncryptFinal_ex(&m_ctx, data, &outlen);
}
Ejemplo n.º 19
0
void crypto_des3_encrypt(CryptoDes3 des3, uint32 length, const uint8* in_data, uint8* out_data)
{
	int len;
	EVP_EncryptUpdate(&des3->des3_ctx, out_data, &len, in_data, length);
}
Ejemplo n.º 20
0
// Translates |input| of |input_len| using aes-gcm-128. The |input| will either
// be encrypted or decrypted based on |direction|. The |key|, which must be of
// size |kAesGcmKeyBytes|, and the |nonce|, which must be of size
// |kAesGcmNonceBytes|, will be used for the translation. A new zend string will
// be returned on success, or NULL (with a visible warning) on failure.
static zend_string* AesGcm128Translate(
    int direction, char* input, size_t input_len, char* key, char* nonce) {
  const EVP_CIPHER* aead = EVP_aes_128_gcm();

  zend_string* result = NULL;

  int expected_len = 0;
  int result_len = 0;

  EVP_CIPHER_CTX context;
  EVP_CIPHER_CTX_init(&context);

  do {
    if (direction == TRANSLATE_ENCRYPT) {
      if (EVP_EncryptInit_ex(&context, aead, 0, 0, 0) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateInitGcmError);
        break;
      }

      if (EVP_CIPHER_CTX_ctrl(&context, EVP_CTRL_GCM_SET_IVLEN, 12, 0) != 1 ||
          EVP_EncryptInit_ex(&context, 0, 0, key, nonce) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateKeyNonceError);
        break;
      }

      expected_len = input_len + 16 /* authentication tag */;
      result = zend_string_alloc(expected_len, 0);
      if (!result) {
        php_error_docref(NULL, E_ERROR, kTranslateAllocationError);
        break;
      }

      if (EVP_EncryptUpdate(&context, result->val, &result_len, input, input_len) != 1 ||
          EVP_EncryptFinal_ex(&context, result->val, &result_len) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateEncryptInputError);
        zend_string_release(result);
        result = NULL;
        break;
      }

      if (EVP_CIPHER_CTX_ctrl(&context, EVP_CTRL_GCM_GET_TAG, 16, result->val + input_len) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateEncryptAuthError);
        zend_string_release(result);
        result = NULL;
        break;
      }

      // Encryption successful!

    } else {
      if (EVP_DecryptInit_ex(&context, aead, 0, 0, 0) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateInitGcmError);
        break;
      }

      expected_len = input_len - 16;

      if (EVP_CIPHER_CTX_ctrl(&context, EVP_CTRL_GCM_SET_TAG, 16, input + expected_len) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateDecryptAuthError);
        break;
      }

      if (EVP_CIPHER_CTX_ctrl(&context, EVP_CTRL_GCM_SET_IVLEN, 12, 0) != 1 ||
          EVP_DecryptInit_ex(&context, 0, 0, key, nonce) != 1) {
        php_error_docref(NULL, E_ERROR, kTranslateKeyNonceError);
        break;
      }

      result = zend_string_alloc(expected_len, 0);
      if (!result) {
        php_error_docref(NULL, E_ERROR, kTranslateAllocationError);
        break;
      }

      if (EVP_DecryptUpdate(&context, result->val, &result_len, input, expected_len) != 1 ||
          EVP_DecryptFinal_ex(&context, result->val + expected_len, &result_len) != 1) {
        php_error_docref(NULL, E_WARNING, kTranslateDecryptionWarning);

        zend_string_release(result);
        result = NULL;
        break;
      }

      // Decryption successful!
    }
  } while(0);

  EVP_CIPHER_CTX_cleanup(&context);

  return result;
}
Ejemplo n.º 21
0
static void create_dkek_share(sc_card_t *card, const char *outf, int iter, char *password, int password_shares_threshold, int password_shares_total)
{
	EVP_CIPHER_CTX ctx;
	FILE *out = NULL;
	u8 filebuff[64], key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH],outbuff[64];
	u8 dkek_share[32];
	char *pwd = NULL;
	int r = 0, outlen, pwdlen = 0;

	if (password == NULL) {

		if (password_shares_threshold == -1) {
			ask_for_password(&pwd, &pwdlen);
		} else { // create password using threshold scheme
			r = generate_pwd_shares(card, &pwd, &pwdlen, password_shares_threshold, password_shares_total);
		}

	} else {
		pwd = password;
		pwdlen = strlen(password);
	}

	if (r < 0) {
		printf("Creating DKEK share failed");
		return;
	}

	memcpy(filebuff, magic, sizeof(magic) - 1);

	r = sc_get_challenge(card, filebuff + 8, 8);
	if (r < 0) {
		printf("Error generating random number failed with ", sc_strerror(r));
		return;
	}

	printf("Enciphering DKEK share, please wait...\n");
	EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), filebuff + 8, (u8 *)pwd, pwdlen, iter, key, iv);

	if (password == NULL) {
		OPENSSL_cleanse(pwd, pwdlen);
		free(pwd);
	}

	r = sc_get_challenge(card, dkek_share, sizeof(dkek_share));
	if (r < 0) {
		printf("Error generating random number failed with ", sc_strerror(r));
		return;
	}

	EVP_CIPHER_CTX_init(&ctx);
	EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv);
	if (!EVP_EncryptUpdate(&ctx, filebuff + 16, &outlen, dkek_share, sizeof(dkek_share))) {
		printf("Error encrypting DKEK share\n");
		return;
	}

	if (!EVP_EncryptFinal_ex(&ctx, filebuff + 16 + outlen, &r)) {
		printf("Error encrypting DKEK share\n");
		return;
	}

	out = fopen(outf, "wb");

	if (out == NULL) {
		perror(outf);
		return;
	}

	if (fwrite(filebuff, 1, sizeof(filebuff), out) != sizeof(filebuff)) {
		perror(outf);
		return;
	}

	fclose(out);

	OPENSSL_cleanse(filebuff, sizeof(filebuff));
	EVP_CIPHER_CTX_cleanup(&ctx);

	printf("DKEK share created and saved to %s\n", outf);
}
Ejemplo n.º 22
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;
    
}
BST_STATIC BST_ERR_ENUM_UINT8  EncryptInternal ( BST_UINT8     *pucIn,
                                             BST_UINT32     ulInLen,
                                             BST_UINT8     *pucOut,
                                             BST_UINT32    *pulOutLen,
                                             BST_UINT8     *pucKey )
{
    BST_INT32                           lLen;
    BST_UINT32                          ulLenTest;
    BST_INT32                           lRet;
    BST_UINT8                           aucValue[8];
    EVP_CIPHER_CTX                      Ctx;
    lLen                                = 0;
    ulLenTest                           = 0;
    lRet                                = 0;

    if ( ( BST_NULL_PTR == pucIn ) || ( BST_NULL_PTR == pucOut )
      || ( BST_NULL_PTR == pucKey) || ( BST_NULL_PTR == pulOutLen ) )
    {
        return BST_ERR_PARAM_ENCRYPTER;
    }

    EVP_CIPHER_CTX_init ( &Ctx );

    lRet = EVP_EncryptInit_ex ( &Ctx, EVP_aes_128_ecb (), NULL, pucKey, aucValue );

    if ( lRet != BST_CORE_OPENSSL_SUCCESS )
    {
        return BST_ERR_PARAM_ENCRYPTER;
    }

    *pulOutLen = 0;
    lRet = EVP_EncryptUpdate ( &Ctx, pucOut + *pulOutLen, &lLen, pucIn + *pulOutLen, ulInLen );

    if ( lRet != BST_CORE_OPENSSL_SUCCESS )
    {
        return BST_ERR_PARAM_ENCRYPTER;
    }

    *pulOutLen += lLen;

    ulLenTest = ulInLen >> 4;

    if ( ulInLen != ulLenTest << 4 )
    {
        lRet = EVP_EncryptFinal_ex ( &Ctx, pucOut + *pulOutLen, &lLen );

        if ( lRet != BST_CORE_OPENSSL_SUCCESS )
        {
            return BST_ERR_PARAM_ENCRYPTER;
        }

        *pulOutLen += lLen;
    }

    lRet = EVP_CIPHER_CTX_cleanup ( &Ctx );

    if ( lRet != BST_CORE_OPENSSL_SUCCESS )
    {
        return BST_ERR_PARAM_ENCRYPTER;
    }

    return BST_NO_ERROR_MSG;
}
Ejemplo n.º 24
0
void mpz_urandomb_crypto(mpz_t rop, cryptorand_t state, mp_bitcnt_t n) {
  unsigned long ctr_iv;
  #pragma omp critical(update_iv_counter)
  {
    // update the internal counter, works at most 2^64 times
    ctr_iv = state->ctr++;
  }

  memcpy(state->iv, &ctr_iv, sizeof(ctr_iv)); 
  mp_bitcnt_t nb = n/8+1; // number of bytes

  if(!(state->ctx = EVP_CIPHER_CTX_new())) {
    perror("Error in initializing new cipher context");
    return;
  }
  if(!EVP_EncryptInit_ex(state->ctx, AES_ALGORITHM, NULL, state->key,
        state->iv)) {
    perror("Error in calling EncryptInit");
    return;
  }

  unsigned char *output;
  if(!(output = malloc(2 * (nb + EVP_MAX_IV_LENGTH)))) {
    perror("Error in initializing output buffer");
    return;
  }
  mp_bitcnt_t outlen = 0;

  int in_size = nb;
  unsigned char in[in_size];
  memset(in, 0, in_size);

  while(outlen < nb) {
    int buflen = 0;
    if(!EVP_EncryptUpdate(state->ctx, output+outlen, &buflen, in, in_size)) {
      perror("Error in calling EncryptUpdate");
      goto output_exit;
    }
    outlen += buflen;
  }
  int final_len = 0;
  if(!EVP_EncryptFinal(state->ctx, output+outlen, &final_len)) {
    perror("Error in calling EncryptFinal");
    goto output_exit;
  }
  outlen += final_len;

  if(outlen > nb) {
    outlen = nb; // we will only use nb bytes
  }

  mp_bitcnt_t true_len = outlen + 4;
  mp_bitcnt_t bytelen = outlen;

  unsigned char *buf;
  if(!(buf = malloc(true_len))) {
    perror("Error in initializing buf");
    goto output_exit;
  }
  memset(buf, 0, true_len);
  memcpy(buf+4, output, outlen);
  buf[4] >>= ((outlen*8) - (unsigned int) n);

  for(int i = 3; i >= 0; i--) {
    buf[i] = (unsigned char) (bytelen % (1 << 8));
    bytelen /= (1 << 8);
  }

  // generate a random n-bit number
  FILE *fp;
  if(!(fp = fmemopen(buf, true_len, "rb"))) {
    perror("Error in calling fmemopen");
    goto buf_exit;
  }

  if(!mpz_inp_raw(rop, fp)) {
    fprintf(stderr, "Error in parsing randomness.\n");
  }

  fclose(fp); 

buf_exit:
  free(buf); 

output_exit:
  free(output);

  EVP_CIPHER_CTX_cleanup(state->ctx);
  free(state->ctx);

}
Ejemplo n.º 25
0
static int aead_tls_seal(const EVP_AEAD_CTX *ctx, uint8_t *out,
                         size_t *out_len, size_t max_out_len,
                         const uint8_t *nonce, size_t nonce_len,
                         const uint8_t *in, size_t in_len,
                         const uint8_t *ad, size_t ad_len) {
  AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)ctx->aead_state;
  size_t total = 0;

  if (!tls_ctx->cipher_ctx.encrypt) {
    /* Unlike a normal AEAD, a TLS AEAD may only be used in one direction. */
    OPENSSL_PUT_ERROR(CIPHER, aead_tls_seal, CIPHER_R_INVALID_OPERATION);
    return 0;

  }

  if (in_len + EVP_AEAD_max_overhead(ctx->aead) < in_len ||
      in_len > INT_MAX) {
    /* EVP_CIPHER takes int as input. */
    OPENSSL_PUT_ERROR(CIPHER, aead_tls_seal, CIPHER_R_TOO_LARGE);
    return 0;
  }

  if (max_out_len < in_len + EVP_AEAD_max_overhead(ctx->aead)) {
    OPENSSL_PUT_ERROR(CIPHER, aead_tls_seal, CIPHER_R_BUFFER_TOO_SMALL);
    return 0;
  }

  if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) {
    OPENSSL_PUT_ERROR(CIPHER, aead_tls_seal, CIPHER_R_INVALID_NONCE_SIZE);
    return 0;
  }

  if (ad_len != 13 - 2 /* length bytes */) {
    OPENSSL_PUT_ERROR(CIPHER, aead_tls_seal, CIPHER_R_INVALID_AD_SIZE);
    return 0;
  }

  /* To allow for CBC mode which changes cipher length, |ad| doesn't include the
   * length for legacy ciphers. */
  uint8_t ad_extra[2];
  ad_extra[0] = (uint8_t)(in_len >> 8);
  ad_extra[1] = (uint8_t)(in_len & 0xff);

  /* Compute the MAC. This must be first in case the operation is being done
   * in-place. */
  uint8_t mac[EVP_MAX_MD_SIZE];
  unsigned mac_len;
  HMAC_CTX hmac_ctx;
  HMAC_CTX_init(&hmac_ctx);
  if (!HMAC_CTX_copy_ex(&hmac_ctx, &tls_ctx->hmac_ctx) ||
      !HMAC_Update(&hmac_ctx, ad, ad_len) ||
      !HMAC_Update(&hmac_ctx, ad_extra, sizeof(ad_extra)) ||
      !HMAC_Update(&hmac_ctx, in, in_len) ||
      !HMAC_Final(&hmac_ctx, mac, &mac_len)) {
    HMAC_CTX_cleanup(&hmac_ctx);
    return 0;
  }
  HMAC_CTX_cleanup(&hmac_ctx);

  /* Configure the explicit IV. */
  if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE &&
      !tls_ctx->implicit_iv &&
      !EVP_EncryptInit_ex(&tls_ctx->cipher_ctx, NULL, NULL, NULL, nonce)) {
    return 0;
  }

  /* Encrypt the input. */
  int len;
  if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out, &len, in,
                         (int)in_len)) {
    return 0;
  }
  total = len;

  /* Feed the MAC into the cipher. */
  if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out + total, &len, mac,
                         (int)mac_len)) {
    return 0;
  }
  total += len;

  unsigned block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx);
  if (block_size > 1) {
    assert(block_size <= 256);
    assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE);

    /* Compute padding and feed that into the cipher. */
    uint8_t padding[256];
    unsigned padding_len = block_size - ((in_len + mac_len) % block_size);
    memset(padding, padding_len - 1, padding_len);
    if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out + total, &len, padding,
                           (int)padding_len)) {
      return 0;
    }
    total += len;
  }

  if (!EVP_EncryptFinal_ex(&tls_ctx->cipher_ctx, out + total, &len)) {
    return 0;
  }
  total += len;

  *out_len = total;
  return 1;
}
Ejemplo n.º 26
0
static void test1(const EVP_CIPHER *c,const unsigned char *key,int kn,
		  const unsigned char *iv,int in,
		  const unsigned char *plaintext,int pn,
		  const unsigned char *ciphertext,int cn,
		  int encdec)
    {
    EVP_CIPHER_CTX ctx;
    unsigned char out[4096];
    int outl,outl2;

    printf("Testing cipher %s%s\n",EVP_CIPHER_name(c),
	   (encdec == 1 ? "(encrypt)" : (encdec == 0 ? "(decrypt)" : "(encrypt/decrypt)")));
    hexdump(stdout,"Key",key,kn);
    if(in)
	hexdump(stdout,"IV",iv,in);
    hexdump(stdout,"Plaintext",plaintext,pn);
    hexdump(stdout,"Ciphertext",ciphertext,cn);
    
    if(kn != c->key_len)
	{
	fprintf(stderr,"Key length doesn't match, got %d expected %d\n",kn,
		c->key_len);
	test1_exit(5);
	}
    EVP_CIPHER_CTX_init(&ctx);
    if (encdec != 0)
        {
	if(!EVP_EncryptInit_ex(&ctx,c,NULL,key,iv))
	    {
	    fprintf(stderr,"EncryptInit failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(10);
	    }
	EVP_CIPHER_CTX_set_padding(&ctx,0);

	if(!EVP_EncryptUpdate(&ctx,out,&outl,plaintext,pn))
	    {
	    fprintf(stderr,"Encrypt failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(6);
	    }
	if(!EVP_EncryptFinal_ex(&ctx,out+outl,&outl2))
	    {
	    fprintf(stderr,"EncryptFinal failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(7);
	    }

	if(outl+outl2 != cn)
	    {
	    fprintf(stderr,"Ciphertext length mismatch got %d expected %d\n",
		    outl+outl2,cn);
	    test1_exit(8);
	    }

	if(memcmp(out,ciphertext,cn))
	    {
	    fprintf(stderr,"Ciphertext mismatch\n");
	    hexdump(stderr,"Got",out,cn);
	    hexdump(stderr,"Expected",ciphertext,cn);
	    test1_exit(9);
	    }
	}

    if (encdec <= 0)
        {
	if(!EVP_DecryptInit_ex(&ctx,c,NULL,key,iv))
	    {
	    fprintf(stderr,"DecryptInit failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(11);
	    }
	EVP_CIPHER_CTX_set_padding(&ctx,0);

	if(!EVP_DecryptUpdate(&ctx,out,&outl,ciphertext,cn))
	    {
	    fprintf(stderr,"Decrypt failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(6);
	    }
	if(!EVP_DecryptFinal_ex(&ctx,out+outl,&outl2))
	    {
	    fprintf(stderr,"DecryptFinal failed\n");
	    ERR_print_errors_fp(stderr);
	    test1_exit(7);
	    }

	if(outl+outl2 != cn)
	    {
	    fprintf(stderr,"Plaintext length mismatch got %d expected %d\n",
		    outl+outl2,cn);
	    test1_exit(8);
	    }

	if(memcmp(out,plaintext,cn))
	    {
	    fprintf(stderr,"Plaintext mismatch\n");
	    hexdump(stderr,"Got",out,cn);
	    hexdump(stderr,"Expected",plaintext,cn);
	    test1_exit(9);
	    }
	}

    EVP_CIPHER_CTX_cleanup(&ctx);

    printf("\n");
    }
Ejemplo n.º 27
0
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
                       void *x, const EVP_CIPHER *enc, unsigned char *kstr,
                       int klen, pem_password_cb *callback, void *u)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int dsize = 0, i = 0, j = 0, 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 || EVP_CIPHER_iv_length(enc) == 0
                || EVP_CIPHER_iv_length(enc) > (int)sizeof(iv)
                   /*
                    * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
                    * fits into buf
                    */
                || (strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13)
                   > sizeof(buf)) {
            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;
    }
    /* dsize + 8 bytes are needed */
    /* actually it needs the cipher block size extra... */
    data = 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;
        }
        if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 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
         */
        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
            goto err;

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

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

        ret = 1;
        if ((ctx = EVP_CIPHER_CTX_new()) == NULL
            || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
            || !EVP_EncryptUpdate(ctx, data, &j, data, i)
            || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
            ret = 0;
        if (ret == 0)
            goto err;
        i += j;
    } 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));
    EVP_CIPHER_CTX_free(ctx);
    OPENSSL_cleanse(buf, PEM_BUFSIZE);
    OPENSSL_clear_free(data, (unsigned int)dsize);
    return ret;
}
Ejemplo n.º 28
0
void mexserver() //gestisco i job
{
    
    long ret,quanti=0;
    char key[32] ;
    unsigned char * msg;
    long numblocchi;
    unsigned char **p;
    unsigned char zero[16];
    int index;
    EVP_CIPHER_CTX* ctx;
    unsigned char ** ciphertext;
    
    unsigned char* L;
    printf("mexdalserver\n");
    //key=malloc(32);
    ret = recv(sk, (void *)key, 32, 0);//key
    if(ret==-1) {
        printf("mexserver errore: errore in ricezione idjob dal server!\n");
        exit(1);
    }
    
    printf("key : \n");
    
    printf("key : %s\n",key);
    
    printf("\n");
    if(ret==0) { //server si e' disconnesso
        printf("Il server ha chiuso la connessione!!/n");
        exit(3);
    }
    ret = recv(sk, (void *)&index, sizeof(int), 0); //mi serve per il calcolo di p
    if(ret==-1) {
        printf("mexserver errore: errore in ricezione lunghezza dal server3!\n");
        exit(1);
    }
    printf("ricevuto index: %d\n",index);
    ret = recv(sk, (void *)&quanti, sizeof(long), 0); //ricevo lunghezza stringa
    if(ret==-1) {
        printf("mexserver errore: errore in ricezione lunghezza dal server1!\n");
        exit(1);
    }
    printf("ricevuto quanti: %ld\n",quanti);
    msg=malloc(quanti);
    ret = recv(sk, (void *)msg, quanti, 0); //ricevo file da cifrare
    if(ret==-1) {
        printf("mexserver errore: errore in ricezione lunghezza dal server2!\n");
        exit(1);
    }
    printf("ricevuto msg\n");
    printf("\n MSG %s\n",msg);
    numblocchi=quanti/16;
    printf("stai elaborando %ld\n",numblocchi);
    printf("blocchi \n");
    //**************************
    exit(1);//****************crush************************
    //****************************
    p=malloc(sizeof(unsigned char*)* numblocchi );
#pragma omp parallel for
    for (int z=1; z<numblocchi; z++) {
        p[z]=malloc(16);
        //l'ultimo carattere mi dice se completato..
    }
    ciphertext=malloc(sizeof(unsigned char*)*numblocchi);
    ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));
    EVP_CIPHER_CTX_init(ctx);
    int outlen=0;
    L=malloc(16);
    /* Context setup for encryption */
    EVP_EncryptInit(ctx, EVP_aes_256_ecb(), key, NULL);
    EVP_CIPHER_CTX_set_padding(ctx, 0);
    EVP_EncryptUpdate(ctx, L, &outlen, (unsigned char*)zero, 16);
    if (!EVP_EncryptFinal(ctx, L+outlen, &outlen)) { // se == 0 -> errore
     	printf("Errore in EVP_EncryptFinal\n");
    	exit(-1);
	}
	EVP_CIPHER_CTX_cleanup(ctx);
	EVP_CIPHER_CTX_free(ctx);
    for (int i=0; i<16; i++)
        printf(" %02X",  (unsigned char)L[i]);
    printf("\n");
    memset(zero, 0, 16);
    zero[15]=1;
    for (int i; i<16; i++)
        L[i]|=zero[i];
    
    //L trovata adessi IL;
    calcolaLI(numblocchi, L, p,index);
    char carry=0;
    char ris;
#pragma omp parallel for private(ctx, outlen)
    for (int i=0;i<numblocchi ; i++) { //fa il cipher
        for(int z=0;z <16;z++){
            // msg[i*16+z]+=p[i][z];{
            ris = msg[i*16+z]&127 || p[i][z]&127;
            msg[i*16+z]+= p[i][z] + carry;
            if (ris==1 && (msg[i*16+z]&127)==0)
                carry=1;
            else
                carry=0;
        }
        ciphertext[i]=malloc(16);
        carry=0;
        ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));
        EVP_CIPHER_CTX_init(ctx);
        outlen = 0;
        EVP_EncryptInit(ctx, EVP_aes_256_ecb(), key, NULL);
        EVP_CIPHER_CTX_set_padding(ctx, 0);
        EVP_EncryptUpdate(ctx, ciphertext[i], &outlen, &msg[i*16], 16);
        if (!EVP_EncryptFinal(ctx, ciphertext[i]+outlen, &outlen)) { // se == 0 -> errore
        	printf("Errore in EVP_EncryptFinal\n");
           	exit(-1);
		}
        EVP_CIPHER_CTX_cleanup(ctx);
		EVP_CIPHER_CTX_free(ctx);
        
    }
    
    
#pragma omp parallel for
    for (int i=0;i<numblocchi ; i++) { //xor tra i cipher calcolati
        for(int z=0;z <16;z++)
            zero[z]^=ciphertext[i][z];
        
    }
    char x='a';
    ret=send(sk,(void*)&x,sizeof(char),0);//mando risultato
    if (ret ==-1)
    {
        printf ("errore nel mandare comando e' il mex d'uscita");
        exit(1);
    }
    printf("zero : \n");
    for (int i=0; i<16; i++)
        printf(" %02X",  (unsigned char)zero[i]);
    printf("\n");
    ret=send(sk,(void*)zero,16,0);//mando risultato
    if (ret ==-1)
    {
        printf ("errore nel mandare comando e' il mex d'uscita");
        exit(1);
    }
    printf("finito un job\n");
}
Ejemplo n.º 29
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);
  }
Ejemplo n.º 30
0
/**
 * @brief Initialise a context for encrypting arbitrary data using the given key.
 * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
 *       *ctx is not NULL, *ctx must point at a previously created structure.
 * @param ctx The block context returned, see note.
 * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
 *           an IV will be created at random, in space allocated from the pool.
 *           If the buffer pointed to is not NULL, the IV in the buffer will be
 *           used.
 * @param key The key structure.
 * @param blockSize The block size of the cipher.
 * @param p The pool to use.
 * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
 *         Returns APR_EINIT if the backend failed to initialise the context. Returns
 *         APR_ENOTIMPL if not implemented.
 */
static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
        const unsigned char **iv, const apr_crypto_key_t *key,
        apr_size_t *blockSize, apr_pool_t *p)
{
    unsigned char *usedIv;
    apr_crypto_config_t *config = key->f->config;
    apr_crypto_block_t *block = *ctx;
    if (!block) {
        *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
    }
    if (!block) {
        return APR_ENOMEM;
    }
    block->f = key->f;
    block->pool = p;
    block->provider = key->provider;

    apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
            apr_pool_cleanup_null);

    /* create a new context for encryption */
    EVP_CIPHER_CTX_init(&block->cipherCtx);
    block->initialised = 1;

    /* generate an IV, if necessary */
    usedIv = NULL;
    if (key->ivSize) {
        if (iv == NULL) {
            return APR_ENOIV;
        }
        if (*iv == NULL) {
            usedIv = apr_pcalloc(p, key->ivSize);
            if (!usedIv) {
                return APR_ENOMEM;
            }
            apr_crypto_clear(p, usedIv, key->ivSize);
            if (!((RAND_status() == 1)
                    && (RAND_bytes(usedIv, key->ivSize) == 1))) {
                return APR_ENOIV;
            }
            *iv = usedIv;
        }
        else {
            usedIv = (unsigned char *) *iv;
        }
    }

    /* set up our encryption context */
#if CRYPTO_OPENSSL_CONST_BUFFERS
    if (!EVP_EncryptInit_ex(&block->cipherCtx, key->cipher, config->engine,
            key->key, usedIv)) {
#else
        if (!EVP_EncryptInit_ex(&block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) usedIv)) {
#endif
        return APR_EINIT;
    }

    /* Clear up any read padding */
    if (!EVP_CIPHER_CTX_set_padding(&block->cipherCtx, key->doPad)) {
        return APR_EPADDING;
    }

    if (blockSize) {
        *blockSize = EVP_CIPHER_block_size(key->cipher);
    }

    return APR_SUCCESS;

}

/**
 * @brief Encrypt data provided by in, write it to out.
 * @note The number of bytes written will be written to outlen. If
 *       out is NULL, outlen will contain the maximum size of the
 *       buffer needed to hold the data, including any data
 *       generated by apr_crypto_block_encrypt_finish below. If *out points
 *       to NULL, a buffer sufficiently large will be created from
 *       the pool provided. If *out points to a not-NULL value, this
 *       value will be used as a buffer instead.
 * @param out Address of a buffer to which data will be written,
 *        see note.
 * @param outlen Length of the output will be written here.
 * @param in Address of the buffer to read.
 * @param inlen Length of the buffer to read.
 * @param ctx The block context to use.
 * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
 *         not implemented.
 */
static apr_status_t crypto_block_encrypt(unsigned char **out,
        apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
        apr_crypto_block_t *ctx)
{
    int outl = *outlen;
    unsigned char *buffer;

    /* are we after the maximum size of the out buffer? */
    if (!out) {
        *outlen = inlen + EVP_MAX_BLOCK_LENGTH;
        return APR_SUCCESS;
    }

    /* must we allocate the output buffer from a pool? */
    if (!*out) {
        buffer = apr_palloc(ctx->pool, inlen + EVP_MAX_BLOCK_LENGTH);
        if (!buffer) {
            return APR_ENOMEM;
        }
        apr_crypto_clear(ctx->pool, buffer, inlen + EVP_MAX_BLOCK_LENGTH);
        *out = buffer;
    }

#if CRYPT_OPENSSL_CONST_BUFFERS
    if (!EVP_EncryptUpdate(&ctx->cipherCtx, (*out), &outl, in, inlen)) {
#else
    if (!EVP_EncryptUpdate(&ctx->cipherCtx, (*out), &outl,
            (unsigned char *) in, inlen)) {
#endif
        return APR_ECRYPT;
    }
    *outlen = outl;

    return APR_SUCCESS;

}

/**
 * @brief Encrypt final data block, write it to out.
 * @note If necessary the final block will be written out after being
 *       padded. Typically the final block will be written to the
 *       same buffer used by apr_crypto_block_encrypt, offset by the
 *       number of bytes returned as actually written by the
 *       apr_crypto_block_encrypt() call. After this call, the context
 *       is cleaned and can be reused by apr_crypto_block_encrypt_init().
 * @param out Address of a buffer to which data will be written. This
 *            buffer must already exist, and is usually the same
 *            buffer used by apr_evp_crypt(). See note.
 * @param outlen Length of the output will be written here.
 * @param ctx The block context to use.
 * @return APR_ECRYPT if an error occurred.
 * @return APR_EPADDING if padding was enabled and the block was incorrectly
 *         formatted.
 * @return APR_ENOTIMPL if not implemented.
 */
static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
        apr_size_t *outlen, apr_crypto_block_t *ctx)
{
    int len = *outlen;

    if (EVP_EncryptFinal_ex(&ctx->cipherCtx, out, &len) == 0) {
        return APR_EPADDING;
    }
    *outlen = len;

    return APR_SUCCESS;

}