Exemple #1
0
static int bsegs_read(BIO *b, char *buf, int size)
{
	BIO_SEGS_CTX *ctx = (BIO_SEGS_CTX *)b->ptr;
	int read = 0;

	while (size > 0 && ctx->current_seg < ctx->nsegs)
	{
		int nb = ctx->seg[ctx->current_seg][SEG_SIZE] - ctx->seg_pos;

		if (nb > size)
			nb = size;

		if (nb > 0)
		{
			if (ctx->seg_pos == 0)
				(void)BIO_seek(b->next_bio, ctx->seg[ctx->current_seg][SEG_START]);

			(void)BIO_read(b->next_bio, buf, nb);
			ctx->seg_pos += nb;
			read += nb;
			buf += nb;
			size -= nb;
		}
		else
		{
			ctx->current_seg++;

			if (ctx->current_seg < ctx->nsegs)
				ctx->seg_pos = 0;
		}
	}

	return read;
}
void CryptStream::_evaluateHeader (int *headerMode) {
	assert (_mode == READ);
	assert (_file_bio); // Operate on _file_bio
	assert (headerMode);
	
	char buf[header_buf_size+1];
	int r = BIO_read(_file_bio, buf, header_buf_size);
	buf[r] = '\0';
	int offset = 0;
	const int ciphNameLen = 30;
	char cipherName[ciphNameLen + 1];
	char iv[256 + 1];
	int useEncryption, useBase64Encode;
	if (r = sscanf (buf, "*167110* # v:%i # c:%i # e:%i # o:%i # ciph:%30s # iv:%256s # count:%i #",
			&this->_version, &useEncryption, &useBase64Encode, &offset, cipherName, iv, &_pbkdfIterationCount) != 7)
	{
		throw std::runtime_error ("Invalid file header. The file is probably not a valid XKey keystore.");
	}
	this->_cipher = EVP_get_cipherbyname(cipherName);
	if (!_cipher)
		throw std::runtime_error ("OpenSSL library does not provide requested Cipher mode from file header");
	if (strnlen((const char*)iv, 256) != _cipher->iv_len * 2)
		throw std::runtime_error ("Invalid initialization vector length");
	if (_pbkdfIterationCount <= 0)
		throw std::runtime_error ("Invalid key iteration count");
	this->_iv.assign( hex2uc(iv, _cipher->iv_len * 2) );
	BIO_seek (_file_bio, offset);
	*headerMode = ((useEncryption) ? (*headerMode | USE_ENCRYPTION) : (*headerMode & ~USE_ENCRYPTION));
	*headerMode = ((useBase64Encode) ? (*headerMode | BASE64_ENCODED) : (*headerMode & ~BASE64_ENCODED));
}
Exemple #3
0
void pki_multi::fromPEM_BIO(BIO *bio, QString name)
{
	QString text;
	pki_base *item = NULL;
	char buf[BUFLEN];
	int len, startpos;
	for (;;) {
		try {
			int pos = BIO_tell(bio);
			len = BIO_read(bio, buf, BUFLEN-1);
			buf[len] = '\0';
			text = buf;
			item = pkiByPEM(text, &startpos);
			if (!item) {
				if (startpos <= 0)
					break;
				if (BIO_seek(bio, pos + startpos) == -1)
					throw errorEx(tr("Seek failed"));
				continue;
			}
			pos += startpos;
			if (BIO_seek(bio, pos) == -1)
				throw errorEx(tr("Seek failed"));
			item->fromPEM_BIO(bio, name);
			if (pos == BIO_tell(bio)) {
				/* No progress, do it manually */
				if (BIO_seek(bio, pos + 1))
					throw errorEx(tr("Seek failed"));
				printf("Could not load: %s\n",
						CCHAR(item->getClassName()));
				delete item;
				continue;
			}
			openssl_error();
			multi.append(item);
		} catch (errorEx &err) {
			MainWindow::Error(err);
			if (item)
				delete item;
			item = NULL;
		}
	}
	if (multi.size() == 0)
		throw errorEx(tr("No known PEM encoded items found"));
}
Exemple #4
0
int main()
{
	const char* inFilename="data.jpg.enc";
    unsigned char key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
    unsigned char iv[]  = {0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};

	BIO* fileBio=BIO_new_file(inFilename,"rb");
	
	BIO* tBio=BIO_new(&methods_t);
	
	BIO* cipherBio = BIO_new(BIO_f_cipher ());
	BIO_set_cipher (cipherBio, EVP_aes_128_cbc (), key, iv, 0);
	
	BIO_push(cipherBio,tBio);
	BIO_push(tBio,fileBio);

	unsigned char* buffer[4096];

    FILE* out = fopen("data.1.c010", "wb");
    int seek_ret=BIO_seek(cipherBio,10000-16);
    if(seek_ret!=0){
    	printf("GmCAJDCY seek_ret %d\n",seek_ret);
    	return 1;
    }
    BIO_read(cipherBio,buffer,16);
	int len=BIO_read(cipherBio,buffer,4096);
	if(len!=4096){
		printf("yRWvFwNc len %d\n",len);
		return 1;
	}
	fwrite(buffer, 1, len, out);
    BIO_free(cipherBio);

    fclose(out);
    
    memset(buffer,0,4096);
    
    FILE* in0=fopen("data.jpg", "rb");
    seek_ret=fseek(in0,10000,SEEK_SET);
    if(seek_ret!=0){
    	printf("TjFQJbgg seek_ret %d\n",seek_ret);
    	return 1;
    }
    len=fread(buffer,1,4096,in0);
	if(len!=4096){
		printf("ZwIxswJf len %d\n",len);
		return 1;
	}
	fclose(in0);
	
	FILE* out0=fopen("data.0.c010", "wb");
	fwrite(buffer, 1, len, out0);
    fclose(out0);

    return 0;
}
Exemple #5
0
RSAKeyImpl::RSAKeyImpl(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase):
	_pRSA(0)
{
	poco_assert_dbg(_pRSA == 0);
	
	_pRSA = RSA_new();
	if (pPublicKeyStream)
	{
		std::string publicKeyData;
		Poco::StreamCopier::copyToString(*pPublicKeyStream, publicKeyData);
		BIO* bio = BIO_new_mem_buf(const_cast<char*>(publicKeyData.data()), static_cast<int>(publicKeyData.size()));
		if (!bio) throw Poco::IOException("Cannot create BIO for reading public key");
		RSA* publicKey = PEM_read_bio_RSAPublicKey(bio, &_pRSA, 0, 0);
		if (!publicKey) 
		{
			int rc = BIO_seek(bio, 0);
			if (rc != 0) throw Poco::FileException("Failed to load public key");
			publicKey = PEM_read_bio_RSA_PUBKEY(bio, &_pRSA, 0, 0);
		}
		BIO_free(bio);
		if (!publicKey)
		{
			freeRSA();
			throw Poco::FileException("Failed to load public key");
		}
	}

	if (pPrivateKeyStream)
	{
		std::string privateKeyData;
		Poco::StreamCopier::copyToString(*pPrivateKeyStream, privateKeyData);
		BIO* bio = BIO_new_mem_buf(const_cast<char*>(privateKeyData.data()), static_cast<int>(privateKeyData.size()));
		if (!bio) throw Poco::IOException("Cannot create BIO for reading private key");
		RSA* privateKey = 0;
		if (privateKeyPassphrase.empty())
			privateKey = PEM_read_bio_RSAPrivateKey(bio, &_pRSA, 0, 0);
		else
			privateKey = PEM_read_bio_RSAPrivateKey(bio, &_pRSA, 0, const_cast<char*>(privateKeyPassphrase.c_str()));
		BIO_free(bio);
		if (!privateKey)
		{
			freeRSA();
			throw Poco::FileException("Failed to load private key");
		}
	}
}
Handle<Key> Provider_System::getKeyFromURI(Handle<std::string> uri, Handle<std::string> format, bool enc){
	LOGGER_FN();

	try{
		if (enc){
			THROW_EXCEPTION(0, Provider_System, NULL, "Encrypted key need password callback function. Unsupported now");
		}
		BIO *bioFile = NULL;
		EVP_PKEY *hkey = NULL;

		LOGGER_OPENSSL(BIO_new);
		bioFile = BIO_new(BIO_s_file());
		LOGGER_OPENSSL(BIO_read_filename);
		if (BIO_read_filename(bioFile, uri->c_str()) > 0){
			LOGGER_OPENSSL(BIO_seek);
			BIO_seek(bioFile, 0);

			if (strcmp(format->c_str(), "PEM") == 0){
				LOGGER_OPENSSL(PEM_read_bio_PrivateKey);
				hkey = PEM_read_bio_PrivateKey(bioFile, NULL, 0, NULL);
			}
			else if (strcmp(format->c_str(), "DER") == 0){
				LOGGER_OPENSSL(d2i_PKCS8PrivateKey_bio);
				hkey = d2i_PKCS8PrivateKey_bio(bioFile, NULL, 0, NULL);
			}
			else{
				THROW_EXCEPTION(0, Provider_System, NULL, "Unsupported format. Only PEM | DER");
			}
		}

		LOGGER_OPENSSL(BIO_free);
		BIO_free(bioFile);

		if (!hkey){
			THROW_EXCEPTION(0, Provider_System, NULL, "Unable decode key from PEM/DER");
		}
		else{
			return new Key(hkey);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, Provider_System, e, "getCSRFromURI");
	}
}
Handle<CertificationRequest> Provider_System::getCSRFromURI(Handle<std::string> uri, Handle<std::string> format){
	LOGGER_FN();

	try{
		BIO *bioFile = NULL;
		X509_REQ *hreq = NULL;

		LOGGER_OPENSSL(BIO_new);
		bioFile = BIO_new(BIO_s_file());
		LOGGER_OPENSSL(BIO_read_filename);
		if (BIO_read_filename(bioFile, uri->c_str()) > 0){
			LOGGER_OPENSSL(BIO_seek);
			BIO_seek(bioFile, 0);

			if (strcmp(format->c_str(), "PEM") == 0){
				LOGGER_OPENSSL(PEM_read_bio_X509_REQ);
				hreq = PEM_read_bio_X509_REQ(bioFile, NULL, NULL, NULL);
			}
			else if (strcmp(format->c_str(), "DER") == 0){
				LOGGER_OPENSSL(d2i_X509_REQ_bio);
				hreq = d2i_X509_REQ_bio(bioFile, NULL);
			}
			else{
				THROW_EXCEPTION(0, Provider_System, NULL, "Unsupported format. Only PEM | DER");
			}
		}

		LOGGER_OPENSSL(BIO_free);
		BIO_free(bioFile);

		if (!hreq){
			THROW_EXCEPTION(0, Provider_System, NULL, "Unable decode csr from PEM/DER");
		}
		else{
			return new CertificationRequest(hreq);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, Provider_System, e, "getCSRFromURI");
	}
}
Handle<CRL> Provider_System::getCRLFromURI(Handle<std::string> uri, Handle<std::string> format){
	LOGGER_FN();

	try{
		BIO *bioFile = NULL;
		X509_CRL *hcrl = NULL;

		LOGGER_OPENSSL(BIO_new);
		bioFile = BIO_new(BIO_s_file());
		LOGGER_OPENSSL(BIO_read_filename);
		if (BIO_read_filename(bioFile, uri->c_str()) > 0){
			LOGGER_OPENSSL(BIO_seek);
			BIO_seek(bioFile, 0);

			if (strcmp(format->c_str(), "PEM") == 0){
				LOGGER_OPENSSL(PEM_read_bio_X509_CRL);
				hcrl = PEM_read_bio_X509_CRL(bioFile, NULL, NULL, NULL);
			}
			else if (strcmp(format->c_str(), "DER") == 0){
				LOGGER_OPENSSL(d2i_X509_CRL_bio);
				hcrl = d2i_X509_CRL_bio(bioFile, NULL);
			}
			else{
				THROW_EXCEPTION(0, Provider_System, NULL, "Unsupported format. Only PEM | DER");
			}
		}
		LOGGER_OPENSSL(BIO_free);
		BIO_free(bioFile);

		if (!hcrl){
			THROW_EXCEPTION(0, Provider_System, NULL, "Unable decode CRL from PEM/DE");
		}
		else{
			return new CRL(hcrl);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, Provider_System, e, "getCRLFromURI");
	}
}
Exemple #9
0
void pki_evp::fromPEM_BIO(BIO *bio, QString name)
{
	EVP_PKEY *pkey;
	int pos;
	pass_info p(XCA_TITLE, QObject::tr(
			"Please enter the password to decrypt the private key."));
	pos = BIO_tell(bio);
	pkey = PEM_read_bio_PrivateKey(bio, NULL, MainWindow::passRead, &p);
	if (!pkey){
		pki_ign_openssl_error();
		pos = BIO_seek(bio, pos);
		pkey = PEM_read_bio_PUBKEY(bio, NULL, MainWindow::passRead, &p);
	}
	if (pkey){
		if (key)
			EVP_PKEY_free(key);
		key = pkey;
		if (EVP_PKEY_isPrivKey(key))
			bogusEncryptKey();
		setIntName(rmslashdot(name));
	}
	openssl_error(name);
}
Exemple #10
0
RSAKeyImpl::RSAKeyImpl(
		const std::string& publicKeyFile, 
		const std::string& privateKeyFile, 
		const std::string& privateKeyPassphrase):
	_pRSA(0)
{
	poco_assert_dbg(_pRSA == 0);
	
	_pRSA = RSA_new();
	if (!publicKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for reading public key", publicKeyFile);
		int rc = BIO_read_filename(bio, publicKeyFile.c_str());
		if (rc)
		{
			RSA* pubKey = PEM_read_bio_RSAPublicKey(bio, &_pRSA, 0, 0);
			if (!pubKey) 
			{
				int rc = BIO_seek(bio, 0);
				if (rc != 0) throw Poco::FileException("Failed to load public key", publicKeyFile);
				pubKey = PEM_read_bio_RSA_PUBKEY(bio, &_pRSA, 0, 0);
			}
			BIO_free(bio);
			if (!pubKey)
			{
				freeRSA();
				throw Poco::FileException("Failed to load public key", publicKeyFile);
			}
		}
		else
		{
			freeRSA();
			throw Poco::FileNotFoundException("Public key file", publicKeyFile);
		}
	}

	if (!privateKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for reading private key", privateKeyFile);
		int rc = BIO_read_filename(bio, privateKeyFile.c_str());
		if (rc)
		{
			RSA* privKey = 0;
			if (privateKeyPassphrase.empty())
				privKey = PEM_read_bio_RSAPrivateKey(bio, &_pRSA, 0, 0);
			else
				privKey = PEM_read_bio_RSAPrivateKey(bio, &_pRSA, 0, const_cast<char*>(privateKeyPassphrase.c_str()));
			BIO_free(bio);
			if (!privKey)
			{
				freeRSA();
				throw Poco::FileException("Failed to load private key", privateKeyFile);
			}
		}
		else
		{
			freeRSA();
			throw Poco::FileNotFoundException("Private key file", privateKeyFile);
		}
	}
}