示例#1
0
Aes256::Aes256(BinData key):
  key_( std::move(key) ),
  iv_( generateRandomData( ivSize() ) ),
  td_(MCRYPT_RIJNDAEL_256, MCRYPT_CFB)
{
  if( key_.size()!=iv_.size() )
    throw std::runtime_error("key and IV size differ");

  assert( static_cast<size_t>(mcrypt_enc_get_key_size(td_.get()))==keySize() );
  assert( static_cast<size_t>(mcrypt_enc_get_iv_size(td_.get())) ==ivSize()  );

  int ret;
  if( (ret = mcrypt_generic_init(td_.get(), key_.data(), key_.size(), iv_.data())) < 0 )
    throw std::runtime_error( (Util::ErrStrm{}<<"mcrypt_generic_init(): "<<mcrypt_strerror(ret)).str().c_str() );
}
示例#2
0
void CipherKeyImpl::generateKey()
{
	ByteVec vec;

	getRandomBytes(vec, keySize());
	setKey(vec);
	
	getRandomBytes(vec, ivSize());
	setIV(vec);
}
示例#3
0
void CipherKeyImpl::generateKey(
	const std::string& password,
	const std::string& salt,
	int iterationCount)
{
	unsigned char keyBytes[EVP_MAX_KEY_LENGTH];
	unsigned char ivBytes[EVP_MAX_IV_LENGTH];

	// OpenSSL documentation specifies that the salt must be an 8-byte array.
	unsigned char saltBytes[8];

	if (!salt.empty())
	{
		int len = static_cast<int>(salt.size());
		// Create the salt array from the salt string
		for (int i = 0; i < 8; ++i)
			saltBytes[i] = salt.at(i % len);
		for (int i = 8; i < len; ++i)
			saltBytes[i % 8] ^= salt.at(i);
	}

	// Now create the key and IV, using the MD5 digest algorithm.
	int keySize = EVP_BytesToKey(
		_pCipher,
		EVP_md5(),
		(salt.empty() ? 0 : saltBytes),
		reinterpret_cast<const unsigned char*>(password.data()),
		static_cast<int>(password.size()),
		iterationCount,
		keyBytes,
		ivBytes);

	// Copy the buffers to our member byte vectors.
	_key.assign(keyBytes, keyBytes + keySize);

	if (ivSize() == 0)
		_iv.clear();
	else
		_iv.assign(ivBytes, ivBytes + ivSize());
}
示例#4
0
CipherKeyImpl::CipherKeyImpl(const std::string& name):
	_pCipher(0),
	_name(name),
	_key(),
	_iv()
{
	// dummy access to Cipherfactory so that the EVP lib is initilaized
	CipherFactory::defaultFactory();
	_pCipher = EVP_get_cipherbyname(name.c_str());

	if (!_pCipher)
		throw Poco::NotFoundException("Cipher " + name + " was not found");
	_key = ByteVec(keySize());
	_iv = ByteVec(ivSize());
	generateKey();
}