int crypt_ec_helper::encrypt(unsigned char* cipherText, unsigned char *message, int messageLength, unsigned char *secret, int secretLength)
	{
		EVP_CIPHER_CTX *ctx;
		int len, ciphertext_len;
		unsigned char* key = new unsigned char[32];
		unsigned char* iv = new unsigned char[16];

		int keyLen = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(),
			NULL,
			secret, secretLength, 150000,
			key, iv);

		/* Create and initialise the context */
		if (!(ctx = EVP_CIPHER_CTX_new()))
			throw std::runtime_error("Encrypt: Failed to create cipher context.\n");

		/* 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))
			throw std::runtime_error("Encrypt: Failed to initialize cipher.\n");

		/* 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, message, messageLength))
			throw std::runtime_error("Encrypt: Failed to encrypt message.\n");

		ciphertext_len = len;

		/* Finalise the encryption. Further ciphertext bytes may be written at
		* this stage.
		*/
		if (1 != EVP_EncryptFinal_ex(ctx, cipherText + len, &len))
			throw std::runtime_error("Encrypt: Failed to finalize message encryption.\n");

		ciphertext_len += len;

		free(key);
		free(iv);
		EVP_CIPHER_CTX_free(ctx);

		return ciphertext_len;
	}
Beispiel #2
0
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
    if (!fKeySet)
        return false;

    // plaintext will always be equal to or lesser than length of ciphertext
    int nLen = vchCiphertext.size();
    int nPLen = nLen, nFLen = 0;

    vchPlaintext = CKeyingMaterial(nPLen);

    EVP_CIPHER_CTX ctx;

    bool fOk = true;

    EVP_CIPHER_CTX_init(&ctx);
    if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
    if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
    if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
    EVP_CIPHER_CTX_cleanup(&ctx);

    if (!fOk) return false;

    vchPlaintext.resize(nPLen + nFLen);
    return true;
}
/*
 * This function encrypts a string before calling send_msg.
 * It also append the given IV for the ecnryption mode.
 * It returns the length of the cipher text (iv is not considered), -1 on error.
 * Errno is set appropriately
 */
int encrypt_msg(int sk, char format, unsigned char* plain, unsigned int plain_len, unsigned char* shared_secret)
{
	EVP_CIPHER_CTX* ctx;
	unsigned char* iv;
	unsigned int iv_len = EVP_MAX_IV_LENGTH;
	unsigned char* outbuf = NULL;
	int outlen, outtot = 0;
	ctx = (EVP_CIPHER_CTX*)calloc(1, sizeof(EVP_CIPHER_CTX));
	EVP_CIPHER_CTX_init(ctx);
	
	iv = (unsigned char*)calloc(1, iv_len);
	RAND_bytes(iv, iv_len);
	if (EVP_EncryptInit(ctx, EVP_aes_256_cbc(), shared_secret, iv) == 0) {
		goto fail;
	}
	outbuf = (unsigned char*)calloc(1, plain_len + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + iv_len);
	if (EVP_EncryptUpdate(ctx, outbuf + iv_len, &outlen, plain, plain_len) == 0) {
		goto fail;
	}
	outtot += outlen;
	if (EVP_EncryptFinal(ctx, outbuf + iv_len + outtot, &outlen) == 0) {
		goto fail;
	}
	outtot += outlen;
	
	//We concatenate iv and cipher text together
	memcpy(outbuf, iv, iv_len);
	if (send_msg(sk, outbuf, outtot + iv_len, format) < outtot + iv_len) {
		goto fail;
	}
	
	EVP_CIPHER_CTX_cleanup(ctx);
	free(ctx);
	free(iv);
	free(outbuf);
	return outtot;
	
	
fail:	EVP_CIPHER_CTX_cleanup(ctx);
	free(ctx);
	free(iv);
	if (outbuf != NULL) {
		free(outbuf);
	}
	return -1;
	
}
Beispiel #4
0
bool AES_CBC_MAC_Create(COSE_MacMessage * pcose, int TSize, const byte * pbKey, size_t cbKey, const byte * pbAuthData, size_t cbAuthData, cose_errback * perr)
{
	const EVP_CIPHER * pcipher = NULL;
	EVP_CIPHER_CTX ctx;
	int cbOut;
	byte rgbIV[16] = { 0 };
	byte * rgbOut = NULL;
	bool f = false;
	unsigned int i;
	cn_cbor * cn = NULL;
#ifdef USE_CBOR_CONTEXT
	cn_cbor_context * context = &pcose->m_message.m_allocContext;
#endif

	rgbOut = COSE_CALLOC(16, 1, context);
	CHECK_CONDITION(rgbOut != NULL, COSE_ERR_OUT_OF_MEMORY);

	switch (cbKey*8) {
	case 128:
		pcipher = EVP_aes_128_cbc();
		break;

	case 256:
		pcipher = EVP_aes_256_cbc();
		break;

	default:
		FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER);
	}

	//  Setup and run the OpenSSL code

	EVP_CIPHER_CTX_init(&ctx);
	CHECK_CONDITION(EVP_EncryptInit_ex(&ctx, pcipher, NULL, pbKey, rgbIV), COSE_ERR_CRYPTO_FAIL);

	for (i = 0; i < (unsigned int)cbAuthData / 16; i++) {
		CHECK_CONDITION(EVP_EncryptUpdate(&ctx, rgbOut, &cbOut, pbAuthData + (i * 16), 16), COSE_ERR_CRYPTO_FAIL);
	}
	if (cbAuthData % 16 != 0) {
		CHECK_CONDITION(EVP_EncryptUpdate(&ctx, rgbOut, &cbOut, pbAuthData + (i * 16), cbAuthData % 16), COSE_ERR_CRYPTO_FAIL);
		CHECK_CONDITION(EVP_EncryptUpdate(&ctx, rgbOut, &cbOut, rgbIV, 16 - (cbAuthData % 16)), COSE_ERR_CRYPTO_FAIL);
	}

	cn = cn_cbor_data_create(rgbOut, TSize / 8, CBOR_CONTEXT_PARAM_COMMA NULL);
	CHECK_CONDITION(cn != NULL, COSE_ERR_OUT_OF_MEMORY);
	rgbOut = NULL;

	CHECK_CONDITION(_COSE_array_replace(&pcose->m_message, cn, INDEX_MAC_TAG, CBOR_CONTEXT_PARAM_COMMA NULL), COSE_ERR_CBOR);
	cn = NULL;

	EVP_CIPHER_CTX_cleanup(&ctx);
	return !f;

errorReturn:
	if (rgbOut != NULL) COSE_FREE(rgbOut, context);
	if (cn != NULL) CN_CBOR_FREE(cn, context);
	EVP_CIPHER_CTX_cleanup(&ctx);
	return false;
}
Beispiel #5
0
// Initializes the keys that are going to be used
int Encryption::init() {
	// initialize
	EncryptAesCtx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));

	DecryptAesCtx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));

	// malloc check
	if (EncryptAesCtx == NULL || DecryptAesCtx == NULL) {
		return -1;
	}

    	EVP_CIPHER_CTX_init(EncryptAesCtx);
 
    	EVP_CIPHER_CTX_init(DecryptAesCtx);

	// init AES
	aesKey = (unsigned char*)malloc(AES_KEYLEN/8);
	aesIV = (unsigned char*)malloc(AES_KEYLEN/8);

	unsigned char *aesPass = (unsigned char*)malloc(AES_KEYLEN / 8);
	unsigned char *aesSalt = (unsigned char*)malloc(8);
	
	if(aesKey == NULL || aesIV == NULL || aesPass == NULL || aesSalt == NULL) {
		return -1;
	}

	// Can use password based key derivation for AES, or random data, this uses
	// random data here, can be changed later to fit to project

	#ifdef USE_PBKDF
	
	// Get some random data to use as the AES pass and salt
        if(RAND_bytes(aesPass, AES_KEYLEN/8) == 0) { 
            return -1;
        }

        if(RAND_bytes(aesSalt, 8) == 0) {
            return -1;
        }
     
	// generate 256 bit key
        if(EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), aesSalt, aesPass, AES_KEYLEN/8, AES_ROUNDS, aesKey, aesIV) == 0) {
            return -1;
        }
    #else
        if(RAND_bytes(aesKey, AES_KEYLEN/8) == 0) {
            return -1;
        }

        if(RAND_bytes(aesIV, AES_KEYLEN/8) == 0) {
            return -1;
        }
    #endif

   	free(aesPass);
    	free(aesSalt);
 
    	return 0;
}
Beispiel #6
0
/**
 * @brief AES256 Create Key function
 * @see el_aes256_encrypt_data()
 * @see el_aes256_decrypt_data()
 * @param key_data The data that will be used to create the key (eg. user+pass)
 * @param key The key generated, based on key_data value
 * @return 0 on success, -1 on error.
 */
int el_aes256_create_key(const unsigned char *key_data, unsigned char *key) {
	int ret, nrounds = 5;
	unsigned char iv[32];

	ret = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), NULL, key_data, strlen((char *) key_data), nrounds, key, iv);

	return -(ret != 32);
}
Beispiel #7
0
void EncryptWrapper::cryptInit(QString pwd){
	QByteArray key(EVP_MAX_KEY_LENGTH,0);
	QByteArray iv(EVP_MAX_IV_LENGTH,0);

//	convert QString to unsigned char
	unsigned char *password = (unsigned char *)malloc(sizeof(unsigned char));
	memcpy(password, pwd.toStdString().c_str(),pwd.size());

	if(!EVP_BytesToKey(EVP_aes_256_cbc(),EVP_sha1(), NULL,
					   (unsigned char *) password,
					   strlen((const char *)password), 1, (unsigned char *)key.data(), (unsigned char *)iv.data())){
		emit errors("EVP_BytesToKey failed: Password "+pwd+" doesn't create.");
		return;
	}
	EVP_CIPHER_CTX_init(&encrypt);
	EVP_EncryptInit(&encrypt, EVP_aes_256_cbc(), (const unsigned char*)key.constData(), (const unsigned char*)iv.constData());
}
Beispiel #8
0
/** 
 * @brief Performs basic Encrypt-then-MAC style Authenticated Encryption.
 *
 * @param[in] ekey            a buffer holding the ENC key
 * @param[in] ekey_len        len of ekey buffer
 * @param[in] mkey            a buffer holding the MAC key
 * @param[in] mkey_len        len of mkey buffer
 * @param[in] ctxt            a buffer holding the ciphertext
 * @param[in] ctxt_len        length of ciphertext
 * @param[in] mac             a buffer holding the MAC
 * @param[in] mac_len         length of MAC
 * @param[in] iv              an iv (optional)
 * @param[in] iv_len          length of iv (optional)
 * @param[out] output         an allocated buffer, will hold the plaintext
 * @param[in,out] output_len  length of buffer, will hold length of plaintext
 * @return 0 on success, non-zero on error
 **/
int verify_then_decrypt(const unsigned char *ekey, size_t ekey_len, 
                        const unsigned char *mkey, size_t mkey_len,
                        const unsigned char *ctxt, size_t ctxt_len,
                        const unsigned char *mac, size_t mac_len,
                        const unsigned char *iv, size_t iv_len,
                        unsigned char *output, size_t *output_len)
{
    EVP_CIPHER_CTX *ctx;
    ctx = EVP_CIPHER_CTX_new();
    EVP_CIPHER *cipher = NULL;
    unsigned char auth[EVP_MAX_MD_SIZE];
    size_t auth_len = EVP_MAX_MD_SIZE;
    int len;
    
    if (!ekey || !ekey_len || !mkey || !mkey_len || 
        !ctxt || !ctxt_len || !mac || !mac_len || !output || !output_len)
        return -1;
    
    OpenSSL_add_all_algorithms();
    memset(auth, 0, auth_len);

    // Verify the HMAC-SHA1
    if (!HMAC(EVP_sha1(), mkey, mkey_len, ctxt, ctxt_len, 
              auth, (unsigned int *) &auth_len))
        goto cleanup;
    if (auth_len != mac_len) goto cleanup;
    if (memcmp(mac, auth, mac_len) != 0) goto cleanup;

    EVP_CIPHER_CTX_init(ctx);
    switch(ekey_len){
        case 16:
            cipher = (EVP_CIPHER *)EVP_aes_128_cbc();
            break;
        case 24:
            cipher = (EVP_CIPHER *)EVP_aes_192_cbc();
            break;
        case 32:
            cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
            break;
        default:
            return -1;
    }
    if (*output_len < ctxt_len) goto cleanup;
    *output_len = 0;

    if (!EVP_DecryptInit(ctx, cipher, ekey, iv)) goto cleanup;
    if (!EVP_DecryptUpdate(ctx, output, (int *) output_len, 
                           ctxt, ctxt_len)) goto cleanup;
    EVP_DecryptFinal(ctx, output + *output_len, &len);
    *output_len += len;
    
    EVP_CIPHER_CTX_cleanup(ctx);
    return 0;
    
cleanup:
    *output_len = 0;
    return 1;
}
Beispiel #9
0
const EVP_CIPHER* get_cipher_type(const enum cipher cipher, const enum cipher_mode mode) {

    switch (mode) {
        case MODE_ECB:

            switch (cipher) {
                case CIPHER_DES:
                    return EVP_des_ecb();
                case CIPHER_AES_128:
                    return EVP_aes_128_ecb();
                case CIPHER_AES_192:
                    return EVP_aes_192_ecb();
                case CIPHER_AES_256:
                    return EVP_aes_256_ecb();
            }

        case MODE_CBC:

            switch (cipher) {
                case CIPHER_DES:
                    return EVP_des_cbc();
                case CIPHER_AES_128:
                    return EVP_aes_128_cbc();
                case CIPHER_AES_192:
                    return EVP_aes_192_cbc();
                case CIPHER_AES_256:
                    return EVP_aes_256_cbc();
            }

        case MODE_OFB:

            switch (cipher) {
                case CIPHER_DES:
                    return EVP_des_ofb();
                case CIPHER_AES_128:
                    return EVP_aes_128_ofb();
                case CIPHER_AES_192:
                    return EVP_aes_192_ofb();
                case CIPHER_AES_256:
                    return EVP_aes_256_ofb();
            }

        case MODE_CFB:

            switch (cipher) {
                case CIPHER_DES:
                    return EVP_des_cfb();
                case CIPHER_AES_128:
                    return EVP_aes_128_cfb();
                case CIPHER_AES_192:
                    return EVP_aes_192_cfb();
                case CIPHER_AES_256:
                    return EVP_aes_256_cfb();
            }
    }

    abort();
}
Beispiel #10
0
/** 
 * @brief Performs basic Encrypt-then-MAC style Authenticated Encryption.
 *
 * @param[in] ekey          a buffer holding the ENC key
 * @param[in] ekey_len      len of ekey buffer
 * @param[in] mkey          a buffer holding the MAC key
 * @param[in] mkey_len      len of mkey buffer
 * @param[in] input         the plaintext message
 * @param[in] input_len     len of message buffer
 * @param[in,out] ctxt      an allocated buffer, will hold the ciphertext
 * @param[in,out] ctxt_len  length of buffer, will hold length of ciphertext
 * @param[in,out] mac       an allocated buffer, will hold the MAC
 * @param[in,out] mac_len   length of buffer, will hold length of MAC
 * @param[in,out] iv        a randomly chosen iv (optional)
 * @param[in] iv_len        length of buffer for iv (optional)
 * @return 0 on success, non-zero on error
 **/
int encrypt_then_mac(const unsigned char *ekey, size_t ekey_len, 
                     const unsigned char *mkey, size_t mkey_len,
                     const unsigned char *input, size_t input_len,
                     unsigned char *ctxt, size_t *ctxt_len,
                     unsigned char *mac, size_t *mac_len,
                     unsigned char *iv, size_t iv_len)
{
    EVP_CIPHER_CTX *ctx;
    ctx = EVP_CIPHER_CTX_new();
    EVP_CIPHER *cipher = NULL;
    int len;
    
    if (!ekey || !ekey_len || !mkey || !mkey_len || 
        !input_len || !ctxt || !ctxt_len || !mac || !mac_len)
        return -1;
    
    OpenSSL_add_all_algorithms();
    
    EVP_CIPHER_CTX_init(ctx);
    switch(ekey_len){
        case 16:
            cipher = (EVP_CIPHER *)EVP_aes_128_cbc();
            break;
        case 24:
            cipher = (EVP_CIPHER *)EVP_aes_192_cbc();
            break;
        case 32:
            cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
            break;
        default:
            return -1;
    }

    if (iv && iv_len) {
        if (!RAND_bytes(iv, iv_len)) goto cleanup;
    }

    if (!EVP_EncryptInit(ctx, cipher, ekey, iv)) goto cleanup;    

    *ctxt_len = 0;
    if (!EVP_EncryptUpdate(ctx, ctxt, (int *) ctxt_len, input, input_len))
        goto cleanup;
    EVP_EncryptFinal(ctx, ctxt + *ctxt_len, &len);
    *ctxt_len += len;
    
    // Do the HMAC-SHA1
    *mac_len = 0;
    if (!HMAC(EVP_sha1(), mkey, mkey_len, ctxt, *ctxt_len,
                          mac, (unsigned int *) mac_len))
        goto cleanup;
    EVP_CIPHER_CTX_cleanup(ctx);
    return 0;
    
cleanup:
    if (ctxt_len) *ctxt_len = 0;
    if (mac_len) *mac_len = 0;
    return 1;
}
Beispiel #11
0
int openssl_encrypt(struct emvpn_socket *v, uint8_t *to, uint8_t *from, int len)
{
    int clen, flen = 0;
    EVP_CIPHER_CTX_init(&enc);
    EVP_EncryptInit(&enc, EVP_aes_256_cbc(), v->key.key, v->key.iv);
    EVP_EncryptUpdate(&enc, to, &clen, from, len);
    EVP_EncryptFinal_ex(&enc, to + clen, &flen);
    return clen + (flen % 16) ;
}
Beispiel #12
0
int aes_init(unsigned char* pwd, unsigned int pwd_len, unsigned char * salt, EVP_CIPHER_CTX *e_ctx, EVP_CIPHER_CTX *d_ctx)
{
	int i, rounds =5; 					/* rounds */
	unsigned char key[32], iv[32];
	
	i = EVP_BytesToKey(EVP_aes_256_cbc(),EVP_sha1(),salt,pwd,pwd_len,rounds,key,iv);
	if(i != 32)
	{
		printf("\n Error,Incorrect key size generated:%d:\n",i);
		return -1;
	}
	
	EVP_CIPHER_CTX_init(e_ctx);
	EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
	EVP_CIPHER_CTX_init(d_ctx);
        EVP_DecryptInit_ex(d_ctx, EVP_aes_256_cbc(), NULL, key, iv);
	return 0;
}
Beispiel #13
0
/**
 * @brief ChaCha-AVX Create Key function
 * @see el_chacha_avx_encrypt_data()
 * @see el_chacha_avx_decrypt_data()
 * @param key_data The data that will be used to create the key (eg. user+pass)
 * @param key The key generated, based on key_data value
 * @return 0 on success, -1 on error.
 */
int el_chacha_avx_create_key(const unsigned char *key_data, unsigned char *key) {
	int ret, nrounds = 5;
	unsigned char iv[32];

	/* XXX: Get rid of openssl from chacha_avx code asap */
	ret = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), NULL, key_data, strlen((char *) key_data), nrounds, key, iv);

	return -(ret != 32);
}
Beispiel #14
0
int s2n_cbc_cipher_aes256_set_encryption_key(struct s2n_session_key *key, struct s2n_blob *in)
{
    eq_check(in->size, 256 / 8);

    EVP_CIPHER_CTX_set_padding(key->evp_cipher_ctx, EVP_CIPH_NO_PADDING);
    GUARD_OSSL(EVP_EncryptInit_ex(key->evp_cipher_ctx, EVP_aes_256_cbc(), NULL, in->data, NULL), S2N_ERR_KEY_INIT);

    return 0;
}
Beispiel #15
0
/*
 * return OpenSSL cipher for JWE encryption algorithm
 */
static const EVP_CIPHER *apr_jwe_enc_to_openssl_cipher(const char *enc) {
	if (apr_strnatcmp(enc, "A128CBC-HS256") == 0) {
		return EVP_aes_128_cbc();
	}
	if (apr_strnatcmp(enc, "A256CBC-HS512") == 0) {
		return EVP_aes_256_cbc();
	}
	return NULL;
}
Beispiel #16
0
int SSL_library_init(void)
	{

#ifndef OPENSSL_NO_DES
	EVP_add_cipher(EVP_des_cbc());
	EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
	EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
	EVP_add_cipher(EVP_rc4());
#endif  
#ifndef OPENSSL_NO_RC2
	EVP_add_cipher(EVP_rc2_cbc());
#endif
#ifndef OPENSSL_NO_AES
	EVP_add_cipher(EVP_aes_128_cbc());
	EVP_add_cipher(EVP_aes_192_cbc());
	EVP_add_cipher(EVP_aes_256_cbc());
#endif
#ifndef OPENSSL_NO_MD2
	EVP_add_digest(EVP_md2());
#endif
#ifndef OPENSSL_NO_MD5
	EVP_add_digest(EVP_md5());
	EVP_add_digest_alias(SN_md5,"ssl2-md5");
	EVP_add_digest_alias(SN_md5,"ssl3-md5");
#endif
#ifndef OPENSSL_NO_SHA
	EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
	EVP_add_digest_alias(SN_sha1,"ssl3-sha1");
	EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);
#endif
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)
	EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
	EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);
	EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1");
	EVP_add_digest_alias(SN_dsaWithSHA1,"dss1");
#endif
#ifndef OPENSSL_NO_ECDSA
	EVP_add_digest(EVP_ecdsa());
#endif
	/* If you want support for phased out ciphers, add the following */
#if 0
	EVP_add_digest(EVP_sha());
	EVP_add_digest(EVP_dss());
#endif
#ifndef OPENSSL_NO_COMP
	/* This will initialise the built-in compression algorithms.
	   The value returned is a STACK_OF(SSL_COMP), but that can
	   be discarded safely */
	(void)SSL_COMP_get_compression_methods();
#endif
	return(1);
	}
Beispiel #17
0
/**
  Retrieve the RSA Private Key from the password-protected PEM key data.

  @param[in]  PemData      Pointer to the PEM-encoded key data to be retrieved.
  @param[in]  PemSize      Size of the PEM key data in bytes.
  @param[in]  Password     NULL-terminated passphrase used for encrypted PEM key data.
  @param[out] RsaContext   Pointer to new-generated RSA context which contain the retrieved
                           RSA private key component. Use RsaFree() function to free the
                           resource.

  If PemData is NULL, then return FALSE.
  If RsaContext is NULL, then return FALSE.

  @retval  TRUE   RSA Private Key was retrieved successfully.
  @retval  FALSE  Invalid PEM key data or incorrect password.

**/
BOOLEAN
EFIAPI
RsaGetPrivateKeyFromPem (
  IN   CONST UINT8  *PemData,
  IN   UINTN        PemSize,
  IN   CONST CHAR8  *Password,
  OUT  VOID         **RsaContext
  )
{
  BOOLEAN  Status;
  BIO      *PemBio;

  //
  // Check input parameters.
  //
  if (PemData == NULL || RsaContext == NULL || PemSize > INT_MAX) {
    return FALSE;
  }

  Status = FALSE;
  PemBio = NULL;

  //
  // Add possible block-cipher descriptor for PEM data decryption.
  // NOTE: Only support most popular ciphers (3DES, AES) for the encrypted PEM.
  //
  EVP_add_cipher (EVP_des_ede3_cbc());
  EVP_add_cipher (EVP_aes_128_cbc());
  EVP_add_cipher (EVP_aes_192_cbc());
  EVP_add_cipher (EVP_aes_256_cbc());

  //
  // Read encrypted PEM Data.
  //
  PemBio = BIO_new (BIO_s_mem ());
  BIO_write (PemBio, PemData, (int)PemSize);
  if (PemBio == NULL) {
    goto _Exit;
  }

  //
  // Retrieve RSA Private Key from encrypted PEM data.
  //
  *RsaContext = PEM_read_bio_RSAPrivateKey (PemBio, NULL, (pem_password_cb *)&PasswordCallback, (void *)Password);
  if (*RsaContext != NULL) {
    Status = TRUE;
  }

_Exit:
  //
  // Release Resources.
  //
  BIO_free (PemBio);

  return Status;
}
/*
 * This function decrypts a string after it has been received on a socket.
 * It performs previous checking on the format and may discard the 
 * message and return an error if the format mismatch. We can avoid a 
 * decryption if the format mismatches.
 * 
 * @return It returns the plaintext length or -1 if a generic error occured,
 * -2 if the format is not the one expected and 0 in case of disconnection.
 * It leaves the decrypted message in **plain ( which is allocated).
 */
int decrypt_msg(int sk, char format, unsigned char** plain, unsigned char* shared_secret)
{
	EVP_CIPHER_CTX* ctx;
	unsigned char iv[EVP_MAX_IV_LENGTH];
	unsigned int iv_len = EVP_MAX_IV_LENGTH;
	unsigned char* msg = NULL;//msg has to set free in this function
	unsigned int msg_len;
	char recv_format;
	int outlen, outtot = 0, ret;
	*plain = NULL;
	ctx = (EVP_CIPHER_CTX*)calloc(1, sizeof(EVP_CIPHER_CTX));
	EVP_CIPHER_CTX_init(ctx);
	
	if ((msg_len = recv_msg(sk, &msg, &recv_format)) <= 0) {
		ret = msg_len;
		goto fail;
	}
	
	if (recv_format != format) {
		ret = -2;
		goto fail;
	}
	
	*plain = (unsigned char*)calloc(1, msg_len - iv_len);
	memcpy(iv, msg, iv_len);
	if (EVP_DecryptInit(ctx, EVP_aes_256_cbc(), shared_secret, iv) == 0) {
		ret = -1;
		goto fail;
	}
	if (EVP_DecryptUpdate(ctx, *plain, &outlen, msg + iv_len, msg_len - iv_len) == 0) {
		ret = -1;
		goto fail;
	}
	outtot = outlen;
	if (EVP_DecryptFinal(ctx, *plain + outtot, &outlen) == 0) {
		ret = -1;
		goto fail;
	}
	outtot += outlen;
	
	EVP_CIPHER_CTX_cleanup(ctx);
	free(ctx);
	free(msg);
	return outtot;
	
fail:	EVP_CIPHER_CTX_cleanup(ctx);
	free(ctx);
	if (*plain != NULL) {
		free(*plain);
	}
	if (msg != NULL) {
		free(msg);
	}
	return ret;
	
}
Beispiel #19
0
crypto_aes_t *crypto_aes_open (const void *key,
                               unsigned int key_size,
                               const void *salt,
                               unsigned int salt_size)
{
    unsigned char ikey[32];
    unsigned char iv[32];
    crypto_aes_t *crypto;

    /* Key Derivation */
    if (crypto_aes_key(ikey, iv, key, key_size, salt, salt_size))
        return(NULL);

    /* Allocate Crypto AES Object */
    if ((crypto = (crypto_aes_t *) malloc(sizeof(crypto_aes_t))) == NULL)
        return(NULL);

    if (pthread_mutex_init(&(crypto->lock), NULL)) {
        free(crypto);
        return(NULL);
    }

    /* Initialize Encryption */
    EVP_CIPHER_CTX_init(&(crypto->enc));
    if (!EVP_EncryptInit_ex(&(crypto->enc), EVP_aes_256_cbc(), NULL, ikey, iv)) {
        EVP_CIPHER_CTX_cleanup(&(crypto->enc));
        pthread_mutex_destroy(&(crypto->lock));
        free(crypto);
        return(NULL);
    }

    /* Initialize Decryption */
    EVP_CIPHER_CTX_init(&(crypto->dec));
    if (!EVP_DecryptInit_ex(&(crypto->dec), EVP_aes_256_cbc(), NULL, ikey, iv)) {
        EVP_CIPHER_CTX_cleanup(&(crypto->enc));
        EVP_CIPHER_CTX_cleanup(&(crypto->dec));
        pthread_mutex_destroy(&(crypto->lock));
        free(crypto);
        return(NULL);
    }

    return(crypto);
}
Beispiel #20
0
static const EVP_CIPHER *
map_mode(unsigned int len)
{
    if (len==16)
        return EVP_aes_128_cbc();
    if (len==32)
        return EVP_aes_256_cbc();
    else
        return NULL;
}
Beispiel #21
0
int
SSL_library_init(void)
{

#ifndef OPENSSL_NO_DES
	EVP_add_cipher(EVP_des_cbc());
	EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
	EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
	EVP_add_cipher(EVP_rc4());
#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))
	EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif  
#ifndef OPENSSL_NO_RC2
	EVP_add_cipher(EVP_rc2_cbc());
	/* Not actually used for SSL/TLS but this makes PKCS#12 work
	 * if an application only calls SSL_library_init().
	 */
	EVP_add_cipher(EVP_rc2_40_cbc());
#endif
	EVP_add_cipher(EVP_aes_128_cbc());
	EVP_add_cipher(EVP_aes_192_cbc());
	EVP_add_cipher(EVP_aes_256_cbc());
	EVP_add_cipher(EVP_aes_128_gcm());
	EVP_add_cipher(EVP_aes_256_gcm());
	EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
	EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#ifndef OPENSSL_NO_CAMELLIA
	EVP_add_cipher(EVP_camellia_128_cbc());
	EVP_add_cipher(EVP_camellia_256_cbc());
#endif

	EVP_add_digest(EVP_md5());
	EVP_add_digest_alias(SN_md5, "ssl2-md5");
	EVP_add_digest_alias(SN_md5, "ssl3-md5");
	EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
	EVP_add_digest_alias(SN_sha1, "ssl3-sha1");
	EVP_add_digest_alias(SN_sha1WithRSAEncryption, SN_sha1WithRSA);
	EVP_add_digest(EVP_sha224());
	EVP_add_digest(EVP_sha256());
	EVP_add_digest(EVP_sha384());
	EVP_add_digest(EVP_sha512());
	EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
	EVP_add_digest_alias(SN_dsaWithSHA1, SN_dsaWithSHA1_2);
	EVP_add_digest_alias(SN_dsaWithSHA1, "DSS1");
	EVP_add_digest_alias(SN_dsaWithSHA1, "dss1");
	EVP_add_digest(EVP_ecdsa());
	/* initialize cipher/digest methods table */
	ssl_load_ciphers();
	return (1);
}
Beispiel #22
0
bool EnigmaMachine::init(BinaryData* password, int passwordLength, BinaryData* salt)
{
   int nrounds(5);
   BinaryData 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.
   int keySize = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, password, 
          passwordLength, nrounds, key, iv);
           
   if (keySize != 32) return false;

   EVP_CIPHER_CTX_init(&m_encryptContext);
   EVP_EncryptInit_ex(&m_encryptContext, EVP_aes_256_cbc(), NULL, key, iv);
   EVP_CIPHER_CTX_init(&m_decryptContext);
   EVP_DecryptInit_ex(&m_decryptContext, EVP_aes_256_cbc(), NULL, key, iv);
 
   return true;
}
Beispiel #23
0
static const EVP_CIPHER * _wi_cipher_cipher(wi_cipher_t *cipher) {
	switch(cipher->type) {
		case WI_CIPHER_AES128:		return EVP_aes_128_cbc();
		case WI_CIPHER_AES192:		return EVP_aes_192_cbc();
		case WI_CIPHER_AES256:		return EVP_aes_256_cbc();
		case WI_CIPHER_BF128:		return EVP_bf_cbc();
		case WI_CIPHER_3DES192:		return EVP_des_ede3_cbc();
	}
	
	return NULL;
}
Beispiel #24
0
static const EVP_CIPHER * typeToCIPHER(Cipher::Type t)
{
	if(t == Cipher::TripleDES)
		return EVP_des_ede3_cbc();
	else if(t == Cipher::AES_128)
		return EVP_aes_128_cbc();
	else if(t == Cipher::AES_256)
		return EVP_aes_256_cbc();
	else
		return 0;
}
Beispiel #25
0
static const EVP_CIPHER* cipher_by_name(const char *name) {
  if (strcmp(name, "DES-CBC") == 0) {
    return EVP_des_cbc();
  } else if (strcmp(name, "AES-128-CBC") == 0) {
    return EVP_aes_128_cbc();
  } else if (strcmp(name,  "AES-256-CBC") == 0) {
    return EVP_aes_256_cbc();
  } else {
    return NULL;
  }
}
Beispiel #26
0
void UBCryptoUtils::aesInit()
{
    int i, nrounds = 5;
    unsigned char key[32], iv[32];
    unsigned char *key_data = (unsigned char *)sAESKey.toAscii().data();
    int key_data_len = sAESKey.length();

    i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), (unsigned char *)sAESSalt.toAscii().data(), key_data,
            key_data_len, nrounds, key, iv);

    if (i != 32)
    {
        qWarning() << QString("Key size is %1 bits - should be 256 bits").arg(i);
        return;
    }

    EVP_CIPHER_CTX_init(&mAesEncryptContext);
    EVP_EncryptInit_ex(&mAesEncryptContext, EVP_aes_256_cbc(), NULL, key, iv);
    EVP_CIPHER_CTX_init(&mAesDecryptContext);
    EVP_DecryptInit_ex(&mAesDecryptContext, EVP_aes_256_cbc(), NULL, key, iv);
}
size_t get_ciphertext_size(size_t plaintext_len) {

    size_t block_size = 0;

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

    return plaintext_len + block_size;
}
Beispiel #28
0
 /*
tlamijan
*/
int main(void) {
 
  unsigned char ot[1024];  // open text
  unsigned char st[1024];  // sifrovany text
  unsigned char key[EVP_MAX_KEY_LENGTH] = "Super tajny klic";  // klic pro sifrovani
  unsigned char iv[EVP_MAX_IV_LENGTH] = "vector unknown";  // inicializacni vektor
  const char * filename = "Mad_scientist.bmp";
  const char * outfilename = "Mad_scientist_aes_cbc.bmp";

  int otLength = 0;
  int stLength = 0;
  int tmpLength = 0;
  int readlen = 0;
  char header[14];
  unsigned int offset = 0;
 
  EVP_CIPHER_CTX ctx; // struktura pro kontext
 
	FILE * fin = fopen(filename,"rb");
	FILE * fout = fopen(outfilename,"w+b");
	if(!fin){
		printf("File not found");
	}

	fread(header,1,14,fin);
	fwrite(header,1,14,fout);
	offset = (unsigned int)*(&header[10]);
	offset -= 14;

	while(offset > 1024){
		fread(ot,1,1024,fin);
		fwrite(ot,1,1024,fout);
		offset -= 1024;
	}
	fread(ot,1,offset,fin);
	fwrite(ot,1,offset,fout);
	

 EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key, iv);  // nastaveni kontextu pro sifrovani
  do{
	  readlen = fread(ot,1,1024,fin);
	  EVP_EncryptUpdate(&ctx,  st, &stLength, ot, readlen);  // sifrovani ot
	  fwrite(st,1,stLength,fout);
  }while(readlen == 1024);
  
  EVP_EncryptFinal(&ctx, &st[stLength], &tmpLength);  // ziskani sifrovaneho textu z kontextu
  fwrite(&st[stLength],1,tmpLength,fout);
  stLength += tmpLength;

  fclose(fin);
  fclose(fout);
  exit(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
 **/
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;
}
Beispiel #30
-1
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;
}