Пример #1
1
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
    if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
        return false;

    int i = 0;
    if (nDerivationMethod == 0)
    {
        i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
                          (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
    }

    if (nDerivationMethod == 1)
    {
        // Passphrase conversion
        uint256 scryptHash = scrypt_salted_multiround_hash((const void*)strKeyData.c_str(), strKeyData.size(), &chSalt[0], 8, nRounds);

        i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
                          (unsigned char *)&scryptHash, sizeof scryptHash, nRounds, chKey, chIV);
        OPENSSL_cleanse(&scryptHash, sizeof scryptHash);
    }


    if (i != (int)WALLET_CRYPTO_KEY_SIZE)
    {
        OPENSSL_cleanse(chKey, sizeof(chKey));
        OPENSSL_cleanse(chIV, sizeof(chIV));
        return false;
    }

    fKeySet = true;
    return true;
}
Пример #2
0
/**
* @brief Prepares AES encryption and decryption contexts.
*
* 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
*
* Code adapted from: http://saju.net.in/code/misc/openssl_aes.c.txt
*
* @param key_data
* @param key_data_len
* @param salt
* @param e_ctx
* @param d_ctx
*
* @return 0 on success
*/
int aes_init(unsigned char *en_key_data, int en_key_data_len, 
			 unsigned char *de_key_data, int de_key_data_len, 
			 unsigned char *salt, EVP_CIPHER_CTX *e_ctx, 
             EVP_CIPHER_CTX *d_ctx) {
	int i, nrounds = 5;
	unsigned char en_key[32], en_iv[32], de_key[32], de_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, en_key_data, en_key_data_len, nrounds, en_key, en_iv);
	if (i != 32) {
	  ERRORF("Key size is %d bits - should be 256 bits", i);
	  return -1;
	}
	if (EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, en_key, en_iv) != 1) {
		ERROR("ERROR initializing encryption context");
		return -1;
	}

	i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, de_key_data, de_key_data_len, nrounds, de_key, de_iv);
	if (i != 32) {
	  ERRORF("Key size is %d bits - should be 256 bits", i);
	  return -1;
	}
	if (EVP_DecryptInit_ex(d_ctx, EVP_aes_256_cbc(), NULL, de_key, de_iv) != 1) {
		ERROR("ERROR initializing decryption context");
		return -1;
	}
	
	return 0;
}
Пример #3
0
int
seafile_derive_key (const char *data_in, int in_len, int version,
                    unsigned char *key, unsigned char *iv)
{
    if (version == 2) {
        PKCS5_PBKDF2_HMAC (data_in, in_len,
                           salt, sizeof(salt),
                           KEYGEN_ITERATION2,
                           EVP_sha256(),
                           32, key);
        PKCS5_PBKDF2_HMAC ((char *)key, 32,
                           salt, sizeof(salt),
                           10,
                           EVP_sha256(),
                           16, iv);
        return 0;
    } else if (version == 1)
        return EVP_BytesToKey (EVP_aes_128_cbc(), /* cipher mode */
                               EVP_sha1(),        /* message digest */
                               salt,              /* salt */
                               (unsigned char*)data_in,
                               in_len,
                               KEYGEN_ITERATION,   /* iteration times */
                               key, /* the derived key */
                               iv); /* IV, initial vector */
    else
        return EVP_BytesToKey (EVP_aes_128_ecb(), /* cipher mode */
                               EVP_sha1(),        /* message digest */
                               NULL,              /* salt */
                               (unsigned char*)data_in,
                               in_len,
                               3,   /* iteration times */
                               key, /* the derived key */
                               iv); /* IV, initial vector */
}
Пример #4
0
//02 002
void config_encryption(const char *password, const char *method) {
    SSLeay_add_all_algorithms();
    sodium_init();
    _method = encryption_method_from_string(method);
    if (_method == ENCRYPTION_TABLE) {
        get_table((unsigned char *) password);
        cipher = CIPHER_TABLE;
    } else if (_method == ENCRYPTION_SALSA20 || _method == ENCRYPTION_CHACHA20) {
        cipher = CIPHER_SODIUM;
        _key_len = 32;
        unsigned char tmp[EVP_MAX_IV_LENGTH];;
        EVP_BytesToKey(EVP_aes_256_cfb(), EVP_md5(), NULL, (unsigned char *)password,
                                strlen(password), 1, _key, tmp);
        shadowsocks_key = _key;
    } else {
        cipher = CIPHER_OPENSSL;
        const char *name = shadowsocks_encryption_names[_method];
        if (_method == ENCRYPTION_RC4_MD5) {
            name = "RC4";
        }
        _cipher = EVP_get_cipherbyname(name);
        if (_cipher == NULL) {
//            assert(0);
            // TODO
            printf("_cipher is nil! \r\nThe %s doesn't supported!\r\n please chose anthor!",name);
        } else {
            unsigned char tmp[EVP_MAX_IV_LENGTH];
            _key_len = EVP_BytesToKey(_cipher, EVP_md5(), NULL, (unsigned char *)password,
                                      strlen(password), 1, _key, tmp);
            shadowsocks_key = _key;
        }

//        printf("%d\n", _key_len);
    }
}
Пример #5
0
/******************************************************************************
 Two way hashing: AES, DES, BlowFish, RC4
 ******************************************************************************/
void Encryption::EncryptionInit() {
    unsigned char key[EVP_MAX_KEY_LENGTH];
    unsigned char iv[EVP_MAX_IV_LENGTH] = "Ben";
    EVP_CIPHER_CTX_init(&ectx);
    EVP_CIPHER_CTX_init(&dctx);
    /* 8 bytes to salt the key_data during key generation. This is an example of
     compiled in salt. We just read the bit pattern created by these two 4 byte
     integers on the stack as 64 bits of contigous salt material -
     ofcourse this only works if sizeof(int) >= 4 */
    unsigned int salt[] = { 12345, 54321 };
    int i, nrounds = 5;
    switch (EncryptionType) {
    case 0:
        //No Encryption Mode
        break;
    case 1:
        i = EVP_BytesToKey(EVP_aes_128_cfb(), EVP_sha1(),
                           (unsigned char *) &salt, (unsigned char *) Password, strlen(
                               Password), nrounds, key, iv);
        EVP_EncryptInit_ex(&ectx, EVP_aes_128_cfb(), NULL,
                           (unsigned char*) key, (unsigned char*) &iv);
        EVP_DecryptInit_ex(&dctx, EVP_aes_128_cfb(), NULL,
                           (unsigned char*) key, (unsigned char*) &iv);
        break;
    case 2:
        i = EVP_BytesToKey(EVP_des_ede_cfb(), EVP_sha1(),
                           (unsigned char *) &salt, (unsigned char *) Password, strlen(
                               Password), nrounds, key, iv);
        EVP_EncryptInit_ex(&ectx, EVP_des_ede_cfb(), NULL,
                           (unsigned char*) key, (unsigned char*) &iv);
        EVP_DecryptInit_ex(&dctx, EVP_des_ede_cfb(), NULL,
                           (unsigned char*) key, (unsigned char*) &iv);
        break;
    case 3:
        i = EVP_BytesToKey(EVP_rc4(), EVP_sha1(), (unsigned char *) &salt,
                           (unsigned char *) Password, strlen(Password), nrounds, key, iv);
        EVP_EncryptInit_ex(&ectx, EVP_rc4(), NULL, (unsigned char*) key,
                           (unsigned char*) &iv);
        EVP_DecryptInit_ex(&dctx, EVP_rc4(), NULL, (unsigned char*) key,
                           (unsigned char*) &iv);
        break;
    case 4:
        i = EVP_BytesToKey(EVP_bf_cfb(), EVP_sha1(), (unsigned char *) &salt,
                           (unsigned char *) Password, strlen(Password), nrounds, key, iv);
        EVP_EncryptInit_ex(&ectx, EVP_bf_cfb(), NULL, (unsigned char*) key,
                           (unsigned char*) &iv);
        EVP_DecryptInit_ex(&dctx, EVP_bf_cfb(), NULL, (unsigned char*) key,
                           (unsigned char*) &iv);
        break;
    }
    return;
}
Пример #6
0
static int decrypt(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_DecryptInit_ex(etx,EVP_aes_256_cfb(),NULL,key,iv);
	len=ilen;
	if(!EVP_DecryptUpdate(etx,out,&len,in,ilen))goto err3;
	rem=ilen-len;
	if(!EVP_DecryptFinal_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_DecryptInit_ex(&etx,EVP_aes_256_cfb(),NULL,key,iv);
	len=ilen;
	if(!EVP_DecryptUpdate(&etx,out,&len,in,ilen))goto err3;
	rem=ilen-len;
	if(!EVP_DecryptFinal_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;
}
Пример #7
0
int
ccnet_generate_cipher (const char *passwd, int plen,
                       unsigned char *key, unsigned char *iv)
{
    int key_len;

    /* Generate the derived key. We use AES 256 bits key,
       CBC cipher mode, and SHA1 as the message digest
       when generating the key. IV is not used in ecb mode,
       actually. */
    key_len  = EVP_BytesToKey (EVP_aes_256_cbc(), /* cipher mode */
                               EVP_sha1(),        /* message digest */
                               NULL,              /* salt */
                               (unsigned char*)passwd,
                               plen,
                               3,   /* iteration times */
                               key, /* the derived key */
                               iv); /* IV, initial vector */

    /* The key should be 32 bytes long for our 256 bit key. */
    if (key_len != KEY_SIZE) {
        g_warning ("failed to init EVP_CIPHER_CTX.\n");
        return -1;
    }

    return 0;
}
Пример #8
0
uint32_t decrypt(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, 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_DecryptInit_ex(&ctx, function(), NULL, key, iv); 
	EVP_DecryptUpdate(&ctx, out, &outl, data, len); 
	EVP_DecryptFinal_ex(&ctx, out + outl, &templ);
	outl +=templ;
	memcpy(ans, out, outl);
	
	/* Clean context struct */ 
	EVP_CIPHER_CTX_cleanup(&ctx);
	free(out);
	return outl;
}
Пример #9
0
char *
CGI_encrypt(const void *p, int len, const char *password) {
    EVP_CIPHER_CTX ctx;
    unsigned char md[DIGEST_SIZE];
    unsigned char iv[EVP_MAX_IV_LENGTH];
    unsigned char key[EVP_MAX_KEY_LENGTH];
    unsigned char *out;
    char *b64;
    int offset, rlen;

    if (p == 0 || len <= 0 || password == 0 || *password == 0) {
        return 0;
    }
    out = malloc(SALT_SIZE + DIGEST_SIZE + len + EVP_MAX_BLOCK_LENGTH);
    init_salt(out);
    digest(p, len, password, out, md);
    EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), out,
        (unsigned char *) password, strlen(password), 1, key, iv);
    EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key, iv);
    offset = SALT_SIZE;
    EVP_EncryptUpdate(&ctx, out + offset, &rlen, md, DIGEST_SIZE);
    offset += rlen;
    EVP_EncryptUpdate(&ctx, out + offset, &rlen, p, len);
    offset += rlen;
    EVP_EncryptFinal(&ctx, out + offset, &rlen);
    b64 = CGI_encode_base64(out, offset + rlen);
    free(out);
    return b64;
}
Пример #10
0
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
    if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
        return false;

    // Try to keep the keydata out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap)
    // Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
    // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.  
    // mlock(&chKey[0], sizeof chKey);
    // mlock(&chIV[0], sizeof chIV);

    int i = 0;
    if (nDerivationMethod == 0)
        i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
                          (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);

    if (i != (int)WALLET_CRYPTO_KEY_SIZE)
    {
        // memset(&chKey, 0, sizeof chKey);
        // memset(&chIV, 0, sizeof chIV);
        OPENSSL_cleanse(chKey, sizeof(chKey));
        OPENSSL_cleanse(chIV, sizeof(chIV));
        return false;
    }

    fKeySet = true;
    return true;
}
Пример #11
0
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
                  pem_password_cb *callback, void *u)
{
    int ok;
    int keylen;
    long len = *plen;
    int ilen = (int) len;       /* EVP_DecryptUpdate etc. take int lengths */
    EVP_CIPHER_CTX *ctx;
    unsigned char key[EVP_MAX_KEY_LENGTH];
    char buf[PEM_BUFSIZE];

#if LONG_MAX > INT_MAX
    /* Check that we did not truncate the length */
    if (len > INT_MAX) {
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_HEADER_TOO_LONG);
        return 0;
    }
#endif

    if (cipher->cipher == NULL)
        return 1;
    if (callback == NULL)
        keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
    else
        keylen = callback(buf, PEM_BUFSIZE, 0, u);
    if (keylen < 0) {
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
        return 0;
    }
#ifdef CHARSET_EBCDIC
    /* Convert the pass phrase from EBCDIC */
    ebcdic2ascii(buf, buf, keylen);
#endif

    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
                        (unsigned char *)buf, keylen, 1, key, NULL))
        return 0;

    ctx = EVP_CIPHER_CTX_new();
    if (ctx == NULL)
        return 0;

    ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
    if (ok)
        ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
    if (ok) {
        /* Squirrel away the length of data decrypted so far. */
        *plen = ilen;
        ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
    }
    if (ok)
        *plen += ilen;
    else
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);

    EVP_CIPHER_CTX_free(ctx);
    OPENSSL_cleanse((char *)buf, sizeof(buf));
    OPENSSL_cleanse((char *)key, sizeof(key));
    return ok;
}
Пример #12
0
bool keyGen(KEY *k, char * password){
    const EVP_CIPHER *cipher;
    const EVP_MD *dgst = NULL;
    const unsigned char *salt = NULL;

    OpenSSL_add_all_algorithms();

    cipher = EVP_get_cipherbyname("aes-256-cbc");
    if(!cipher) {
        fprintf(stderr, "no such cipher\n");
        return false;
    }

    dgst=EVP_get_digestbyname("md5");
    if(!dgst) { 
        fprintf(stderr, "no such digest\n"); 
        return false; 
    }

    if(!EVP_BytesToKey(cipher, dgst, salt,(unsigned char *) password,strlen(password), 1, k->key, k->iv)){
        fprintf(stderr, "EVP_BytesToKey failed\n");
        return false;
    }
    k->KL = cipher->key_len;
    k->IL = cipher->iv_len;
}
Пример #13
0
void
BufferDecryptor::generate_key(int cipher)
{
#ifdef HAVE_LIBCRYPTO
  const EVP_CIPHER *evp_cipher = cipher_by_id(cipher);

  const size_t key_size = EVP_CIPHER_key_length(evp_cipher);
  const size_t iv_size = EVP_CIPHER_iv_length(evp_cipher);
  unsigned char *key = (unsigned char *)malloc(key_size);
  unsigned char iv[iv_size];
  if( ! EVP_BytesToKey(evp_cipher, EVP_sha256(), NULL,
		       (const unsigned char *)key_.c_str(), key_.size(), 8, key, iv))
  {
    free(key);
#endif
    throw std::runtime_error("Failed to generate key");
#ifdef HAVE_LIBCRYPTO
  }

  std::string ks((const char *)key, key_size);
  free(key);

  keys_[cipher] = ks;
#endif
}
Пример #14
0
int main(void) {
  uc key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], salt[SALT_LENGTH];
  ccp cipher_name = getenv("CIPHER");
  ccp digest_name = getenv("DIGEST");
  ccp salt_hex = getenv("SALT");
  ccp password = getenv("PASSWORD");
  if (!cipher_name)
    cipher_name = "blowfish";
  if (!digest_name)
    digest_name = "md5";
  if (!password || !strlen(password))
    return EXIT_BAD_PASS;
  if (salt_hex && strlen(salt_hex) < 2 * SALT_LENGTH)
    return EXIT_BAD_SALT;
  if (salt_hex)
    for (int i = 0; i < SALT_LENGTH; i++)
      sscanf(salt_hex + 2 * i, "%2hhx", salt + i);
  OpenSSL_add_all_algorithms();
  const EVP_CIPHER *ciph = EVP_get_cipherbyname(cipher_name);
  const EVP_MD *dgst = EVP_get_digestbyname(digest_name);
  int keylen = EVP_BytesToKey(ciph, dgst, salt_hex ? salt : NULL,
                              (uc *)password, strlen(password), 1, key, iv);
  if (!keylen)
    return EXIT_SSL_FAIL;
  if (salt_hex)
    hex("salt", salt, SALT_LENGTH);
  hex("key", key, keylen);
  hex("iv", iv, IV_LENGTH);
  return EXIT_SUCCESS;
}
static VALUE
ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
    EVP_CIPHER_CTX *ctx;
    const EVP_MD *digest;
    VALUE vpass, vsalt, viter, vdigest;
    unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
    int iter;

    rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
    StringValue(vpass);
    if(!NIL_P(vsalt)){
	StringValue(vsalt);
	if(RSTRING(vsalt)->len != PKCS5_SALT_LEN)
	    rb_raise(eCipherError, "salt must be an 8-octet string");
	salt = RSTRING(vsalt)->ptr;
    }
    iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
    digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
    GetCipher(self, ctx);
    EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
		   RSTRING(vpass)->ptr, RSTRING(vpass)->len, iter, key, iv); 
    if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
	ossl_raise(eCipherError, NULL);
    OPENSSL_cleanse(key, sizeof key);
    OPENSSL_cleanse(iv, sizeof iv);

    return Qnil;
}
Пример #16
0
/* generowanie kontekstu w oparciu o haslo */
long bmd_gen_sym_ctx_with_pass(long crypt_algo,long hash_algo,char *pass,long pass_len,
							   bmd_crypt_ctx_t **ctx)
{
long status;
char tmp_key[EVP_MAX_KEY_LENGTH];
char tmp_IV[EVP_MAX_IV_LENGTH];

	PRINT_INFO("LIBBMDPKIINF Generating symmetric ctx with pass\n");
	if(crypt_algo!=BMD_CRYPT_ALGO_DES3)		{	BMD_FOK(BMD_ERR_UNIMPLEMENTED);	}
	if(hash_algo!=BMD_HASH_ALGO_SHA1)		{	BMD_FOK(BMD_ERR_UNIMPLEMENTED);	}
	if(pass==NULL)					{	BMD_FOK(BMD_ERR_PARAM3);	}
	if(ctx==NULL)					{	BMD_FOK(BMD_ERR_PARAM5);	}
	if((*ctx)!=NULL)					{	BMD_FOK(BMD_ERR_PARAM5);	}

	status=EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_sha1(),NULL, (unsigned char*)pass,pass_len,500,(unsigned char*)tmp_key, (unsigned char*)tmp_IV);
	if( status < 0 )
	{
		PRINT_ERROR("LIBBMDPKIERR EVP_BytesToKey %li\n",status);
		return BMD_ERR_OP_FAILED;
	}
	BMD_FOK(bmd_create_ctx(ctx,BMD_CTX_SOURCE_NONE,BMD_CTX_TYPE_SYM));
	set_gen_buf2(tmp_key,status,&((*ctx)->sym->key));
	set_gen_buf2(tmp_IV,EVP_MAX_IV_LENGTH,&((*ctx)->sym->IV));
	memset(tmp_key,0,EVP_MAX_KEY_LENGTH);
	memset(tmp_IV,0,EVP_MAX_IV_LENGTH);

	return BMD_OK;
}
Пример #17
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;
}
Пример #18
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);
}
Пример #19
0
void crypto_get_key(const EVP_CIPHER *cipher, char *password, unsigned char *key,
                    unsigned char *iv) {
    /* if (PKCS5_PBKDF2_HMAC_SHA1(password, strlen(password), NULL, 0, 1000, 32, key) != 1) */
    /*     crypto_handle_error(); */

    if (EVP_BytesToKey(cipher, EVP_md5(), NULL, (unsigned char *)password, strlen(password), 1, key,
                       iv) == 0)
        crypto_handle_error();
}
Пример #20
0
size_t
crypt_initialize_ectx(byte* key_data, size_t key_length, EVP_CIPHER_CTX* ctx) {
    byte key[32], iv[32];
    EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), NULL, key_data, key_length,
                   10, key, iv);
    EVP_CIPHER_CTX_init(ctx);
    EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
    return 0;
}
Пример #21
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);
}
Пример #22
0
static int key_init(unsigned char *key_data, int key_data_len, EVP_CIPHER_CTX *ctx) {
    int i, nrounds = 10;
    unsigned char key[16], iv[16];
    i = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_md5(), NULL, key_data, key_data_len, nrounds, key, iv);
    printf("Key is %d bytes\n",i);
    EVP_CIPHER_CTX_init(ctx);
    EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);

    return 0;
}
Пример #23
0
BOOL CryptProtectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags)
{
	BYTE* pCipherText;
	int cbOut, cbFinal;
	BYTE randomKey[256];
	WINPR_PROTECTED_MEMORY_BLOCK* pMemBlock;

	if (dwFlags != CRYPTPROTECTMEMORY_SAME_PROCESS)
		return FALSE;

	if (!g_ProtectedMemoryBlocks)
		g_ProtectedMemoryBlocks = ListDictionary_New(TRUE);

	pMemBlock = (WINPR_PROTECTED_MEMORY_BLOCK*) malloc(sizeof(WINPR_PROTECTED_MEMORY_BLOCK));
	ZeroMemory(pMemBlock, sizeof(WINPR_PROTECTED_MEMORY_BLOCK));

	pMemBlock->pData = pData;
	pMemBlock->cbData = cbData;
	pMemBlock->dwFlags = dwFlags;

	/* AES Initialization */

	RAND_bytes(pMemBlock->salt, 8);
	RAND_bytes(randomKey, sizeof(randomKey));

	EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(),
			pMemBlock->salt,
			randomKey, sizeof(randomKey),
			4, pMemBlock->key, pMemBlock->iv);

	SecureZeroMemory(randomKey, sizeof(randomKey));

	EVP_CIPHER_CTX_init(&(pMemBlock->enc));
	EVP_EncryptInit_ex(&(pMemBlock->enc), EVP_aes_256_cbc(), NULL, pMemBlock->key, pMemBlock->iv);

	EVP_CIPHER_CTX_init(&(pMemBlock->dec));
	EVP_DecryptInit_ex(&(pMemBlock->dec), EVP_aes_256_cbc(), NULL, pMemBlock->key, pMemBlock->iv);

	/* AES Encryption */

	cbOut = pMemBlock->cbData + AES_BLOCK_SIZE - 1;
	pCipherText = (BYTE*) malloc(cbOut);

	EVP_EncryptInit_ex(&(pMemBlock->enc), NULL, NULL, NULL, NULL);
	EVP_EncryptUpdate(&(pMemBlock->enc), pCipherText, &cbOut, pMemBlock->pData, pMemBlock->cbData);
	EVP_EncryptFinal_ex(&(pMemBlock->enc), pCipherText + cbOut, &cbFinal);

	CopyMemory(pMemBlock->pData, pCipherText, pMemBlock->cbData);
	free(pCipherText);

	ListDictionary_Add(g_ProtectedMemoryBlocks, pData, pMemBlock);

	return TRUE;
}
Пример #24
0
static int
decrypt_token (CcnetProcessor *processor)
{
    USE_PRIV;
    int hex_len, encrypted_len, token_len; 
    char *encrypted_token = NULL;
    SeafileCrypt *crypt = NULL;
    unsigned char key[16], iv[16];
    char *token = NULL;
    int ret = 0;

    /* raw data is half the length of hexidecimal */
    hex_len = strlen(priv->token);
    if (hex_len % 2 != 0) {
        seaf_warning ("[check tx slave v3] invalid length of encrypted token\n"); 
        ret = -1;
        goto out;
    }

    encrypted_len = hex_len / 2;
    encrypted_token = g_malloc (encrypted_len);
    hex_to_rawdata (priv->token,
                    (unsigned char *)encrypted_token,
                    encrypted_len);

    EVP_BytesToKey (EVP_aes_128_cbc(), /* cipher mode */
                    EVP_sha1(),        /* message digest */
                    NULL,              /* slat */
                    (unsigned char*)priv->session_key,
                    strlen(priv->session_key),
                    1,   /* iteration times */
                    key, /* the derived key */
                    iv); /* IV, initial vector */

    crypt = seafile_crypt_new (1, key, iv);
    
    if (seafile_decrypt (&token, &token_len, encrypted_token,
                         encrypted_len, crypt) < 0) {
        seaf_warning ("[check tx slave v3] failed to decrypt token\n");
        ret = -1;
        goto out;
    }

    g_free (priv->token);
    /* we can use the decrypted data directly, since the trailing null byte is
     * also included when encrypting in the client */
    priv->token = token;

out:
    g_free (crypt);
    g_free (encrypted_token);
    
    return ret;
}
Пример #25
0
	int aes_init(const unsigned char *key_data, int key_data_len, unsigned char *ssalt, EVP_CIPHER_CTX *e_ctx)
	{
		unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
		if (EVP_BytesToKey(EVP_aes_128_cbc(), EVP_md5(), ssalt, key_data, key_data_len, 1, key, iv) != 16) {
			return -1;
		}
		
		EVP_CIPHER_CTX_init(e_ctx);
		EVP_EncryptInit_ex(e_ctx, EVP_aes_128_cbc(), NULL, key, iv);
		return 0;
	}
Пример #26
0
int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP_CIPHER_CTX *e_ctx, EVP_CIPHER_CTX *d_ctx)
{
	int i, nrounds = 5;
	unsigned char key[32], iv[32];
	i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
	if (i != 32) 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;
}
Пример #27
0
bool LoadGridKey(std::string gridkey, std::string salt)
{
    const char* chGridKey = gridkey.c_str();
    const char* chSalt = salt.c_str();
    OPENSSL_cleanse(chKeyGridcoin, sizeof(chKeyGridcoin));
    OPENSSL_cleanse(chIVGridcoin, sizeof(chIVGridcoin));
    EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(),(unsigned char *)chSalt,
        (unsigned char *)chGridKey,
        strlen(chGridKey), 1,
        chKeyGridcoin, chIVGridcoin);
    fKeySetGridcoin = true;
    return true;
}
	int crypt_ec_helper::decrypt(unsigned char* cipherText, int cipherTextLen, unsigned char *secret, int secretLength, unsigned char* plainText)
	{
		EVP_CIPHER_CTX *ctx;

		int len, plaintext_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("Decrypt: Failed to create cipher context.\n");

		/* Initialise the decryption 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_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
			throw std::runtime_error("Decrypt: Failed to initialize cipher.\n");

		plaintext_len = 0;

		/* Provide the message to be decrypted, and obtain the plaintext output.
		* EVP_DecryptUpdate can be called multiple times if necessary
		*/
		if (1 != EVP_DecryptUpdate(ctx, plainText, &len, cipherText, cipherTextLen))
			throw std::runtime_error("Decrypt: Failed to decrypt message.\n");

		plaintext_len += len;

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

		plaintext_len += len;

		/* Clean up */
		free(key);
		free(iv);
		EVP_CIPHER_CTX_free(ctx);

		return plaintext_len;
	}
Пример #29
0
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
                  pem_password_cb *callback, void *u)
{
    int i = 0, j, o, klen;
    long len;
    EVP_CIPHER_CTX *ctx;
    unsigned char key[EVP_MAX_KEY_LENGTH];
    char buf[PEM_BUFSIZE];

    len = *plen;

    if (cipher->cipher == NULL)
        return (1);
    if (callback == NULL)
        klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
    else
        klen = callback(buf, PEM_BUFSIZE, 0, u);
    if (klen <= 0) {
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
        return (0);
    }
#ifdef CHARSET_EBCDIC
    /* Convert the pass phrase from EBCDIC */
    ebcdic2ascii(buf, buf, klen);
#endif

    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
                        (unsigned char *)buf, klen, 1, key, NULL))
        return 0;

    j = (int)len;
    ctx = EVP_CIPHER_CTX_new();
    if (ctx == NULL)
        return 0;
    o = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
    if (o)
        o = EVP_DecryptUpdate(ctx, data, &i, data, j);
    if (o)
        o = EVP_DecryptFinal_ex(ctx, &(data[i]), &j);
    EVP_CIPHER_CTX_free(ctx);
    OPENSSL_cleanse((char *)buf, sizeof(buf));
    OPENSSL_cleanse((char *)key, sizeof(key));
    if (o)
        j += i;
    else {
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
        return (0);
    }
    *plen = j;
    return (1);
}
Пример #30
0
int do_crypt(FILE *in, FILE *out, int do_encrypt, unsigned char *key_data,
		int key_data_len, unsigned char *salt) {
	/* Allow enough space in output buffer for additional block */
	int i, nrounds = 2;
	unsigned char key[16], iv[16];
	unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
	memset(inbuf, 0, 1024);
	int inlen, outlen;
	EVP_CIPHER_CTX ctx;
	/* Bogus key and IV: we'd normally set these from
	 * another source.
	 */
	i = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha1(), salt, key_data,
			key_data_len, nrounds, key, iv);
	if (i != 16) {
		printf("Key size is %d bits - should be 256 bits\n", i);
		return -1;
	}
	/* Don't set key or IV right away; we want to check lengths */
	EVP_CIPHER_CTX_init(&ctx);
	EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, NULL, NULL, do_encrypt);
	OPENSSL_assert(EVP_CIPHER_CTX_key_length(&ctx) == 16);
	OPENSSL_assert(EVP_CIPHER_CTX_iv_length(&ctx) == 16);
	/* Now we can set key and IV */
	EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, do_encrypt);
	for (;;) {
		inlen = fread(inbuf, 1, 1024, in);
		if (inlen <= 0)
			break;
		memset(outbuf, 0, 1024 + EVP_MAX_BLOCK_LENGTH);
		if (!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) {
			/* Error */
			EVP_CIPHER_CTX_cleanup(&ctx);
			return 0;
		}
		fwrite(outbuf, 1, outlen, out);
		memset(inbuf, 0, 1024);
	}
	if (!EVP_CipherFinal_ex(&ctx, outbuf, &outlen)) {
		/* Error */
		EVP_CIPHER_CTX_cleanup(&ctx);
		fclose(in);
		fclose(out);
		invalid_token();
	}
	fwrite(outbuf, 1, outlen, out);
	EVP_CIPHER_CTX_cleanup(&ctx);
	fclose(in);
	fclose(out);
	return 1;
}