Example of AES using Crypto++ [closed] - encryption

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I have been searching the Internet for good c++ AES code sample/tutorial that teaches the basics of the encryption technology and the use of the Library but so far I have had no luck getting decent material.
good: Easy to understand (Just the basics for on the go study).

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
How do I install Crypto++ in Visual Studio 2010 Windows 7?
*nix environment
For Ubuntu I did:
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Related

Reading from character device with Qt

I'm not very good at character devices, so I need your help. A have a char device(let's call it /dev/my_light) which is a light sensor. I have to read the data from this file and transform it to the brightness value and then pass it to the brightness manager that changes the brightness of my screen. The problem is that when I read the value for some period of time I get old values from the file.I assume there is a buffer(again not sure how character devices exactly work). Whereas when I use cat /dev/my_light I see new data! Is it possible to get rid off the buffer and read new values that were written to the file just right now. Here is my code in Qt:
void MySensor::updateMySensor()
{
Packet packet;
packet.startByte = 0;
packet.mantissa = 0;
packet.exp = 0;
d->device = ::open(d->path.toStdString().c_str(), O_RDONLY);
if (d->device == -1)
{
qDebug() << Q_FUNC_INFO << "can't open the sensor";
return;
}
ssize_t size = ::read(d->device, &packet, sizeof(packet));
close(d->device);
if (size == -1)
{
qDebug() << errno;
return;
}
packet.exp &= 0x0F;
float illumination = pow(2, packet.exp) * packet.mantissa * 0.045;
if(d->singleShot) emit lightSensorIsRunning(true);
emit illuminationRead(illumination);
}
The mySensor function is called every second. I tried to call it each 200 msec but it didn't help. The value of illumination stays old for about 7 seconds(!) whereas the value that I get from cat is new just immediately.
Thank you in advance!
I can't test with your specific device, however, I'm using the keyboard as a read only device.
The program attempts to connect to keyboard and read all keys pressed inside and outside the window. It's a broad solution you'll have to adapt to meet your demands.
Note that I'm opening the file with O_RDONLY | O_NONBLOCK which means open in read only mode and no wait for the event be triggered(some notifier needed to know when data is ready!) respectively.
You'll need super user privilege to run this example!
#include <QtCore>
#include <fcntl.h>
#include <linux/input.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const char *device_name = "/dev/input/by-path/platform-i8042-serio-0-event-kbd";
int descriptor = open(device_name, O_RDONLY | O_NONBLOCK);
if (descriptor < 0)
{
qDebug() << "Error" << strerror(errno);
return a.exec();
}
QFile device;
if (!device.open(descriptor, QFile::ReadOnly))
{
qDebug() << "Error" << qPrintable(device.errorString());
return a.exec();
}
QSocketNotifier notifier(device.handle(), QSocketNotifier::Read);
QObject::connect(&notifier, &QSocketNotifier::activated, &notifier, [&](int socket){
Q_UNUSED(socket)
struct input_event ev;
QByteArray data = device.readAll();
qDebug() << "Event caught:"
<< "\n\nDATA SIZE" << data.size()
<< "\nSTRUCT COUNT" << data.size() / int(sizeof(input_event))
<< "\nSTRUCT SIZE" << sizeof(input_event);
qDebug() << ""; //New line
while (data.size() >= int(sizeof(input_event)))
{
memcpy(&ev, data.data(), sizeof(input_event));
data.remove(0, int(sizeof(input_event)));
qDebug() << "TYPE" << ev.type << "CODE" << ev.code << "VALUE" << ev.value << "TIME" << ev.time.tv_sec;
}
qDebug() << ""; //New line
});
return a.exec();
}

Point Cloud Library: Error while adding point cloud to PCL Visualizer viewer

I have a point cloud (.pcd) file, from which I have generated normals. Now I want to display the input point cloud along with the generated normals in the same viewer window (not in multiple viewports). The code I have developed is
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/features/normal_3d.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/features/integral_image_normal.h>
int main ()
{
// load point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
if (pcl::io::loadPCDFile<pcl::PointXYZ> ("table_scene_mug_stereo_textured.pcd", *cloud) == -1)
{
PCL_ERROR ("Couldn't read file table_scene_mug_stereo_textured.pcd \n");
return (-1);
}
std::cout << "Loaded "
<< cloud->width * cloud->height
<< " data points from test_pcd.pcd with the following fields: "
<< std::endl;
std::cout << "Input cloud Point Size "
<< cloud->points.size ()
<< std::endl;
// organized or unorganized normal estimation
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
if (cloud->isOrganized ())
{
std::cout << "Computing normals Inside organized block " << std::endl;
pcl::IntegralImageNormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
ne.setInputCloud (cloud);
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setNormalSmoothingSize (float (0.03));
ne.setDepthDependentSmoothing (true);
ne.compute (*cloud_normals);
}
else
{
std::cout << "Computing normals Inside non-organized block " << std::endl;
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
ne.setInputCloud (cloud);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
ne.setSearchMethod (tree);
ne.setRadiusSearch (0.03);
ne.compute (*cloud_normals);
}
std::cout << "cloud_normals Point Size "<< cloud_normals->points.size () << std::endl;
//write the normals to a PCD file
pcl::PCDWriter writer;
writer.write("computed_normals.pcd", *cloud_normals, false);
// visualize normals
pcl::visualization::PCLVisualizer viewer("PCL Viewer");
viewer.setBackgroundColor (0.0, 0.0, 0.0);
viewer.addPointCloud< pcl::PointXYZRGB >( cloud, "cloud", 0);
viewer.addPointCloudNormals<pcl::PointXYZ,pcl::Normal>(cloud, cloud_normals);
while (!viewer.wasStopped ())
{
viewer.spinOnce ();
}
return 0;
}
When I try to debug the code, I am getting an error
no instance of overloaded function "pcl::visualization::PCLVisualizer::addPointCloud" matches the
argument list
in the line
viewer.addPointCloud< pcl::PointXYZRGB >( cloud, "cloud", 0);
I have referred the documentation and spent quite some time in the web to solve this problem without success.
Am I adding point cloud to the viewer correctly? If not please let me know the correct way of adding the point cloud to the viewer along with the generated normals.
You have tried to add the wrong type of point cloud. Change the line to:
viewer.addPointCloud< pcl::PointXYZ >( cloud, "cloud", 0);
This question was also answered here:
http://www.pcl-users.org/Point-Cloud-Library-Error-while-adding-point-cloud-to-PCL-Visualizer-viewer-td4046232.html
For more information about types of point clouds, reference the PCL library here:
http://pointclouds.org/documentation/tutorials/adding_custom_ptype.php#what-pointt-types-are-available-in-pcl

Unable to read shared memory data using boost created by Qt

I've created a Qt shared memory program to write a string into shared memory. Now After writing, I need to read it from Boost program. I tried using simple programs, but I couldn't read the string using Boost interprocess.
Here is the Qt code that is writing into the shared memory. And I'm double checking if the string is written by reading from the shared memory from the same program.
void CDialog::loadString()
{
if(sharedMemory.isAttached())
{
if(!sharedMemory.detach())
{
lbl->setText("Unable to detach from Shared Memory");
return;
}
}
lbl->setText("Click on Top Button");
char sString[] = "my string";
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << sString;
int size = buffer.size();
qDebug() << size;
if(!sharedMemory.create(size))
{
lbl->setText("Unable to create shared memory segment");
qDebug() << lbl->text();
}
sharedMemory.lock();
char *to = (char *) sharedMemory.data();
const char *from = buffer.data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();
char * str;
QDataStream in(&buffer);
sharedMemory.lock();
buffer.setData((char *)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> str;
sharedMemory.unlock();
qDebug() << str;
}
And I'm reading it from boost using the same key which I've provided in the Qt program.
Below is the Boost program code -
int main()
{
boost::interprocess::shared_memory_object shdmem(boost::interprocess::open_only, "Highscore", boost::interprocess::read_only);
boost::interprocess::offset_t size;
if (shdmem.get_size(size))
std::cout << "Shared Mem Size: " << size << std::endl;
boost::interprocess::mapped_region region2(shdmem, boost::interprocess::read_only);
char *i2 = static_cast<char *>(region2.get_address());
std::cout << i2 << std::endl;
return 0;
}
Kindly help me in reading the shared memory data from Boost program.
Thank you.
From the Qt docs:
Warning: QSharedMemory changes the key in a Qt-specific way. It is therefore currently not possible to use the shared memory of non-Qt applications with QSharedMemory.
You will probably need to use Boost on both sides.

OpenCL 1.2 C++ Wrapper - undefined reference to clReleaseDevice

I am trying to use the OpenCL C++ wrapper API for the following program :
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <cstdio>
#include <cstdlib>
#include <iostream>
const char helloStr [] = "__kernel void "
"hello(void) "
"{ "
" "
"} ";
int
main(void)
{
cl_int err = CL_SUCCESS;
try {
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if (platforms.size() == 0) {
std::cout << "Platform size 0\n";
return -1;
}
cl_context_properties properties[] =
{ CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0};
cl::Context context(CL_DEVICE_TYPE_CPU, properties);
std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
cl::Program::Sources source(1,
std::make_pair(helloStr,strlen(helloStr)));
cl::Program program_ = cl::Program(context, source);
program_.build(devices);
cl::Kernel kernel(program_, "hello", &err);
cl::Event event;
cl::CommandQueue queue(context, devices[0], 0, &err);
queue.enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(4,4),
cl::NullRange,
NULL,
&event);
event.wait();
}
catch (cl::Error err) {
std::cerr
<< "ERROR: "
<< err.what()
<< "("
<< err.err()
<< ")"
<< std::endl;
}
return EXIT_SUCCESS;
}
I use the same kernel file from that blog post, anyways that is not the issue since I can't get past compilation.
I'm compiling the program with the following command :
g++ example.cpp -o example -l OpenCL
and I get the following error message :
/tmp/ccbUf7dB.o: In function `cl::detail::ReferenceHandler<_cl_device_id*>::release(_cl_device_id*)':
example.cpp:(.text._ZN2cl6detail16ReferenceHandlerIP13_cl_device_idE7releaseES3_[_ZN2cl6detail16ReferenceHandlerIP13_cl_device_idE7releaseES3_]+0x14): undefined reference to `clReleaseDevice'
collect2: error: ld returned 1 exit status
I've read stuff about clReleaseDevice not working for legacy devices (see for example this question), but my graphics card is pretty recent (NVidia GTX 660 Ti, supports OpenCL 1.2). Where can I go from there?
I am running this on Ubuntu 13.04 x64 with nvidia-opencl-dev and opencl-headers installed from ubuntu repositories.
The root cause
The problem is that the OpenCL library that you are linking against does not support OpenCL 1.2. Speaking generically, until an OpenCL implementation supporting the version you want to use becomes available for a specific platform, you will have this problem when linking against the OpenCL shared library provided with it. There are two solutions:
Download the version of cl.hpp from Khronos that matches the OpenCL version provided by your chosen hardware and continue using the library provided by your device's manufacturer.
Link against an OpenCL shared library that implements the latest OpenCL standard, but write multiple code paths - one for each OpenCL version, ensuring that each code path only uses OpenCL functions that are supported by that version. This route is harder and I have no idea how you can do it with the C++ wrapper. If you try to call an OpenCL 1.2 function on a platform that doesn't support OpenCL 1.2 you will get a segfault, that's why different code paths are needed.
Nvidia specific
Nvidia has been very slow in delivering OpenCL 1.2 support. As a result, their OpenCL library did not provide the OpenCL 1.2 functions the linker was looking for, resulting in the errors.
At the end of May 2015 Nvidia released drivers that support OpenCL 1.2, see the comments by Z Boson below. Updating your drivers should resolve the linker error. GeForce GTX 6xx and later cards (except for rebrands of earlier generations) support OpenCL 1.2. You can check the conformant products list on the Khronos OpenCL site to make sure. The GTX 660 Ti is listed so you're in luck.
Yeah. I have never seen OpenCL 1.2 on Nvidia devices. Compile this on your system, and look at the "OpenCL C Version":
#include <iostream>
#include <vector>
#include <CL/cl.hpp>
int main() {
// Get the platforms
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
// Loop over the number of platforms
for ( size_t i = 0; i < platforms.size(); ++i ) {
// Display the platform information
std::cout << "Platform " << i+1 << ": "
<< platforms[i].getInfo<CL_PLATFORM_NAME>()
<< "\n----------------------------------------------"
<< "\nVendor : " << platforms[i].getInfo<CL_PLATFORM_VENDOR>()
<< "\nVersion : " << platforms[i].getInfo<CL_PLATFORM_VERSION>();
// Get the devices on the current platform
std::vector <cl::Device> devices;
platforms[i].getDevices( CL_DEVICE_TYPE_ALL , & devices);
// Loop over the devices
std::cout << "\n----------------------------------------------\n";
for ( size_t j = 0; j < devices.size(); ++j ) {
// Display the device information
std::cout
<< "\n Device " << j+1 << ": "
<< devices[j].getInfo< CL_DEVICE_NAME >()
<< "\n\t Device Version : "
<< devices[j].getInfo< CL_DEVICE_VERSION >()
<< "\n\t OpenCL C Version : "
<< devices[j].getInfo< CL_DEVICE_OPENCL_C_VERSION >()
<< "\n\t Compute Units : "
<< devices[j].getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >()
<< "\n\t Max Work Group Size: "
<< devices[j].getInfo< CL_DEVICE_MAX_WORK_GROUP_SIZE >()
<< "\n\t Clock Frequency : "
<< devices[j].getInfo< CL_DEVICE_MAX_CLOCK_FREQUENCY >()
<< "\n\t Local Memory Size : "
<< devices[j].getInfo< CL_DEVICE_LOCAL_MEM_SIZE >()
<< "\n\t Global Memory Size : "
<< devices[j].getInfo< CL_DEVICE_GLOBAL_MEM_SIZE >();
// Check if the device supports double precision
std::string str = devices[j].getInfo<CL_DEVICE_EXTENSIONS>();
size_t found = str.find("cl_khr_fp64");
std::cout << "\n\t Double Precision : ";
if ( found != std::string::npos ){ std::cout << "yes\n"; }
else { std::cout << "no\n"; }
}
std::cout << "\n----------------------------------------------\n";
}
// std::cin.ignore();
return 0;
}

QtCreator 2.4.1 console input

I'm somewhat new to C++ and QT.
Trying to run a very simple program in QtCreator, which uses console input on WinXP:
#include <QString>
#include <QTextStream>
int main() {
QTextStream streamOut(stdout);
QTextStream streamIn(stdin);
QString s1("This "), s2("is a "), s3("string.");
QString s4 = s1 + s2 + s3;
streamOut << s4 << endl;
streamOut << "The length of that string is " << s4.length() << endl;
streamOut << "Enter a sentence with whitespaces: " << endl;
s4 = streamIn.readLine();
streamOut << "Here is your sentence: \n" << s4 << endl;
streamOut << "The length of your sentence is: " << s4.length() << endl;
return 0;
}
Problem is that native QTCreator's application output, for it's name, doesn't support typing in things. Here is application output:
Starting C:\QProject\test-build-desktop-Qt_4_8_0_for_Desktop_-MinGW_Qt_SDK___>z>>\debug\test.exe...
This is a string.
The length of that string is 17
Enter a sentence with whitespaces:
Qml debugging is enabled. Only use this in a safe environment!
I've tried checking "Run in terminal" in Projects>Desktop>Run as some answers to similar questions here suggested and the terminal shows up, but it doesn't seem to interact with the program anyhow. Terminal's output:
Press RETURN to close this window...
I would say that checking Run in terminal is correct and needed.
What is surprising is that you don't get any compile error, as there is a mistake at line 8 :
cout << "Enter a sentence: "<<;
The last << is wrong.
Correcting your code, I get this :
#include <QString>
#include <QTextStream>
QTextStream cout(stdout);
QTextStream cin(stdin);
int main() {
QString s2;
cout << "Enter a sentence: ";
s2 = cin.readLine();
cout << "Here is your sentence:" << s2 << endl;
cout << "The length of your sentence is: " << s2.length() << endl;
return 0;
}
which works fine on my computer (WinXP, QtCreator 2.2.0).
Are you sure your Qt project is correct and that you are compiling the right file ?

Resources