Update POCO library.

This commit is contained in:
Sandu Liviu Catalin committed 2023-03-23 20:19:11 +02:00
1 parent 8d15f4b6e9
commit 233fc103f9
2521 files changed
+257092 -72789

No files matched your search

+12 -8
View File
@@ -39,30 +39,32 @@ Cipher::~Cipher()
}
std::string Cipher::encryptString(const std::string& str, Encoding encoding)
std::string Cipher::encryptString(const std::string& str, Encoding encoding, bool padding)
{
std::istringstream source(str);
std::ostringstream sink;
encrypt(source, sink, encoding);
encrypt(source, sink, encoding, padding);
return sink.str();
}
std::string Cipher::decryptString(const std::string& str, Encoding encoding)
std::string Cipher::decryptString(const std::string& str, Encoding encoding, bool padding)
{
std::istringstream source(str);
std::ostringstream sink;
decrypt(source, sink, encoding);
decrypt(source, sink, encoding, padding);
return sink.str();
}
void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding)
void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding, bool padding)
{
CryptoInputStream encryptor(source, createEncryptor());
CryptoTransform::Ptr p = createEncryptor();
if (!padding) p->setPadding(0);
CryptoInputStream encryptor(source, p);
switch (encoding)
{
@@ -102,9 +104,11 @@ void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding
}
void Cipher::decrypt(std::istream& source, std::ostream& sink, Encoding encoding)
void Cipher::decrypt(std::istream& source, std::ostream& sink, Encoding encoding, bool padding)
{
CryptoOutputStream decryptor(sink, createDecryptor());
CryptoTransform::Ptr p = createDecryptor();
if (!padding) p->setPadding(0);
CryptoOutputStream decryptor(sink, p);
switch (encoding)
{
+14
View File
@@ -18,10 +18,14 @@
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/CipherImpl.h"
#include "Poco/Crypto/RSACipherImpl.h"
#include "Poco/Crypto/EVPCipherImpl.h"
#include "Poco/Exception.h"
#include "Poco/SingletonHolder.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/provider.h>
#endif
namespace Poco {
@@ -30,6 +34,10 @@ namespace Crypto {
CipherFactory::CipherFactory()
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
OSSL_PROVIDER_load(NULL, "default");
OSSL_PROVIDER_load(NULL, "legacy");
#endif
}
@@ -62,4 +70,10 @@ Cipher* CipherFactory::createCipher(const RSAKey& key, RSAPaddingMode paddingMod
}
Cipher* CipherFactory::createCipher(const EVPPKey& key)
{
return new EVPCipherImpl(key);
}
} } // namespace Poco::Crypto
+4 -2
View File
@@ -98,20 +98,22 @@ namespace
{
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
_pContext = EVP_CIPHER_CTX_new();
EVP_CipherInit(
if (!_pContext) throwError();
int rc = EVP_CipherInit(
_pContext,
_pCipher,
&_key[0],
_iv.empty() ? 0 : &_iv[0],
(dir == DIR_ENCRYPT) ? 1 : 0);
#else
EVP_CipherInit(
int rc = EVP_CipherInit(
&_context,
_pCipher,
&_key[0],
_iv.empty() ? 0 : &_iv[0],
(dir == DIR_ENCRYPT) ? 1 : 0);
#endif
if (rc == 0) throwError();
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
if (_iv.size() != EVP_CIPHER_iv_length(_pCipher) && EVP_CIPHER_mode(_pCipher) == EVP_CIPH_GCM_MODE)
+21
View File
@@ -21,6 +21,25 @@
#include <openssl/evp.h>
namespace
{
void throwError()
{
unsigned long err;
std::string msg;
while ((err = ERR_get_error()))
{
if (!msg.empty())
msg.append("; ");
msg.append(ERR_error_string(err, 0));
}
throw Poco::IOException(msg);
}
}
namespace Poco {
namespace Crypto {
@@ -186,6 +205,8 @@ void CipherKeyImpl::generateKey(
keyBytes,
ivBytes);
if (!keySize) throwError();
// Copy the buffers to our member byte vectors.
_key.assign(keyBytes, keyBytes + keySize);
+1 -1
View File
@@ -28,7 +28,7 @@ CryptoTransform::~CryptoTransform()
{
}
int CryptoTransform::setPadding(int padding)
{
return 1;
+6 -2
View File
@@ -26,10 +26,10 @@ DigestEngine::DigestEngine(const std::string& name):
{
const EVP_MD* md = EVP_get_digestbyname(_name.c_str());
if (!md) throw Poco::NotFoundException(_name);
EVP_DigestInit_ex(_pContext, md, NULL);
EVP_DigestInit_ex(_pContext, md, NULL);
}
DigestEngine::~DigestEngine()
{
EVP_MD_CTX_destroy(_pContext);
@@ -37,7 +37,11 @@ DigestEngine::~DigestEngine()
int DigestEngine::nid() const
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
return EVP_MD_nid(EVP_MD_CTX_get0_md(_pContext));
#else
return EVP_MD_nid(EVP_MD_CTX_md(_pContext));
#endif
}
std::size_t DigestEngine::digestLength() const
+2 -4
View File
@@ -21,9 +21,7 @@
#include "Poco/StreamCopier.h"
#include <sstream>
#include <openssl/evp.h>
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
#include <openssl/bn.h>
#endif
namespace Poco {
@@ -78,8 +76,8 @@ ECKeyImpl::ECKeyImpl(int curve):
}
ECKeyImpl::ECKeyImpl(const std::string& publicKeyFile,
const std::string& privateKeyFile,
ECKeyImpl::ECKeyImpl(const std::string& publicKeyFile,
const std::string& privateKeyFile,
const std::string& privateKeyPassphrase): KeyPairImpl("ec", KT_EC_IMPL), _pEC(0)
{
if (EVPPKey::loadKey(&_pEC, PEM_read_PrivateKey, EVP_PKEY_get1_EC_KEY, privateKeyFile, privateKeyPassphrase))
+310
View File
@@ -0,0 +1,310 @@
//
// EVPCipherImpl.cpp
//
// Library: Crypto
// Package: EVP
// Module: EVPCipherImpl
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Crypto/EVPCipherImpl.h"
#include "Poco/Crypto/CryptoTransform.h"
#include "Poco/Exception.h"
#include "Poco/Logger.h"
#include <openssl/err.h>
#include <openssl/evp.h>
#include <cstring>
namespace Poco {
namespace Crypto {
namespace
{
void throwError(std::string&& msg)
{
unsigned long err;
while ((err = ERR_get_error()))
{
if (!msg.empty()) msg.append("; ");
msg.append(ERR_error_string(err, 0));
}
throw Poco::IOException(msg);
}
class EVPPKeyContext
{
public:
EVPPKeyContext() = delete;
EVPPKeyContext(const EVP_PKEY* pEVP) : _pCtx(EVP_PKEY_CTX_new(const_cast<EVP_PKEY*>(pEVP), NULL))
{
if (!_pCtx)
{
std::string fmt = "EVPPKeyContext():%s()";
throwError(Poco::format(fmt, std::string("EVP_PKEY_CTX_new")));
}
}
~EVPPKeyContext()
{
EVP_PKEY_CTX_free(_pCtx);
}
operator EVP_PKEY_CTX*()
{
return _pCtx;
}
private:
EVP_PKEY_CTX* _pCtx = nullptr;
};
class EVPEncryptImpl: public CryptoTransform
{
public:
EVPEncryptImpl(const EVP_PKEY* pEVP):
_pEVP(pEVP),
_pCtx(_pEVP),
_pos(0),
_pBuf(0)
{
std::string fmt = "EVPEncryptImpl():%s()";
poco_check_ptr(_pEVP);
if (!_pCtx)
throwError(Poco::format(fmt, std::string("EVP_PKEY_CTX_new")));
if (EVP_PKEY_encrypt_init(_pCtx) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt_init")));
_blockSize = EVP_PKEY_size(const_cast<EVP_PKEY*>(_pEVP));
if (!_blockSize)
throwError(Poco::format(fmt, std::string("EVP_PKEY_size")));
_pBuf = new unsigned char[_blockSize];
}
~EVPEncryptImpl()
{
delete [] _pBuf;
}
std::size_t blockSize() const
{
return _blockSize;
}
std::string getTag(std::size_t)
{
return "";
}
void setTag(const std::string&)
{
}
std::streamsize transform(const unsigned char* input, std::streamsize inputLength,
unsigned char* output, std::streamsize outputLength)
{
std::string fmt = "EVPEncryptImpl::transform():%s()";
std::streamsize maxSize = static_cast<std::streamsize>(maxDataSize(input, inputLength));
std::streamsize evpSize = static_cast<std::streamsize>(_blockSize);
poco_assert_dbg(_pos <= maxSize);
poco_assert (outputLength >= evpSize);
int rc = 0;
while (inputLength > 0)
{
poco_assert_dbg (maxSize >= _pos);
std::streamsize missing = maxSize - _pos;
if (missing == 0)
{
poco_assert (outputLength >= evpSize);
std::size_t outLen;
if (EVP_PKEY_encrypt(_pCtx, NULL, &outLen, _pBuf, static_cast<std::size_t>(maxSize)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt(NULL)")));
if (EVP_PKEY_encrypt(_pCtx, output, &outLen, _pBuf, static_cast<std::size_t>(maxSize)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt")));
rc += static_cast<int>(outLen);
output += outLen;
outputLength -= outLen;
_pos = 0;
}
else
{
if (missing > inputLength) missing = inputLength;
std::memcpy(_pBuf + _pos, input, static_cast<std::size_t>(missing));
input += missing;
_pos += missing;
inputLength -= missing;
}
}
return rc;
}
std::streamsize finalize(unsigned char* output, std::streamsize length)
{
poco_assert (length >= blockSize());
poco_assert (_pos <= maxDataSize(output, length));
std::string fmt = "EVPEncryptImpl::finalize():%s()";
std::size_t outLen = 0;
if (_pos > 0)
{
if (EVP_PKEY_encrypt(_pCtx, NULL, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt")));
if (EVP_PKEY_encrypt(_pCtx, output, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt")));
}
return static_cast<std::streamsize>(outLen);
}
private:
std::size_t maxDataSize(const unsigned char* pIO, std::streamsize length)
{
std::string fmt = "EVPEncryptImpl::maxDataSize():%s()";
std::size_t outLength = 0;
if (EVP_PKEY_encrypt(_pCtx, NULL, &outLength, pIO, length) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_encrypt")));
return outLength;
}
const EVP_PKEY* _pEVP;
EVPPKeyContext _pCtx;
int _blockSize;
std::streamsize _pos;
unsigned char* _pBuf;
};
class EVPDecryptImpl: public CryptoTransform
{
public:
EVPDecryptImpl(const EVP_PKEY* pEVP):
_pEVP(pEVP),
_pCtx(_pEVP),
_pos(0),
_pBuf(0)
{
std::string fmt = "EVPDecryptImpl():%s()";
poco_check_ptr(_pEVP);
if (EVP_PKEY_decrypt_init(_pCtx) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_decrypt_init")));
_blockSize = EVP_PKEY_size(const_cast<EVP_PKEY*>(_pEVP));
if (!_blockSize)
throwError(Poco::format(fmt, std::string("EVP_PKEY_size")));
_pBuf = new unsigned char[_blockSize];
}
~EVPDecryptImpl()
{
delete [] _pBuf;
}
std::size_t blockSize() const
{
return _blockSize;
}
std::string getTag(std::size_t)
{
return "";
}
void setTag(const std::string&)
{
}
std::streamsize transform(const unsigned char* input, std::streamsize inputLength,
unsigned char* output, std::streamsize outputLength)
{
std::string fmt = "EVPDecryptImpl::transform():%s()";
std::streamsize evpSize = static_cast<std::streamsize>(_blockSize);
poco_assert_dbg(_pos <= evpSize);
poco_assert (outputLength >= evpSize);
int rc = 0;
while (inputLength > 0)
{
poco_assert_dbg (evpSize >= _pos);
std::streamsize missing = evpSize - _pos;
if (missing == 0)
{
std::size_t outLen = 0;
if (EVP_PKEY_decrypt(_pCtx, NULL, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_decrypt(NULL)")));
if (EVP_PKEY_decrypt(_pCtx, output, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_decrypt")));
rc += static_cast<int>(outLen);
output += outLen;
outputLength -= outLen;
_pos = 0;
}
else
{
if (missing > inputLength) missing = inputLength;
std::memcpy(_pBuf + _pos, input, static_cast<std::size_t>(missing));
input += missing;
_pos += missing;
inputLength -= missing;
}
}
return rc;
}
std::streamsize finalize(unsigned char* output, std::streamsize length)
{
poco_assert (length >= _blockSize);
std::string fmt = "EVPDecryptImpl::finalize():%s()";
std::size_t outLen = 0;
if (EVP_PKEY_decrypt(_pCtx, NULL, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_decrypt(NULL)")));
poco_assert (length >= outLen);
if (_pos > 0)
{
if (EVP_PKEY_decrypt(_pCtx, output, &outLen, _pBuf, static_cast<std::size_t>(_pos)) <= 0)
throwError(Poco::format(fmt, std::string("EVP_PKEY_decrypt")));
}
return outLen;
}
private:
const EVP_PKEY* _pEVP;
EVPPKeyContext _pCtx;
int _blockSize;
std::streamsize _pos;
unsigned char* _pBuf;
};
}
EVPCipherImpl::EVPCipherImpl(const EVPPKey& key):
_key(key)
{
}
EVPCipherImpl::~EVPCipherImpl()
{
}
CryptoTransform::Ptr EVPCipherImpl::createEncryptor()
{
return new EVPEncryptImpl(_key);
}
CryptoTransform::Ptr EVPCipherImpl::createDecryptor()
{
return new EVPDecryptImpl(_key);
}
} } // namespace Poco::Crypto
+215 -18
View File
@@ -14,19 +14,33 @@
#include "Poco/Crypto/EVPPKey.h"
#include "Poco/Crypto/PKCS12Container.h"
#include "Poco/Crypto/X509Certificate.h"
#include "Poco/Crypto/ECKey.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/NumberFormatter.h"
#include <iostream>
namespace Poco {
namespace Crypto {
const std::map<int, std::string> EVPPKey::KNOWN_TYPES =
{
{ EVP_PKEY_RSA, "rsa" },
// not implemented
//{ EVP_PKEY_DSA, "dsa" },
//{ EVP_PKEY_DH, "dh" },
{ EVP_PKEY_EC, "ec" }
};
EVPPKey::EVPPKey(const std::string& ecCurveName): _pEVPPKey(0)
{
newECKey(ecCurveName.c_str());
poco_check_ptr(_pEVPPKey);
checkType();
}
@@ -34,13 +48,93 @@ EVPPKey::EVPPKey(const char* ecCurveName): _pEVPPKey(0)
{
newECKey(ecCurveName);
poco_check_ptr(_pEVPPKey);
checkType();
}
EVPPKey::EVPPKey(const X509Certificate& cert):
_pEVPPKey(X509_get_pubkey(const_cast<X509*>(cert.certificate())))
{
poco_check_ptr(_pEVPPKey);
checkType();
}
EVPPKey::EVPPKey(const PKCS12Container& cont): EVPPKey(cont.getKey())
{
poco_check_ptr(_pEVPPKey);
checkType();
}
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
EVPPKey::EVPPKey(int type, int param): _pEVPPKey(0)
{
EVP_PKEY_CTX *pCtx = EVP_PKEY_CTX_new_id(type, NULL);
if (NULL == pCtx)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_CTX_new_id()\n", type, param);
throw OpenSSLException(getError(msg));
}
int ret = EVP_PKEY_keygen_init(pCtx);
if (ret != 1)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_keygen_init()\n", type, param);
throw OpenSSLException(getError(msg));
}
if (EVP_PKEY_RSA == type)
{
ret = EVP_PKEY_CTX_set_rsa_keygen_bits(pCtx, param);
if (ret != 1)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_CTX_set_rsa_keygen_bits()\n", type, param);
throw OpenSSLException(getError(msg));
}
}
else if (EVP_PKEY_EC == type)
{
ret = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pCtx, param);
if (ret != 1)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_CTX_set_ec_paramgen_curve_nid()\n", type, param);
throw OpenSSLException(getError(msg));
}
}
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
ret = EVP_PKEY_generate(pCtx, &_pEVPPKey);
if (ret != 1)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_generate()\n", type, param);
throw OpenSSLException(getError(msg));
}
#else
ret = EVP_PKEY_keygen(pCtx, &_pEVPPKey);
if (ret != 1)
{
std::string msg = Poco::format(
"EVPPKey(%d, %d):EVP_PKEY_keygen()\n", type, param);
throw OpenSSLException(getError(msg));
}
#endif
EVP_PKEY_CTX_free(pCtx);
checkType();
}
#endif // OPENSSL_VERSION_NUMBER >= 0x10000000L
EVPPKey::EVPPKey(EVP_PKEY* pEVPPKey): _pEVPPKey(0)
{
duplicate(pEVPPKey, &_pEVPPKey);
poco_check_ptr(_pEVPPKey);
checkType();
}
@@ -57,9 +151,11 @@ EVPPKey::EVPPKey(const std::string& publicKeyFile,
// no private key, this must be public key only, otherwise throw
if (!loadKey(&_pEVPPKey, PEM_read_PUBKEY, (EVP_PKEY_get_Key_fn)0, publicKeyFile))
{
throw OpenSSLException("ECKeyImpl(const string&, const string&, const string&");
std::string msg = "EVPPKey(const string&, const string&, const string&)\n";
throw OpenSSLException(getError(msg));
}
poco_check_ptr(_pEVPPKey);
checkType();
}
@@ -76,9 +172,11 @@ EVPPKey::EVPPKey(std::istream* pPublicKeyStream,
// no private key, this must be public key only, otherwise throw
if (!loadKey(&_pEVPPKey, PEM_read_bio_PUBKEY, (EVP_PKEY_get_Key_fn)0, pPublicKeyStream))
{
throw OpenSSLException("ECKeyImpl(istream*, istream*, const string&");
std::string msg = "EVPPKey(istream* ,istream* const string&)\n";
throw OpenSSLException(getError(msg));
}
poco_check_ptr(_pEVPPKey);
checkType();
}
@@ -86,6 +184,7 @@ EVPPKey::EVPPKey(const EVPPKey& other)
{
duplicate(other._pEVPPKey, &_pEVPPKey);
poco_check_ptr(_pEVPPKey);
checkType();
}
@@ -93,6 +192,7 @@ EVPPKey::EVPPKey(EVPPKey&& other) noexcept:
_pEVPPKey(other._pEVPPKey)
{
other._pEVPPKey = nullptr;
checkType();
}
@@ -100,6 +200,7 @@ EVPPKey& EVPPKey::operator = (const EVPPKey& other)
{
duplicate(other._pEVPPKey, &_pEVPPKey);
poco_check_ptr(_pEVPPKey);
checkType();
return *this;
}
@@ -108,6 +209,7 @@ EVPPKey& EVPPKey::operator = (EVPPKey&& other) noexcept
{
_pEVPPKey = other._pEVPPKey;
other._pEVPPKey = nullptr;
checkType();
return *this;
}
@@ -118,19 +220,68 @@ EVPPKey::~EVPPKey()
}
const std::string& EVPPKey::name() const
{
int t = type(_pEVPPKey);
auto it = KNOWN_TYPES.find(t);
if (it == KNOWN_TYPES.end())
throw Poco::NotImplementedException(Poco::format("EVPPKey::type(%d)", t));
return it->second;
}
void EVPPKey::checkType()
{
if (_pEVPPKey)
{
int t = type(_pEVPPKey);
if (KNOWN_TYPES.find(t) == KNOWN_TYPES.end())
throw Poco::NotImplementedException(Poco::format("EVPPKey::type(%d)", t));
}
}
void EVPPKey::setKey(EC_KEY* pKey)
{
if (!EVP_PKEY_set1_EC_KEY(_pEVPPKey, pKey))
{
std::string msg = "EVPPKey::setKey('EC')\n";
throw OpenSSLException(getError(msg));
}
}
void EVPPKey::setKey(RSA* pKey)
{
if (!EVP_PKEY_set1_RSA(_pEVPPKey, pKey))
{
std::string msg = "EVPPKey::setKey('RSA')\n";
throw OpenSSLException(getError(msg));
}
}
void EVPPKey::save(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase) const
{
if (!publicKeyFile.empty() && (publicKeyFile != privateKeyFile))
{
BIO* bio = BIO_new(BIO_s_file());
if (!bio) throw Poco::IOException("Cannot create BIO for writing public key file", publicKeyFile);
if (!bio)
{
std::string msg = Poco::format(
"EVPPKey::save(%s) Cannot create BIO for writing public key file\n", publicKeyFile);
throw Poco::IOException(getError(msg));
}
try
{
if (BIO_write_filename(bio, const_cast<char*>(publicKeyFile.c_str())))
{
if (!PEM_write_bio_PUBKEY(bio, _pEVPPKey))
{
throw Poco::WriteFileException("Failed to write public key to file", publicKeyFile);
std::string msg = Poco::format("EVPPKey::save('%s', '%s', '%s')\n",
publicKeyFile, privateKeyFile, privateKeyPassphrase);
msg.append(Poco::format("Failed to write public key '%s' to file", publicKeyFile));
throw Poco::WriteFileException(getError(msg));
}
}
else throw Poco::CreateFileException("Cannot create public key file");
@@ -146,7 +297,12 @@ void EVPPKey::save(const std::string& publicKeyFile, const std::string& privateK
if (!privateKeyFile.empty())
{
BIO* bio = BIO_new(BIO_s_file());
if (!bio) throw Poco::IOException("Cannot create BIO for writing private key file", privateKeyFile);
if (!bio)
{
std::string msg = Poco::format(
"EVPPKey::save(%s): Cannot create BIO for writing private key file\n", privateKeyFile);
throw Poco::IOException(getError(msg));
}
try
{
if (BIO_write_filename(bio, const_cast<char*>(privateKeyFile.c_str())))
@@ -163,9 +319,18 @@ void EVPPKey::save(const std::string& publicKeyFile, const std::string& privateK
static_cast<int>(privateKeyPassphrase.length()), 0, 0);
}
if (!rc)
throw Poco::FileException("Failed to write private key to file", privateKeyFile);
{
std::string msg = Poco::format(
"EVPPKey::save(%s):PEM_write_bio_PrivateKey()\n", privateKeyFile);
throw Poco::FileException(getError(msg));
}
}
else
{
std::string msg = Poco::format(
"EVPPKey::save(%s):BIO_write_filename()\n", privateKeyFile);
throw Poco::CreateFileException(getError(msg));
}
else throw Poco::CreateFileException("Cannot create private key file", privateKeyFile);
}
catch (...)
{
@@ -182,11 +347,18 @@ void EVPPKey::save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStre
if (pPublicKeyStream && (pPublicKeyStream != pPrivateKeyStream))
{
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) throw Poco::IOException("Cannot create BIO for writing public key");
if (!bio)
{
std::string msg = "EVPPKey::save(ostream*, ostream*, const string&)\n";
msg.append("Cannot create BIO for writing public key");
throw Poco::IOException(getError(msg));
}
if (!PEM_write_bio_PUBKEY(bio, _pEVPPKey))
{
std::string msg = "EVPPKey::save(ostream*, ostream*, const string&)\n";
msg.append("Failed to write public key to stream");
BIO_free(bio);
throw Poco::WriteFileException("Failed to write public key to stream");
throw Poco::WriteFileException(getError(msg));
}
char* pData;
long size = BIO_get_mem_data(bio, &pData);
@@ -197,7 +369,12 @@ void EVPPKey::save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStre
if (pPrivateKeyStream)
{
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) throw Poco::IOException("Cannot create BIO for writing public key");
if (!bio)
{
std::string msg = "EVPPKey::save(ostream*, ostream*, const string&)\n";
msg.append("Cannot create BIO for writing private key");
throw Poco::IOException(getError(msg));
}
int rc = 0;
if (privateKeyPassphrase.empty())
rc = PEM_write_bio_PrivateKey(bio, _pEVPPKey, 0, 0, 0, 0, 0);
@@ -207,8 +384,10 @@ void EVPPKey::save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStre
static_cast<int>(privateKeyPassphrase.length()), 0, 0);
if (!rc)
{
std::string msg = "EVPPKey::save(ostream*, ostream*, const string&)\n";
msg.append("Failed to write private key to stream");
BIO_free(bio);
throw Poco::FileException("Failed to write private key to stream");
throw Poco::FileException(getError(msg));
}
char* pData;
long size = BIO_get_mem_data(bio, &pData);
@@ -224,8 +403,11 @@ EVP_PKEY* EVPPKey::duplicate(const EVP_PKEY* pFromKey, EVP_PKEY** pToKey)
"provided key pointer is null.");
*pToKey = EVP_PKEY_new();
if (!*pToKey) throw NullPointerException("EVPPKey::duplicate(): "
"EVP_PKEY_new() returned null.");
if (!*pToKey)
{
std::string msg = "EVPPKey::duplicate():EVP_PKEY_new()\n";
throw NullPointerException(getError(msg));
}
int keyType = type(pFromKey);
switch (keyType)
@@ -238,7 +420,11 @@ EVP_PKEY* EVPPKey::duplicate(const EVP_PKEY* pFromKey, EVP_PKEY** pToKey)
EVP_PKEY_set1_RSA(*pToKey, pRSA);
RSA_free(pRSA);
}
else throw OpenSSLException("EVPPKey::duplicate(): EVP_PKEY_get1_RSA()");
else
{
std::string msg = "EVPPKey::duplicate():EVP_PKEY_get1_RSA()\n";
throw OpenSSLException(getError(msg));
}
break;
}
case EVP_PKEY_EC:
@@ -250,14 +436,24 @@ EVP_PKEY* EVPPKey::duplicate(const EVP_PKEY* pFromKey, EVP_PKEY** pToKey)
EC_KEY_free(pEC);
int cmp = EVP_PKEY_cmp_parameters(*pToKey, pFromKey);
if (cmp < 0)
throw OpenSSLException("EVPPKey::duplicate(): EVP_PKEY_cmp_parameters()");
{
std::string msg = "EVPPKey::duplicate():EVP_PKEY_cmp_parameters()\n";
throw OpenSSLException(getError(msg));
}
if (0 == cmp)
{
if(!EVP_PKEY_copy_parameters(*pToKey, pFromKey))
throw OpenSSLException("EVPPKey::duplicate(): EVP_PKEY_copy_parameters()");
{
std::string msg = "EVPPKey::duplicate():EVP_PKEY_copy_parameters()\n";
throw OpenSSLException(getError(msg));
}
}
}
else throw OpenSSLException();
else
{
std::string msg = "EVPPKey::duplicate():EVP_PKEY_get1_EC_KEY()\n";
throw OpenSSLException(getError(msg));
}
break;
}
default:
@@ -281,7 +477,8 @@ void EVPPKey::newECKey(const char* ecCurveName)
EC_KEY_free(pEC);
return;
err:
throw OpenSSLException("EVPPKey:newECKey()");
std::string msg = "EVPPKey::newECKey()\n";
throw OpenSSLException(getError(msg));
}
+168
View File
@@ -0,0 +1,168 @@
//
// Envelope.cpp
//
// Library: Crypto
// Package: Envelope
// Module: Envelope
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Crypto/Envelope.h"
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
#if !defined(EVP_CIPHER_CTX_init)
#define EVP_CIPHER_CTX_init(a)
#endif
#endif
namespace Poco {
namespace Crypto {
Envelope::Envelope(int cipherNID): _pCipher(EVP_get_cipherbynid(cipherNID)),
_pCtx(EVP_CIPHER_CTX_new())
{
poco_check_ptr(_pCipher);
poco_check_ptr(_pCtx);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (1 != EVP_CIPHER_CTX_init(_pCtx))
handleErrors(std::string("Envelope():EVP_CIPHER_CTX_init()"));
#else
EVP_CIPHER_CTX_init(_pCtx);
#endif
_iv.resize(ivSize(), 0);
}
Envelope::Envelope(const EVPPKey& key, int cipherNID):
Envelope(cipherNID)
{
addKey(key);
}
Envelope::Envelope(const EVPPKeyVec& keys, int cipherNID):
Envelope(cipherNID)
{
for (const auto& k : keys) addKey(k);
}
Envelope::~Envelope()
{
for (auto& pK : _pubKeys)
EVP_PKEY_free(pK);
EVP_CIPHER_CTX_free(_pCtx);
}
void Envelope::addKey(const EVPPKey& key)
{
EVP_PKEY* pKey;
_pubKeys.push_back(EVPPKey::duplicate((const EVP_PKEY*)key, &pKey));
_encKeys.emplace_back(EVP_PKEY_size(_pubKeys.back()));
}
const Envelope::ByteVec& Envelope::seal(const ByteVec& plainData)
{
std::vector<Byte*> pEncKeys(_encKeys.size(), 0);
std::vector<int> encKeysSizes(_encKeys.size(), 0);
int i = 0;
for (const auto& k : _encKeys)
pEncKeys[i++] = new Byte[k.size()];
int noOfKeys = static_cast<int>(_pubKeys.size());
if (_encKeys.size() != EVP_SealInit(_pCtx, _pCipher, &pEncKeys[0], &encKeysSizes[0], &_iv[0], &_pubKeys[0], noOfKeys))
{
i = 0;
for (; i < _encKeys.size(); ++i) delete [] pEncKeys[i];
handleErrors(std::string("Envelope::seal():EVP_SealInit()"));
}
i = 0;
for (auto& k : _encKeys)
{
if (encKeysSizes[i] != k.size())
k.resize(encKeysSizes[i]);
std::memcpy(&k[0], pEncKeys[i], encKeysSizes[i]);
++i;
}
i = 0;
for (; i < _encKeys.size(); ++i) delete [] pEncKeys[i];
int cipherTextLen = 0, len = 0;
int plainDataSize = static_cast<int>(plainData.size());
_encContent.resize(plainDataSize + blockSize());
if (1 != EVP_SealUpdate(_pCtx, &_encContent[0], &len, &plainData[0], plainDataSize))
handleErrors(std::string("Envelope::seal():EVP_SealUpdate()"));
cipherTextLen = len;
poco_assert (cipherTextLen < _encContent.size());
if(1 != EVP_SealFinal(_pCtx, &_encContent[len], &len))
handleErrors(std::string("Envelope::seal():EVP_SealFinal()"));
cipherTextLen += len;
poco_assert (cipherTextLen <= _encContent.size());
_encContent.resize(cipherTextLen);
return _encContent;
}
const Envelope::ByteVec& Envelope::seal(const std::string& plainText)
{
return seal(ByteVec(plainText.begin(), plainText.end()));
}
Envelope::ByteVec Envelope::open(const EVPPKey& privKey, const ByteVec& encKey, const ByteVec& iv)
{
if (iv.size() > 0) _iv = iv;
int encContentLen = static_cast<int>(_encContent.size());
int blockSz = blockSize();
int mod = encContentLen % blockSz;
if (mod || (encContentLen < blockSz))
{
throw Poco::InvalidArgumentException(
Poco::format("Envelope::open(): bad encrypted buffer size: %z (must be N x %d)",
_encContent.size(), blockSz));
}
int encKeyLen = static_cast<int>(encKey.size());
EVP_PKEY* pKey = const_cast<EVP_PKEY*>((const EVP_PKEY*)privKey);
if (1 != EVP_OpenInit(_pCtx, _pCipher, &encKey[0], encKeyLen, &_iv[0], pKey))
handleErrors(std::string("Envelope::open():EVP_OpenInit()"));
ByteVec plainData(_encContent.size()+blockSz, 0);
int len = 0;
if(1 != EVP_OpenUpdate(_pCtx, &plainData[0], &len, &_encContent[0], encContentLen))
handleErrors(std::string("Envelope::open():EVP_OpenUpdate()"));
int totalLen = len;
if(1 != EVP_OpenFinal(_pCtx, &plainData[len], &len))
handleErrors(std::string("Envelope::open():EVP_OpenFinal()"));
totalLen += len;
plainData.resize(totalLen);
return plainData;
}
void Envelope::handleErrors(std::string&& msg)
{
unsigned long err;
while ((err = ERR_get_error()))
{
if (!msg.empty()) msg.append("\n");
msg.append(ERR_error_string(err, 0));
}
throw CryptoException(msg);
}
} } // namespace Poco::Crypto
+45 -14
View File
@@ -13,15 +13,16 @@
#include "Poco/Crypto/OpenSSLInitializer.h"
#include "Poco/Crypto/CryptoException.h"
#include "Poco/RandomStream.h"
#include "Poco/Thread.h"
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#if OPENSSL_VERSION_NUMBER >= 0x0907000L
#include <openssl/conf.h>
#endif
#if defined(POCO_OS_FAMILY_WINDOWS)
#define POCO_STR_HELPER(x) #x
#define POCO_STR(x) POCO_STR_HELPER(x)
@@ -58,9 +59,17 @@ namespace Poco {
namespace Crypto {
Poco::FastMutex* OpenSSLInitializer::_mutexes(0);
Poco::AtomicCounter OpenSSLInitializer::_rc;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
Poco::FastMutex* OpenSSLInitializer::_mutexes(0);
#endif
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
OSSL_PROVIDER* OpenSSLInitializer::_defaultProvider(0);
OSSL_PROVIDER* OpenSSLInitializer::_legacyProvider(0);
#endif
OpenSSLInitializer::OpenSSLInitializer()
{
@@ -87,18 +96,15 @@ void OpenSSLInitializer::initialize()
{
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
CONF_modules_load(NULL, NULL, 0);
#elif OPENSSL_VERSION_NUMBER >= 0x0907000L
#else
OPENSSL_config(NULL);
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
char seed[SEEDSIZE];
RandomInputStream rnd;
rnd.read(seed, sizeof(seed));
RAND_seed(seed, SEEDSIZE);
int nMutexes = CRYPTO_num_locks();
_mutexes = new Poco::FastMutex[nMutexes];
CRYPTO_set_locking_callback(&OpenSSLInitializer::lock);
@@ -107,14 +113,33 @@ void OpenSSLInitializer::initialize()
// https://sourceforge.net/p/poco/bugs/110/
//
// From http://www.openssl.org/docs/crypto/threads.html :
// "If the application does not register such a callback using CRYPTO_THREADID_set_callback(),
// then a default implementation is used - on Windows and BeOS this uses the system's
// "If the application does not register such a callback using CRYPTO_THREADID_set_callback(),
// then a default implementation is used - on Windows and BeOS this uses the system's
// default thread identifying APIs"
CRYPTO_set_id_callback(&OpenSSLInitializer::id);
#endif
CRYPTO_set_dynlock_create_callback(&OpenSSLInitializer::dynlockCreate);
CRYPTO_set_dynlock_lock_callback(&OpenSSLInitializer::dynlock);
CRYPTO_set_dynlock_destroy_callback(&OpenSSLInitializer::dynlockDestroy);
char seed[SEEDSIZE];
RandomInputStream rnd;
rnd.read(seed, sizeof(seed));
RAND_seed(seed, SEEDSIZE);
#endif
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
if (!_defaultProvider)
{
_defaultProvider = OSSL_PROVIDER_load(NULL, "default");
if (!_defaultProvider) throw CryptoException("Failed to load OpenSSL default provider");
}
if (!_legacyProvider)
{
_legacyProvider = OSSL_PROVIDER_load(NULL, "legacy");
if (!_legacyProvider) throw CryptoException("Failed to load OpenSSL legacy provider");
}
#endif
}
}
@@ -123,6 +148,7 @@ void OpenSSLInitializer::uninitialize()
{
if (--_rc == 0)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_cleanup();
ERR_free_strings();
CRYPTO_set_locking_callback(0);
@@ -130,12 +156,14 @@ void OpenSSLInitializer::uninitialize()
CRYPTO_set_id_callback(0);
#endif
delete [] _mutexes;
CONF_modules_free();
#endif
}
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
void OpenSSLInitializer::lock(int mode, int n, const char* file, int line)
{
if (mode & CRYPTO_LOCK)
@@ -177,6 +205,9 @@ void OpenSSLInitializer::dynlockDestroy(struct CRYPTO_dynlock_value* lock, const
}
#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
void initializeCrypto()
{
OpenSSLInitializer::initialize();
+12 -11
View File
@@ -128,19 +128,12 @@ std::string PKCS12Container::extractFriendlyName(X509* pCert)
std::string friendlyName;
if(pCert)
{
STACK_OF(PKCS12_SAFEBAG)*pBags = 0;
PKCS12_SAFEBAG*pBag = PKCS12_add_cert(&pBags, pCert);
if(pBag)
int length = 0;
char* pBuffer = reinterpret_cast<char*>(X509_alias_get0(pCert, &length));
if (pBuffer)
{
char* pBuffer = PKCS12_get_friendlyname(pBag);
if(pBuffer)
{
friendlyName = pBuffer;
OPENSSL_free(pBuffer);
}
if(pBags) sk_PKCS12_SAFEBAG_pop_free(pBags, PKCS12_SAFEBAG_free);
friendlyName.append(pBuffer, length);
}
else throw OpenSSLException("PKCS12Container::extractFriendlyName()");
}
else throw NullPointerException("PKCS12Container::extractFriendlyName()");
@@ -171,7 +164,15 @@ void PKCS12Container::load(PKCS12* pPKCS12, const std::string& password)
int certCount = sk_X509_num(pCA);
for (int i = 0; i < certCount; ++i)
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
X509* pX509 = sk_X509_value(pCA, i);
#else
// Cert order is reversed on OpenSSL < 3.
// https://github.com/openssl/openssl/issues/16421
// https://github.com/openssl/openssl/pull/12641
// https://github.com/jeroen/openssl/commit/f5eb85eb0fd432406a24abda6511c449eaee6162
X509* pX509 = sk_X509_value(pCA, (certCount - i - 1));
#endif
if (pX509)
{
_caCertList.push_back(X509Certificate(pX509, true));
+2 -2
View File
@@ -51,7 +51,7 @@ void RSADigestEngine::reset()
_signature.clear();
}
const DigestEngine::Digest& RSADigestEngine::digest()
{
if (_digest.empty())
@@ -77,7 +77,7 @@ const DigestEngine::Digest& RSADigestEngine::signature()
return _signature;
}
bool RSADigestEngine::verify(const DigestEngine::Digest& sig)
{
digest();
+10 -17
View File
@@ -21,9 +21,7 @@
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
#include <openssl/bn.h>
#endif
namespace Poco {
@@ -66,7 +64,6 @@ RSAKeyImpl::RSAKeyImpl(const PKCS12Container& cont):
RSAKeyImpl::RSAKeyImpl(int keyLength, unsigned long exponent): KeyPairImpl("rsa", KT_RSA_IMPL),
_pRSA(0)
{
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
_pRSA = RSA_new();
int ret = 0;
BIGNUM* bn = 0;
@@ -83,15 +80,11 @@ RSAKeyImpl::RSAKeyImpl(int keyLength, unsigned long exponent): KeyPairImpl("rsa"
throw;
}
if (!ret) throw Poco::InvalidArgumentException("Failed to create RSA context");
#else
_pRSA = RSA_generate_key(keyLength, exponent, 0, 0);
if (!_pRSA) throw Poco::InvalidArgumentException("Failed to create RSA context");
#endif
}
RSAKeyImpl::RSAKeyImpl(const std::string& publicKeyFile,
const std::string& privateKeyFile,
RSAKeyImpl::RSAKeyImpl(const std::string& publicKeyFile,
const std::string& privateKeyFile,
const std::string& privateKeyPassphrase): KeyPairImpl("rsa", KT_RSA_IMPL),
_pRSA(0)
{
@@ -109,7 +102,7 @@ RSAKeyImpl::RSAKeyImpl(const std::string& publicKeyFile,
if (!pubKey)
{
int rc = BIO_reset(bio);
// BIO_reset() normally returns 1 for success and 0 or -1 for failure.
// BIO_reset() normally returns 1 for success and 0 or -1 for failure.
// File BIOs are an exception, they return 0 for success and -1 for failure.
if (rc != 0) throw Poco::FileException("Failed to load public key", publicKeyFile);
pubKey = PEM_read_bio_RSA_PUBKEY(bio, &_pRSA, 0, 0);
@@ -174,7 +167,7 @@ RSAKeyImpl::RSAKeyImpl(std::istream* pPublicKeyStream,
if (!publicKey)
{
int rc = BIO_reset(bio);
// BIO_reset() normally returns 1 for success and 0 or -1 for failure.
// BIO_reset() normally returns 1 for success and 0 or -1 for failure.
// File BIOs are an exception, they return 0 for success and -1 for failure.
if (rc != 1) throw Poco::FileException("Failed to load public key");
publicKey = PEM_read_bio_RSA_PUBKEY(bio, &_pRSA, 0, 0);
@@ -293,7 +286,7 @@ void RSAKeyImpl::save(const std::string& publicKeyFile,
}
BIO_free(bio);
}
if (!privateKeyFile.empty())
{
BIO* bio = BIO_new(BIO_s_file());
@@ -306,8 +299,8 @@ void RSAKeyImpl::save(const std::string& publicKeyFile,
if (privateKeyPassphrase.empty())
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
else
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(),
reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())),
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(),
reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())),
static_cast<int>(privateKeyPassphrase.length()), 0, 0);
if (!rc) throw Poco::FileException("Failed to write private key to file", privateKeyFile);
}
@@ -350,10 +343,10 @@ void RSAKeyImpl::save(std::ostream* pPublicKeyStream,
if (privateKeyPassphrase.empty())
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
else
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(),
reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())),
rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(),
reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())),
static_cast<int>(privateKeyPassphrase.length()), 0, 0);
if (!rc)
if (!rc)
{
BIO_free(bio);
throw Poco::FileException("Failed to write private key to stream");
+11 -6
View File
@@ -121,7 +121,7 @@ X509Certificate& X509Certificate::operator = (X509Certificate&& cert) noexcept
}
void X509Certificate::swap(X509Certificate& cert)
void X509Certificate::swap(X509Certificate& cert) noexcept
{
using std::swap;
swap(cert._issuerName, _issuerName);
@@ -416,10 +416,14 @@ X509Certificate::List X509Certificate::readPEM(const std::string& pemFileName)
{
List caCertList;
BIO* pBIO = BIO_new_file(pemFileName.c_str(), "r");
if (pBIO == NULL) throw OpenFileException("X509Certificate::readPEM()");
if (pBIO == NULL) throw OpenFileException(Poco::format("X509Certificate::readPEM(%s)", pemFileName));
X509* x = PEM_read_bio_X509(pBIO, NULL, 0, NULL);
if (!x) throw OpenSSLException(Poco::format("X509Certificate::readPEM(%s)", pemFileName));
while(x)
if (!x)
{
BIO_free(pBIO);
throw OpenSSLException(Poco::format("X509Certificate::readPEM(%s)", pemFileName));
}
while (x)
{
caCertList.push_back(X509Certificate(x));
x = PEM_read_bio_X509(pBIO, NULL, 0, NULL);
@@ -432,14 +436,15 @@ X509Certificate::List X509Certificate::readPEM(const std::string& pemFileName)
void X509Certificate::writePEM(const std::string& pemFileName, const List& list)
{
BIO* pBIO = BIO_new_file(pemFileName.c_str(), "a");
if (pBIO == NULL) throw OpenFileException("X509Certificate::writePEM()");
if (pBIO == NULL) throw OpenFileException(Poco::format("X509Certificate::writePEM(%s)", pemFileName));
List::const_iterator it = list.begin();
List::const_iterator end = list.end();
for (; it != end; ++it)
{
if (!PEM_write_bio_X509(pBIO, const_cast<X509*>(it->certificate())))
{
throw OpenSSLException("X509Certificate::writePEM()");
BIO_free(pBIO);
throw OpenSSLException(Poco::format("X509Certificate::writePEM(%s)", pemFileName));
}
}
BIO_free(pBIO);