Пример #1
0
static int encrypt(void *ctx,char *name,char *file,void *in,int ilen,void *out)
{
	int len;
	int rem;
	int r=NOUSER;
	struct spwd *sp;
#if OPENSSL_VERSION_NUMBER >= 0x1010000fL
	EVP_CIPHER_CTX *etx;
#else
	EVP_CIPHER_CTX etx;
#endif
	unsigned char bfr[512];
	unsigned char key[32];
	unsigned char iv[32];

	if(!(sp=getspnam(name)))goto err1;

	len=sizeof(bfr);
	if((r=sign(ctx,file,sp->sp_pwdp,strlen(sp->sp_pwdp),bfr,&len)))
		goto err2;

	r=CRYPTOFAIL;
#if OPENSSL_VERSION_NUMBER >= 0x1010000fL
	etx=EVP_CIPHER_CTX_new();
	EVP_BytesToKey(EVP_aes_256_cfb(),EVP_sha256(),NULL,bfr,len,1,key,iv);
	EVP_EncryptInit_ex(etx,EVP_aes_256_cfb(),NULL,key,iv);
	len=ilen;
	if(!EVP_EncryptUpdate(etx,out,&len,in,ilen))goto err3;
	rem=ilen-len;
	if(!EVP_EncryptFinal_ex(etx,out+len,&rem))goto err3;
	r=OK;

err3:	EVP_CIPHER_CTX_free(etx);
#else
	EVP_CIPHER_CTX_init(&etx);
	EVP_BytesToKey(EVP_aes_256_cfb(),EVP_sha256(),NULL,bfr,len,1,key,iv);
	EVP_EncryptInit_ex(&etx,EVP_aes_256_cfb(),NULL,key,iv);
	len=ilen;
	if(!EVP_EncryptUpdate(&etx,out,&len,in,ilen))goto err3;
	rem=ilen-len;
	if(!EVP_EncryptFinal_ex(&etx,out+len,&rem))goto err3;
	r=OK;

err3:	EVP_CIPHER_CTX_cleanup(&etx);
#endif
	memclear(key,0,sizeof(key));
	memclear(iv,0,sizeof(iv));
err2:	memclear(bfr,0,sizeof(bfr));
	memclear(sp->sp_pwdp,0,strlen(sp->sp_pwdp));
err1:	return r;
}
Пример #2
0
rstatus_t dyn_aes_encrypt(const unsigned char *msg, size_t msg_len, struct mbuf *mbuf, unsigned char *aes_key) {
	if (ENCRYPTION) {
		size_t block_len  = 0;
		size_t enc_msg_len = 0;

		ASSERT(mbuf != NULL && mbuf->last == mbuf->pos);

		//if(!EVP_EncryptInit_ex(aes_encrypt_ctx, aes_cipher, NULL, aes_key, aes_iv)) {
		if(!EVP_EncryptInit_ex(aes_encrypt_ctx, aes_cipher, NULL, aes_key, aes_key)) {
			return DN_ERROR;
		}

		if(!EVP_EncryptUpdate(aes_encrypt_ctx, mbuf->start, (int*)&block_len, (unsigned char*) msg, msg_len)) {
			return DN_ERROR;
		}
		enc_msg_len += block_len;

		if(!EVP_EncryptFinal_ex(aes_encrypt_ctx, mbuf->start + enc_msg_len, (int*) &block_len)) {
			return DN_ERROR;
		}

		EVP_CIPHER_CTX_cleanup(aes_encrypt_ctx);
		mbuf->last = mbuf->pos + enc_msg_len + block_len;

		return enc_msg_len + block_len;
	} else {
		mbuf_copy(mbuf, msg, msg_len);
		return (int) msg_len;
	}
}
Пример #3
0
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;

	// init context
	if(!(ctx = EVP_CIPHER_CTX_new())){
       		 handle_errors();
	}
	// init encryption operation
	if(1 != EVP_EncryptInit_ex(ctx, EVP_des_ede3_cbc(), NULL, key, iv)){
		handle_errors();
	}
	// obtain encrypted output
	if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)){
		handle_errors();
		ciphertext_len = len; 
	}
	ciphertext_len=len;
	// finalize 
	if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)){
		handle_errors();
		ciphertext_len += len;
	}
	ciphertext_len += len;
	EVP_CIPHER_CTX_free(ctx);
	return ciphertext_len;

}
Пример #4
0
    r_int32 AESCipher::encrypt(const unsigned char* raw, const size_t& rawLen, unsigned char* dest, size_t* destLen) 
    {

        /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
        int c_len = rawLen % AES_BLOCK_SIZE == 0 ? rawLen : (rawLen / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE; ;
        if (*destLen < (size_t)c_len)
        {
            return CIPHER_STATUS_BUFFER_ERROR;
        }
        
        int f_len = 0;
        if (!EVP_EncryptInit_ex(&m_ectx, NULL, NULL, NULL, NULL))
        {
            return CIPHER_STATUS_UNKNOWN_ERROR;
        }
        

        if (!EVP_EncryptUpdate(&m_ectx, dest, &c_len, raw, rawLen))
        {
            return CIPHER_STATUS_UNKNOWN_ERROR;
        }

        if (!EVP_EncryptFinal_ex(&m_ectx, dest+c_len, &f_len))
        {
            return CIPHER_STATUS_UNKNOWN_ERROR;
        }

        *destLen = c_len + f_len;
        return CIPHER_STATUS_OK;
    }
Пример #5
0
wi_boolean_t wi_cipher_encrypt_bytes(wi_cipher_t *cipher, const void *decrypted_buffer, wi_uinteger_t decrypted_length, void **out_buffer, wi_uinteger_t *out_length) {
	void		*encrypted_buffer;
	int			encrypted_length, padded_length;
	
	encrypted_buffer = wi_malloc(decrypted_length + EVP_CIPHER_block_size(cipher->cipher));

	if(EVP_EncryptUpdate(&cipher->encrypt_ctx, encrypted_buffer, &encrypted_length, decrypted_buffer, decrypted_length) != 1) {
		wi_error_set_openssl_error();
		
		wi_free(encrypted_buffer);
		
		return false;
	}
	
	if(EVP_EncryptFinal_ex(&cipher->encrypt_ctx, encrypted_buffer + encrypted_length, &padded_length) != 1) {
		wi_error_set_openssl_error();
		
		wi_free(encrypted_buffer);
		
		return false;
	}

	if(EVP_EncryptInit_ex(&cipher->encrypt_ctx, NULL, NULL, NULL, NULL) != 1) {
		wi_error_set_openssl_error();
		
		wi_free(encrypted_buffer);
		
		return false;
	}

	*out_buffer = encrypted_buffer;
	*out_length = encrypted_length + padded_length;
	
	return true;
}
Пример #6
0
// Encrypts whatever is being sent over the wire. msg is the original plaintext, msgLen
// is the length of it, encMsg is where the output will be stored, aesKey and aesIV are what
// are used at the key and IV to encrypt.
int Encryption::EncryptAes(const unsigned char *msg, size_t msgLen, unsigned char **encMsg, unsigned char *aesKey, unsigned char *aesIV) {
	size_t blockLen = 0;
	size_t encMsgLen = 0;
	
	*encMsg = (unsigned char*) malloc(msgLen + AES_BLOCK_SIZE);
	if (encMsg == NULL) {
		return -1;
	}
	
	// setting up cipher context for AES CBC encryption
	if (!EVP_EncryptInit_ex(EncryptAesCtx, EVP_aes_256_cbc(), NULL, aesKey, aesIV)) {
		return -1;
	}
	
	// encrypts a message of msgLen from msg to encMsg. Number of bytes written in blockLen
	if (!EVP_EncryptUpdate(EncryptAesCtx, *encMsg, (int*)&blockLen, (unsigned char*)msg, msgLen)) {
		return -1;
	}
	encMsgLen += blockLen;
	
	// uses padding to finish off the remaining message to be encrypted
	if (!EVP_EncryptFinal_ex(EncryptAesCtx, *encMsg + encMsgLen, (int*)&blockLen)) {
		return -1;
	}
	
	EVP_CIPHER_CTX_cleanup(EncryptAesCtx);
	
	return encMsgLen + blockLen;
}
CK_RV PKCS11_Encryption_OpenSSL::EncryptFinal(Cryptoki_Session_Context* pSessionCtx, CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen)
{
    OPENSSL_HEADER();
    OpenSSLEncryptData *pEnc;
    
    if(pSessionCtx == NULL || pSessionCtx->EncryptionCtx == NULL) return CKR_SESSION_CLOSED;

    pEnc = (OpenSSLEncryptData*)pSessionCtx->EncryptionCtx;
    
    if(pEnc->IsSymmetric)
    {
        int outLen = *pulLastEncryptedPartLen;
        
        OPENSSL_CHECKRESULT(EVP_EncryptFinal_ex((EVP_CIPHER_CTX*)pEnc->Key->ctx, pLastEncryptedPart, &outLen));
        
        *pulLastEncryptedPartLen = outLen;

        OPENSSL_CHECKRESULT(EVP_CIPHER_CTX_cleanup((EVP_CIPHER_CTX*)pEnc->Key->ctx));
    }
    else
    {
        EVP_PKEY_CTX_free((EVP_PKEY_CTX*)pEnc->Key->ctx);
        
        *pulLastEncryptedPartLen = 0;
    }

    OPENSSL_CLEANUP();

    TINYCLR_SSL_FREE(pEnc);
    pSessionCtx->EncryptionCtx = NULL;

    OPENSSL_RETURN();
}    
Пример #8
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)){
        free(ciphertext);
        return QString();
    }

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

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

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

    free(ciphertext);

    return QString::fromLatin1(cipheredData.toBase64());
}
Пример #9
0
static inline int aes_128_encrypt_block(EVP_CIPHER_CTX *evp_ctx,
					uint8_t const key[16], uint8_t const in[16], uint8_t out[16])
{
	size_t len;

	if (unlikely(EVP_EncryptInit_ex(evp_ctx, EVP_aes_128_ecb(), NULL, key, NULL) != 1)) {
		tls_strerror_printf("Failed initialising AES-128-ECB context");
		return -1;
	}

	/*
	 *	By default OpenSSL will try and pad out a 16 byte
	 *	plaintext to 32 bytes so that it's detectable that
	 *	there was padding.
	 *
	 *	In this case we know the length of the plaintext
	 *	we're trying to recover, so we explicitly tell
	 *	OpenSSL not to pad here, and not to expected padding
	 *	when decrypting.
	 */
	EVP_CIPHER_CTX_set_padding(evp_ctx, 0);
	if (unlikely(EVP_EncryptUpdate(evp_ctx, out, (int *)&len, in, 16) != 1) ||
	    unlikely(EVP_EncryptFinal_ex(evp_ctx, out + len, (int *)&len) != 1)) {
		tls_strerror_printf("Failed encrypting data");
		return -1;
	}

	return 0;
}
Пример #10
0
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;
}
Пример #11
0
sgx_status_t sgx_aes_gcm128_enc_get_mac(uint8_t *mac, sgx_aes_state_handle_t aes_gcm_state)
{
    if ((mac == NULL) || (aes_gcm_state == NULL))
    {
        return SGX_ERROR_INVALID_PARAMETER;
    }
    sgx_status_t ret = SGX_ERROR_UNEXPECTED;
    int tmp = 0;
    EVP_CIPHER_CTX *pState = (EVP_CIPHER_CTX*)aes_gcm_state;
    do {
        // Finalise the encryption
        //
        if (1 != EVP_EncryptFinal_ex(pState, NULL, &tmp)) {
            break;
        }

        // Get tag (MAC)
        //
        if (!EVP_CIPHER_CTX_ctrl(pState, EVP_CTRL_AEAD_GET_TAG, SGX_AESGCM_MAC_SIZE, mac)) {
            break;
        }

        ret = SGX_SUCCESS;
    } while (1);
    
    //In case of error, clear output MAC buffer.
    //
    if (ret != SGX_SUCCESS) {
	    memset_s(mac, SGX_AESGCM_MAC_SIZE, 0, SGX_AESGCM_MAC_SIZE);
    }

    return ret;
}
Пример #12
0
/**
* @brief Encrypt *len bytes of data
*
* All data going in & out is considered binary (unsigned char[])
*
* Code adapted from: http://saju.net.in/code/misc/openssl_aes.c.txt
*
* @param e
* @param plaintext
* @param plaintext_len
* @param ciphertext_buf
* @param ciphertext_buf_len
*
* @return Size of ciphertext on success, -1 on failure
*/
int aes_encrypt(EVP_CIPHER_CTX *e, 
				unsigned char *plaintext, int plaintext_len,
				unsigned char *ciphertext_buf, int ciphertext_buf_len) {
	/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
	int c_len = plaintext_len + AES_BLOCK_SIZE, f_len = 0;
	if (ciphertext_buf_len < c_len) {
		ERROR("Ciphertext buffer too small");
		return -1;
	}
	
	/* allows reusing of 'e' for multiple encryption cycles */
	if (EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL) != 1) {
		ERROR("ERROR initializing encryption");
		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, ciphertext_buf, &c_len, plaintext, plaintext_len) != 1) {
		ERROR("ERROR encrypting");
		return -1;
	}
	
	/* update ciphertext with the final remaining bytes */
	if (EVP_EncryptFinal_ex(e, ciphertext_buf+c_len, &f_len) != 1) {
		ERROR("ERROR encrypting");
		return -1;
	}
	
	return c_len + f_len;
}
Пример #13
0
size_t AES::CbcEncrypt256(const char *pIn, int iInLen, char *pOut, char *pKey, char *pIv)
{
    EVP_CIPHER_CTX *ctx;

    if(!(ctx = EVP_CIPHER_CTX_new())) 
    {
        //Error for create
        return 0;
    }

    //Init Encrypt
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, pKey, pIv))
    {
        //Error
        return 0;
    }
    int iLen, iCipherLen;
    if(1 != EVP_EncryptUpdate(ctx, pOut, &iLen, pIn, iInLen))
    {
        return 0;
    }
    iCipherLen = iLen;
    if(1 != EVP_EncryptFinal_ex(ctx, pOut + iCipherLen, &iLen))
    {
        return 0;
    }

    iCipherLen += iLen;

    EVP_CIPHER_CTX_free(ctx);

    return iCipherLen;
}
Пример #14
0
static int aesEncrypt(char* input, int inlen, char* output, int* outlen) {
    int c_len; //length of ciphertext
    int f_len; //rest length of padded ciphertext
    EVP_CIPHER_CTX ctx;

    if (input == NULL || inlen <= 0 || output == NULL || *outlen <= 0) {
        return -1;
    }

    EVP_CIPHER_CTX_init(&ctx);

    if (EVP_EncryptInit_ex(&ctx, EVP_aes_128_ecb(), NULL, key, NULL) != 1) {
        return -2;
    }

    if (EVP_EncryptUpdate(&ctx, (unsigned char*)output, &c_len, (const unsigned char*)input,
                          inlen) != 1) {
        return -3;
    }

    if (EVP_EncryptFinal_ex(&ctx, (unsigned char*)(output + c_len), &f_len) != 1) {
        return -4;
    }

    EVP_CIPHER_CTX_cleanup(&ctx);

    *outlen = c_len + f_len;
    return 0;
}
Пример #15
0
uint32_t encrypt(const BYTE *password, const BYTE* data, uint32_t len, BYTE* ans, encrypt_function function) {
	EVP_CIPHER_CTX ctx;
	uint32_t keyl = 0, ivl = 0;
	uint32_t outl = 0, templ = 0;
	char *out = calloc(len + EVP_MAX_BLOCK_LENGTH - 1, sizeof(char));
	keyl = EVP_CIPHER_key_length(function());
	ivl = EVP_CIPHER_iv_length(function());
	BYTE key[keyl];
	BYTE iv[ivl];
	
	/* Getting keys and iv */ 
	// Salt is setting in NULL
	EVP_BytesToKey(function(), EVP_md5(), NULL, password, strlen(password),1, key, iv);

    /* Initialize context */
    EVP_CIPHER_CTX_init(&ctx);
	EVP_EncryptInit_ex(&ctx, function(), NULL, key, iv); 
	EVP_EncryptUpdate(&ctx, out, &outl, data, len); 
	EVP_EncryptFinal_ex(&ctx, out + outl, &templ);
	outl +=templ;
	memcpy(ans, out, outl);
	
	/* Clean context struct */ 
	EVP_CIPHER_CTX_cleanup(&ctx);
	free(out);
	return outl;
}
Пример #16
0
// 입력 파라미터: 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;
}
Пример #17
0
int EncryptString(char type, char *in, char *out, unsigned char *key, int plainlen)
{
    int cipherlen = 0, tmplen;
    unsigned char iv[32] =
        { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 };
    EVP_CIPHER_CTX ctx;

    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx, CfengineCipher(type), NULL, key, iv);

    if (!EVP_EncryptUpdate(&ctx, out, &cipherlen, in, plainlen))
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return -1;
    }

    if (!EVP_EncryptFinal_ex(&ctx, out + cipherlen, &tmplen))
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return -1;
    }

    cipherlen += tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx);
    return cipherlen;
}
Пример #18
0
/**
 * Takes a block of data and encrypts it with a symmetric cypher.
 * The output buffer must be at least the size of source data + block size.
 */
int encrypt_block(int keytype, const unsigned char *IV,
                  const unsigned char *key,
                  const unsigned char *src, unsigned int srclen,
                  unsigned char *dest, unsigned int *destlen)
{
    EVP_CIPHER_CTX ctx;
    const EVP_CIPHER *cipher = get_cipher(keytype);
    int len;

    EVP_CIPHER_CTX_init(&ctx);
    if (!EVP_EncryptInit_ex(&ctx, cipher, NULL, key, IV)) {
        log_ssl_err("EncryptInit failed");
        return 0;
    }
    if (!EVP_EncryptUpdate(&ctx, dest, &len, src, srclen)) {
        log_ssl_err("EncryptUpdate failed");
        return 0;
    }
    *destlen = len;
    if (!EVP_EncryptFinal_ex(&ctx, dest + *destlen, &len)) {
        log_ssl_err("EncryptFinal failed");
        return 0;
    }
    *destlen += len;
    EVP_CIPHER_CTX_cleanup(&ctx);

    return 1;
}
/**
  *  @brief
  *
  *  @param
  *  @return
  */
void ipmi20_encrypt_aes_cbc_128(unsigned char *init_vec,
								unsigned char *key,
								unsigned char *data,
								int data_len,
								unsigned char *out,
								int *out_len)
{
	EVP_CIPHER_CTX ctx;

	EVP_CIPHER_CTX_init(&ctx);
	EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, init_vec);
	EVP_CIPHER_CTX_set_padding(&ctx, 0);

	if (!EVP_EncryptUpdate(&ctx, out, out_len, data, data_len)) {
		*out_len = 0;

		return;
	} else {
		int len_tmp = 0;

		if (!EVP_EncryptFinal_ex(&ctx, out + *out_len, &len_tmp)) {
			*out_len = 0;

			return;
		} else {
			*out_len += len_tmp;
			EVP_CIPHER_CTX_cleanup(&ctx);
		}
	}
}
Пример #20
0
JNIEXPORT int JNICALL Java_com_facebook_crypto_cipher_NativeGCMCipher_nativeEncryptFinal(
  JNIEnv* env,
  jobject obj,
  jbyteArray macTag,
  jint tagLen) {

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

  jbyte* tagBytes = (*env)->GetByteArrayElements(env, macTag, NULL);
  if (!tagBytes) {
    return CRYPTO_FAILURE;
  }

  int retCode = CRYPTO_SUCCESS;
  if (!retCode || !EVP_EncryptFinal_ex(ctx, tagBytes, &bytesWritten)) {
    retCode = CRYPTO_FAILURE;
  }

  if (!retCode || !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, tagLen, tagBytes)) {
    retCode = CRYPTO_FAILURE;
  }

  (*env)->ReleaseByteArrayElements(env, macTag, tagBytes, 0);
  return retCode;
}
Пример #21
0
void aes_gcm_encrypt(void)
{
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen;
    unsigned char outbuf[1024];
    printf("AES GCM Encrypt:\n");
    printf("Plaintext:\n");
    BIO_dump_fp(stdout, gcm_pt, sizeof(gcm_pt));
    ctx = EVP_CIPHER_CTX_new();
    /* Set cipher type and mode */
    EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
    /* Set IV length if default 96 bits is not appropriate */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, sizeof(gcm_iv), NULL);
    /* Initialise key and IV */
    EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
    /* Zero or more calls to specify any AAD */
    EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad));
    /* Encrypt plaintext */
    EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt));
    /* Output encrypted block */
    printf("Ciphertext:\n");
    BIO_dump_fp(stdout, outbuf, outlen);
    /* Finalise: note get no output for GCM */
    EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
    /* Get tag */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, outbuf);
    /* Output tag */
    printf("Tag:\n");
    BIO_dump_fp(stdout, outbuf, 16);
    EVP_CIPHER_CTX_free(ctx);
}
Пример #22
0
/*
 * Encrypt the plaintext input using AES-128 in CTR mode.
 */
int
secretbox_encrypt(unsigned char *key, unsigned char *in, unsigned char *out,
                  int data_len)
{
        EVP_CIPHER_CTX   crypt;
        unsigned char    nonce[SECRETBOX_IV_SIZE];
        unsigned char    cryptkey[SECRETBOX_CRYPT_SIZE];
        int              ctlen = 0;
	int		 finale = 0;
        int              res = 0;

        if (!secretbox_generate_nonce(nonce)) {
                return -1;
        }
	memcpy(out, nonce, SECRETBOX_IV_SIZE);
        memcpy(cryptkey, key, SECRETBOX_CRYPT_SIZE);

        EVP_CIPHER_CTX_init(&crypt);
        if (EVP_EncryptInit_ex(&crypt, EVP_aes_128_ctr(), NULL, cryptkey, nonce))
        if (EVP_EncryptUpdate(&crypt, out+SECRETBOX_IV_SIZE, &ctlen, in, data_len))
        if (EVP_EncryptFinal_ex(&crypt, out+SECRETBOX_IV_SIZE+ctlen, &finale))
        if (ctlen+finale == data_len)
                res = 1;
        EVP_CIPHER_CTX_cleanup(&crypt);
        memset(cryptkey, 0x0, SECRETBOX_CRYPT_SIZE);
        return res;
}
Пример #23
0
int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
	{
	int i;
	i = EVP_EncryptFinal_ex(ctx,out,outl);
	EVP_EncryptInit_ex(ctx,NULL,NULL,NULL,NULL);
	return i;
	}
Пример #24
0
static LUA_FUNCTION(openssl_evp_cipher_final)
{
  EVP_CIPHER_CTX* c = CHECK_OBJECT(1, EVP_CIPHER_CTX, "openssl.evp_cipher_ctx");
  char out[EVP_MAX_BLOCK_LENGTH];
  int outl = sizeof(out);
  CIPHER_MODE mode;
  int ret = 0;

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

  if (mode == DO_CIPHER)
    ret = EVP_CipherFinal_ex(c, (byte*)out, &outl);
  else if (mode == DO_ENCRYPT)
    ret = EVP_EncryptFinal_ex(c, (byte*)out, &outl);
  else if (mode == DO_DECRYPT)
    ret = EVP_DecryptFinal_ex(c, (byte*)out, &outl);
  else
    luaL_error(L, "never go here");
  lua_pop(L, 1);

  if (ret == 1)
  {
    lua_pushlstring(L, out, outl);
    return 1;
  }
  return openssl_pushresult(L, ret);
}
Пример #25
0
bool AesPasswordCipher::encrypt(const uint8_t* input, size_t input_size, std::vector<uint8_t>& output) {
	if(!evpCipher)
		evpCipher.reset(EVP_CIPHER_CTX_new());

	if(EVP_EncryptInit_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_EncryptUpdate(evpCipher.get(), &output[0], &bytesWritten, input, input_size) <= 0)
		return false;

	totalLength += bytesWritten;

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

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

	return true;
}
Пример #26
0
// General secure AES 256 CBC encryption routine
bool EncryptAES256(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;

    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);

    if (!fOk) return false;

    sCiphertext.resize(nCLen + nFLen);
    return true;
}
Пример #27
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;

    bool fOk = true;

    EVP_CIPHER_CTX_init(&ctx);
    if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
    if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
    if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
    EVP_CIPHER_CTX_cleanup(&ctx);

    if (!fOk) return false;

    vchCiphertext.resize(nCLen + nFLen);
    return true;
}
Пример #28
0
QByteArray UBAbstractPublisher::encrypt(const QString& clear)
{
    static const char *key = "9ecHaspud9uD9ste5erAchehefrup3ec";

    EVP_CIPHER_CTX aesEncryptContext;

    EVP_CIPHER_CTX_init(&aesEncryptContext);

    EVP_EncryptInit_ex(&aesEncryptContext, EVP_aes_256_ecb(), NULL, (const unsigned char*)key, NULL);

    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(&aesEncryptContext, NULL, NULL, NULL, NULL))
        return QByteArray();

    if(!EVP_EncryptUpdate(&aesEncryptContext, cipherText, &cipheredLength, (unsigned char *)clearData.data(), clearData.length()))
        return QByteArray();

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

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

    free(cipherText);
    EVP_CIPHER_CTX_cleanup(&aesEncryptContext);

    return cipheredData;

}
Пример #29
0
bool OldEncrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext, const unsigned char chKey[32], const unsigned char chIV[16])
{
    // 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_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, chKey, chIV) != 0;
    if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
    if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
    EVP_CIPHER_CTX_cleanup(ctx);

    EVP_CIPHER_CTX_free(ctx);

    if (!fOk) return false;

    vchCiphertext.resize(nCLen + nFLen);
    return true;
}
Пример #30
0
rstatus_t
aes_encrypt(const unsigned char *msg, size_t msg_len, unsigned char **enc_msg, unsigned char *aes_key) {
	size_t block_len  = 0;
	size_t enc_msg_len = 0;

	*enc_msg = (unsigned char*)malloc(msg_len + AES_BLOCK_SIZE);
	if(enc_msg == NULL)
		return DN_ERROR;

	//if(!EVP_EncryptInit_ex(aes_encrypt_ctx, aes_cipher, NULL, aes_key, aes_iv)) {
	if(!EVP_EncryptInit_ex(aes_encrypt_ctx, aes_cipher, NULL, aes_key, aes_key)) {
		return DN_ERROR;
	}

	if(!EVP_EncryptUpdate(aes_encrypt_ctx, *enc_msg, (int*)&block_len, (unsigned char*)msg, msg_len)) {
		return DN_ERROR;
	}
	enc_msg_len += block_len;

	if(!EVP_EncryptFinal_ex(aes_encrypt_ctx, *enc_msg + enc_msg_len, (int*) &block_len)) {
		return DN_ERROR;
	}

	//EVP_CIPHER_CTX_cleanup(aesEncryptCtx);

	return enc_msg_len + block_len;
}