How can I recover compressed y value from sender? - signing

I am working on following scenario:
Generate private and public key
Generate compressed public key with:
PublicKey.AccessGroupParameters().SetPointCompression(true)
Sign some data and send to other end with compressed public key.
[At other end] verify signature using public key
For step 4, I need recover y value. Is there some API I can use among Crypto++?

For step 4, I need recover y value. Is there some API I can use among Crypto++?
During verification, you will load the persisted or serialized key after setting point compression to true.
Below is a little program to experiment with point compression. You can find it on the Crypto++ wiki under Point Compression.
It generates a random key, then creates two public key - one with and and without compression. They two public keys are serialized. Then, it loads two new public keys with the serialized values.
Key 1 (no compress) and Key 2 (compress) and saved, then Key 3 (no compress) and Key 4 (no compress) are loaded from saved values. The keys are the same, and the output is:
$ ./cryptopp-test.exe
Key 1 size (no compression): 214
3081D33081A406072A8648CE3D0201308198020101302006072A8648CE3D0101021500FFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFF7FFFFFFF302C0414FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC0414
1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA450429044A96B5688EF573284664698968C38BB913CB
FC8223A628553168947D59DCC912042351377AC5FB3202150100000000000000000001F4C8F927AED3
CA752257020101032A0004CBFD13CEB20D677D9D3781AFA2E66B7BD5BC0E3C4EB8702144AA62BE5235
DFC691567AA2A7101AB1
Key 2 size (compression): 174
3081AB30819006072A8648CE3D0201308184020101302006072A8648CE3D0101021500FFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFF7FFFFFFF302C0414FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC0414
1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA450415024A96B5688EF573284664698968C38BB913CB
FC8202150100000000000000000001F4C8F927AED3CA75225702010103160003CBFD13CEB20D677D9D
3781AFA2E66B7BD5BC0E3C
Key 3 (after deserialization of Key 1):
y3.x: cbfd13ceb20d677d9d3781afa2e66b7bd5bc0e3ch
y3.y: 4eb8702144aa62be5235dfc691567aa2a7101ab1h
Key 4 (after deserialization of Key 2):
y4.x: cbfd13ceb20d677d9d3781afa2e66b7bd5bc0e3ch
y4.y: 4eb8702144aa62be5235dfc691567aa2a7101ab1h
Here's the program to create, copy, save, load, compress, uncompress and serialize the keys and points.
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <cryptopp/osrng.h>
using CryptoPP::AutoSeededRandomPool;
#include <cryptopp/secblock.h>
using CryptoPP::SecByteBlock;
#include <cryptopp/filters.h>
using CryptoPP::StringSource;
using CryptoPP::StringSink;
#include <cryptopp/hex.h>
using CryptoPP::HexEncoder;
#include <cryptopp/sha.h>
using CryptoPP::SHA1;
#include <cryptopp/integer.h>
using CryptoPP::Integer;
#include <cryptopp/eccrypto.h>
using CryptoPP::ECP;
using CryptoPP::ECDSA;
#include <cryptopp/oids.h>
using CryptoPP::ASN1::secp160r1;
int main(int argc, char* argv[])
{
AutoSeededRandomPool prng;
// Generate a private key, and two public keys.
// One with and one without compression
ECDSA<ECP, SHA1>::PrivateKey privateKey;
privateKey.Initialize(prng, secp160r1());
ECDSA<ECP, SHA1>::PublicKey publicKey1;
privateKey.MakePublicKey(publicKey1);
ECDSA<ECP, SHA1>::PublicKey publicKey2;
privateKey.MakePublicKey(publicKey2);
publicKey2.AccessGroupParameters().SetPointCompression(true);
// Save the public keys
string p1, p2;
publicKey1.Save(StringSink(p1).Ref());
publicKey2.Save(StringSink(p2).Ref());
// Print some stuff about them
string s3, s4;
StringSource ss3(p1, true, new HexEncoder(new StringSink(s3)));
StringSource ss4(p2, true, new HexEncoder(new StringSink(s4)));
cout << "Key 1 (not compressed): " << p1.size() << " bytes" << endl;
cout << " " << s3 << endl;
cout << "Key 2 (compressed): " << p2.size() << " bytes" << endl;
cout << " " << s4 << endl;
cout << endl;
// Two new keys to load up the persisted keys
ECDSA<ECP, SHA1>::PublicKey publicKey3, publicKey4;
publicKey4.AccessGroupParameters().SetPointCompression(true);
publicKey3.Load(StringSource(p1, true).Ref());
publicKey4.Load(StringSource(p2, true).Ref());
// And validate them
publicKey3.Validate(prng, 3);
publicKey4.Validate(prng, 3);
// Get the public elements of the loaded keys
const ECP::Point& y3 = publicKey3.GetPublicElement();
const Integer& y3_x = y3.x;
const Integer& y3_y = y3.y;
const ECP::Point& y4 = publicKey4.GetPublicElement();
const Integer& y4_x = y4.x;
const Integer& y4_y = y4.y;
// Print some stuff about them
cout << "Key 3 (after deserialization of Key 1):" << endl;
cout << " y3.x: " << std::hex << y3_x << endl;
cout << " y3.y: " << std::hex << y3_y << endl;
cout << "Key 4 (after deserialization of Key 2):" << endl;
cout << " y4.x: " << std::hex << y4_x << endl;
cout << " y4.y: " << std::hex << y4_y << endl;
cout << endl;
return 0;
}
You can even cross wires when loading the serialized keys and it just works. Below, the compressed key was loaded from a non-compressed serialization (and vice-versa):
//////////////////////////////////////////////////////////////////////
// Two new keys to load up the persisted keys, but crossing wires
// so so there's a compress/uncompressed mismatch
ECDSA<ECP, SHA1>::PublicKey publicKey5, publicKey6;
publicKey6.AccessGroupParameters().SetPointCompression(true);
// This should be `p1`
publicKey5.Load(StringSource(p2, true).Ref());
// This should be `p2`
publicKey6.Load(StringSource(p1, true).Ref());
// Get the public elemnts of the loaded keys
const ECP::Point& y5 = publicKey5.GetPublicElement();
const Integer& y5_x = y5.x;
const Integer& y5_y = y5.y;
const ECP::Point& y6 = publicKey6.GetPublicElement();
const Integer& y6_x = y6.x;
const Integer& y6_y = y6.y;
// Print some stuff about them
cout << "Key 5 (after deserialization of Key 1):" << endl;
cout << " y5.x: " << std::hex << y5_x << endl;
cout << " y5.y: " << std::hex << y5_y << endl;
cout << "Key 6 (after deserialization of Key 2):" << endl;
cout << " y6.x: " << std::hex << y6_x << endl;
cout << " y6.y: " << std::hex << y6_y << endl;
cout << endl;
If you want to get at the underlying domain parameters (like the base point), use:
const DL_GroupParameters_EC< ECP >& params = publicKey.GetGroupParameters()

Related

Conditional reading of CArchive operator overload in structure data

I have two serialize operator overloads:
friend CArchive& operator<<(CArchive& rArchive, S_MEMORIAL_INFO const& rsMI)
{
return rArchive << rsMI.strHost
<< rsMI.strCohost
<< rsMI.strZoomAttendant
<< rsMI.strChairman
<< rsMI.strPrayerOpen
<< rsMI.strPrayerClose
<< rsMI.strSpeaker
<< rsMI.strImagePath
<< rsMI.strTextBeforeImage
<< rsMI.strTextAfterImage
<< rsMI.iImageWidthAsPercent
<< rsMI.iSongOpen
<< rsMI.iSongClose;
}
friend CArchive& operator>>(CArchive& rArchive, S_MEMORIAL_INFO& rsMI)
{
return rArchive >> rsMI.strHost
>> rsMI.strCohost
>> rsMI.strZoomAttendant
>> rsMI.strChairman
>> rsMI.strPrayerOpen
>> rsMI.strPrayerClose
>> rsMI.strSpeaker
>> rsMI.strImagePath
>> rsMI.strTextBeforeImage
>> rsMI.strTextAfterImage
>> rsMI.iImageWidthAsPercent
>> rsMI.iSongOpen
>> rsMI.iSongClose;
}
But I now wat to introduce version tracking so that I can cope with new fields without causing crashes in my software for users.
So now I would like:
friend CArchive& operator>>(CArchive& rArchive, S_MEMORIAL_INFO const& rsMI)
{
WORD wVersion{};
rArchive >> wVersion
>> rsMI.strHost
>> rsMI.strCohost
>> rsMI.strZoomAttendant
>> rsMI.strChairman
>> rsMI.strPrayerOpen
>> rsMI.strPrayerClose
>> rsMI.strSpeaker;
rsMI.strTheme.Empty();
if(wVersion >= 2)
rArchive >> rsMI.strTheme;
return rArchive >> rsMI.strImagePath
>> rsMI.strTextBeforeImage
>> rsMI.strTextAfterImage
>> rsMI.iImageWidthAsPercent
>> rsMI.iSongOpen
>> rsMI.iSongClose;
}
friend CArchive& operator<<(CArchive& rArchive, S_MEMORIAL_INFO& rsMI)
{
WORD wVersion = 2;
return rArchive << wVersion
<< rsMI.strHost
<< rsMI.strCohost
<< rsMI.strZoomAttendant
<< rsMI.strChairman
<< rsMI.strPrayerOpen
<< rsMI.strPrayerClose
<< rsMI.strSpeaker
<< rsMI.strTheme
<< rsMI.strImagePath
<< rsMI.strTextBeforeImage
<< rsMI.strTextAfterImage
<< rsMI.iImageWidthAsPercent
<< rsMI.iSongOpen
<< rsMI.iSongClose;
}
How can I now cope with the fact that for some users there is no WORD value there in the archive?
With hindsight I would have designed the serialization to write a version number right from the outset, but too late for that now.
As noted in the comments, the problem is that when reading wVersion from the archive this removes two bytes from the CString object following. CArchive performs its own buffer management. The class definition contains several member variables for this, and it's quite easy to find out what they are doing. These members are protected though, so we need to define a derived class, containing a member which sets the current buffer pointer two bytes back:
class CArchiveHlp : public CArchive
{
public :
void GoBack2()
{
if (m_lpBufCur - m_lpBufStart < 2)
AfxThrowFileException(CFileException::genericException);
m_lpBufCur -= 2;
}
};
Then you can use this class in your code like this:
rArchive >> wVersion;
if (wVersion != 2) // Or any other valid version number
{
((CArchiveHlp*)&rArchive)->GoBack2();
wVersion = 0;
}
rArchive >> rsMI.strHost
.
.
The (CArchiveHlp*) cast is wrong in some way because the actual object is not CArchiveHlp (a dynamic_cast would fail here), however the classes are almost identical, and the GoBack2() member is not virtual (so no v-table), therefore you can call it without any problem - it calls CArchiveHlp code for a CArchive class instance, whose data in memory are identical.
It's tested and works.

Crypto++ Raw RSA sign short message with a short key

I have a message with a size limitation of 128 bit, which i want to sign and verify me as the originator. I have only one requirement : The cipher must not exceed the 128 bit limit.
So, after some research of the topic of signing and verification, i decided to use Raw RSA with a key-length of 128 bit, because i did not find any other suitable algorithms with fulfil the requirements. Other algorithms seem always to have some sort of memory overhead that need the cipher to be larger, but maybe i missed the correct ones (If so, it would be great to give me an hint)
I know, that this is crackable in no time, but the main requirement is the short message.
So at first, i tried to encrypt the message with the public key. I wanted to use the high-level schemes that Crypto++ provides (eg. CryptoPP::RSAES_OAEP_SHA_Encryptor), but they have some sort of memory overhead for digests and other stuff, so i used Raw RSA to do the calculations directly.
My C++ code for en-/decryption looks like follows :
// This is our message
std::string message = "0123456789ABCDEX";
CryptoPP::Integer m((const byte *)message.data(), message.size());
std::cout << "message ( "<< std::dec << m.ByteCount() <<" bytes) : " << std::hex << m << std::endl;
// Generate keys
Integer n("0x3a1a51415e596a0d3e261661a35a68f99"); // modulus
Integer e("0x11"); // public exponent
Integer d("0x15dfbe36ba1ba36848b5d3ad478bb011"); // private exponent
RSA::PrivateKey privKey;
RSA::PublicKey pubKey;
privKey.Initialize(n, e, d); // Used for decryption
pubKey.Initialize(n, e); // Used for encryption
// Encrypt
CryptoPP::Integer c = pubKey.ApplyFunction(m); //generate cipher
std::cout << "cipher ( " << std::dec << c.ByteCount() << " bytes) : " << std::hex << c << std::endl;
// Decrypt
CryptoPP::Integer r = privKey.CalculateInverse(prng, c);
std::cout << "decrypted ( " << std::dec <<r.ByteCount()<<" bytes) : " << std::hex << r << std::endl;
if (r == m)
{
std::cout << "Decryption successful" << std::endl;
}
else
{
std::cout << "Decryption failed" << std::endl;
}
Output :
message ( 16 bytes) : 30313233343536373839414243444558h
cipher ( 16 bytes) : 2e294ff384751724c7dbbc31def66511h
decrypted ( 16 bytes) : 30313233343536373839414243444558h
Decryption successful
Now, in order to sign my message i need to use the private key for "encryption" and the public key for "decryption" (i quoted, since it's technically not an encryption). Under the above mentioned link, there is also a paragraph on how to perform private key encryption. There it is written, that one has only to switch the e (public exponent) and d (private exponent) parameters, when creating the pubilc and private key, and then follow the same steps like for encryption :
Encode the message
ApplyFunction (with the private key)
CalculateInverse (with the public key)
But this does not work, since pubKey has no CalculateInverse-method. So i tried a weird thing and now do the following
Encode the message
CalculateInverse (with the private key)
ApplyFunction (with the public key)
or in code :
// This is our message
std::string message = "0123456789ABCDEX";
CryptoPP::Integer m((const byte *)message.data(), message.size());
std::cout << "message ( "<< std::dec << m.ByteCount() <<" bytes) : " << std::hex << m << std::endl;
// Generate keys
Integer n("0x3a1a51415e596a0d3e261661a35a68f99"); // modulus
Integer e("0x11"); // now private exponent
Integer d("0x15dfbe36ba1ba36848b5d3ad478bb011"); // now public exponent
RSA::PrivateKey privKey;
RSA::PublicKey pubKey;
privKey.Initialize(n, d, e); // Used for signing (d and e are swapped)
pubKey.Initialize(n, d); // Used for verification
// Sign with the private key
CryptoPP::Integer c = privKey.CalculateInverse(prng, m); //
std::cout << "cipher ( " << std::dec << c.ByteCount() << " bytes) : " << std::hex << c << std::endl;
// Verify with the public key
CryptoPP::Integer r = pubKey.ApplyFunction(c);
std::cout << "decrypted ( " << std::dec <<r.ByteCount()<<" bytes) : " << std::hex << r << std::endl;
if (r == m) { /* sucess */ } else { /* failed */ }
I'm heavily uncertain if this is the correct way of doing it. And why do i have to swap the exponents? It still works, even if i do not swap them.

CGAL example cannot read input files?

this is my first stackoverflow question, so I hope the following text meets the question requirements. If not, please tell me what needs to be changed so I can adapt the question.
I'm new to CGAL and C++ in general. I would like to use CGAL 5.0.2 on a Macbook Pro early 2015 with macOS Catalina Version 10.15.4.
So to begin with, I followed the instruction steps given by the CGAL documentation using the package manager Homebrew. Since CGAL is a header-only library I configured it using CMake, as is recommended by the documentation.
It all worked out fine, so I went on trying the recommended examples given in the file CGAL-5.0.2.tar.xz, which is provided here. I'm particularly interested in the example Voronoi_Diagram_2.
Using the Terminal I executed the command -DCGAL_DIR=$HOME/CGAL-5.0.2 -DCMAKE_BUILD_TYPE=Release . in the example folder called Voronoi_Diagram_2. Then I executed the command make. All went well, no error messages were prompted. But executing the resulting exec file didn't produce any results.
After some research I managed to modify the code in a way that it prints the values of some variables. Problem seems to be that the input file which contains the line segments for which the voronoi diagramm shall be calculated is not correctly read.
The while loop which I highlighted in the code below by inserting //// signs seems not to be entered. That's why I assume that the variable ifs is empty, even though the input file "data1.svd.cin", which can be found in the folder "data" of the example, wasn't.
Does anyone have an idea for the reasons of this behaviour? Any help is appreciated.
This is the vd_2_point_location_sdg_linf.cpp file included in the example, which I modified:
// standard includes
#include <iostream>
#include <fstream>
#include <cassert>
// includes for defining the Voronoi diagram adaptor
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h>
#include <CGAL/Segment_Delaunay_graph_Linf_2.h>
#include <CGAL/Voronoi_diagram_2.h>
#include <CGAL/Segment_Delaunay_graph_adaptation_traits_2.h>
#include <CGAL/Segment_Delaunay_graph_adaptation_policies_2.h>
// typedefs for defining the adaptor
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Segment_Delaunay_graph_Linf_filtered_traits_2<K> Gt;
typedef CGAL::Segment_Delaunay_graph_Linf_2<Gt> DT;
typedef CGAL::Segment_Delaunay_graph_adaptation_traits_2<DT> AT;
typedef CGAL::Segment_Delaunay_graph_degeneracy_removal_policy_2<DT> AP;
typedef CGAL::Voronoi_diagram_2<DT,AT,AP> VD;
// typedef for the result type of the point location
typedef AT::Site_2 Site_2;
typedef AT::Point_2 Point_2;
typedef VD::Locate_result Locate_result;
typedef VD::Vertex_handle Vertex_handle;
typedef VD::Face_handle Face_handle;
typedef VD::Halfedge_handle Halfedge_handle;
typedef VD::Ccb_halfedge_circulator Ccb_halfedge_circulator;
void print_endpoint(Halfedge_handle e, bool is_src) {
std::cout << "\t";
if ( is_src ) {
if ( e->has_source() ) std::cout << e->source()->point() << std::endl;
else std::cout << "point at infinity" << std::endl;
} else {
if ( e->has_target() ) std::cout << e->target()->point() << std::endl;
else std::cout << "point at infinity" << std::endl;
}
}
int main()
{
std::ifstream ifs("data/data1.svd.cin");
assert( ifs );
VD vd;
Site_2 t;
// /////////// Inserted Comment ////////////////////////////////
std::cout << "In the following the insertion from ifs should take place" << std::flush;
// ///////////////// while loop which doesn't seem to be active //////////////////
while ( ifs >> t ) {
// Existing Code to insert the points in the voronoi structure
vd.insert(t);
// Inserted Code to check if while loop is entered
std::cout << "Entered while loop" << std::flush;
}
// ///////////////////////////////////////////////////////////////////////////////
ifs.close();
assert( vd.is_valid() );
std::ifstream ifq("data/queries1.svd.cin");
assert( ifq );
Point_2 p;
while ( ifq >> p ) {
std::cout << "Query point (" << p.x() << "," << p.y()
<< ") lies on a Voronoi " << std::flush;
Locate_result lr = vd.locate(p);
if ( Vertex_handle* v = boost::get<Vertex_handle>(&lr) ) {
std::cout << "vertex." << std::endl;
std::cout << "The Voronoi vertex is:" << std::endl;
std::cout << "\t" << (*v)->point() << std::endl;
} else if ( Halfedge_handle* e = boost::get<Halfedge_handle>(&lr) ) {
std::cout << "edge." << std::endl;
std::cout << "The source and target vertices "
<< "of the Voronoi edge are:" << std::endl;
print_endpoint(*e, true);
print_endpoint(*e, false);
} else if ( Face_handle* f = boost::get<Face_handle>(&lr) ) {
std::cout << "face." << std::endl;
std::cout << "The vertices of the Voronoi face are"
<< " (in counterclockwise order):" << std::endl;
Ccb_halfedge_circulator ec_start = (*f)->ccb();
Ccb_halfedge_circulator ec = ec_start;
do {
print_endpoint(ec, false);
} while ( ++ec != ec_start );
}
std::cout << std::endl;
}
ifq.close();
return 0;
}

CGAL hole filling with color

I need to implement a 3D hole filling using CGAL library that support color.
is there any possibility to do it without CGAL library modification? I need to fill the hole with an average color of the hole's edge.
Regards, Ali
....
int main(int argc, char* argv[])
{
const char* filename = (argc > 1) ? argv[1] : "data/mech-holes-shark.off";
Mesh mesh;
OpenMesh::IO::read_mesh(mesh, filename);
// Incrementally fill the holes
unsigned int nb_holes = 0;
BOOST_FOREACH(halfedge_descriptor h, halfedges(mesh))
{
if(CGAL::is_border(h,mesh))
{
std::vector<face_descriptor> patch_facets;
std::vector<vertex_descriptor> patch_vertices;
bool success = CGAL::cpp11::get<0>(
CGAL::Polygon_mesh_processing::triangulate_refine_and_fair_hole(
mesh,
h,
std::back_inserter(patch_facets),
std::back_inserter(patch_vertices),
CGAL::Polygon_mesh_processing::parameters::vertex_point_map(get(CGAL::vertex_point, mesh)).
geom_traits(Kernel())) );
CGAL_assertion(CGAL::is_valid_polygon_mesh(mesh));
std::cout << "* FILL HOLE NUMBER " << ++nb_holes << std::endl;
std::cout << " Number of facets in constructed patch: " << patch_facets.size() << std::endl;
std::cout << " Number of vertices in constructed patch: " << patch_vertices.size() << std::endl;
std::cout << " Is fairing successful: " << success << std::endl;
}
}
CGAL_assertion(CGAL::is_valid_polygon_mesh(mesh));
OpenMesh::IO::write_mesh(mesh, "filled_OM.off");
return 0;
}
If you use CGAL::Surface_mesh as Mesh, you can use dynamic property maps to define attributes for your simplices, which allows for example to define colors per face. The "standard" syntax for this is
mesh.add_property_map<face_descriptor, CGAL::Color >("f:color")
I think. There are examples in the documentation of Surface_mesh.

IntelliSense: no operator "<<" matches these operands ) and LNK1120/2001 unresolved

I am working on a assignment for school and I am having some issues i havnet been able to figure out
I got 2 files Stundet.cpp and Student.h
in my Student.h i am declaring a Student class
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
class Student
{private:
string fname;
string lname;
int ID;
public:
Student();
Student(string first,string last, int ID_num);
static int numberOfStudents;
void getName();
void getID();
};
in my Student.cpp i got
`#include <iostream>
#include "Student.h"
#include <string>
using namespace std;
Student::Student()
{numberOfStudents+=1;
}
Student::Student(string first, string last, int ID_num)
{fname=first;
lname=last;
ID=ID_num;
numberOfStudents+=1;}
int Student::numberOfStudents=0;
void Student::getName()
{cout<<fname<<lname;}
void Student::getID()
{cout<<ID;}
main()
{
Student st1("Hakan", "Haberdar", 1234), st2("Charu", "Hans", 2345), st3("Tarikul", "Islam", 5442), st4;
cout << "We created " << Student::numberOfStudents << " student objects." << endl;
cout << st1.getID() << " " << st1.getName() << endl;
cout << st2.getID() << " " << st2.getName() << endl;
cout << st3.getID() << " " << st3.getName() << endl;
cout << st4.getID() << " " << st4.getName() << endl;
system("pause");
} `
my first issue is that i keep getting these external errors that i have no idea how to fix, ive looked around but i dont really understand how to apply what i find. My errors are
Error 1 error LNK2001: unresolved external symbol _WinMainCRTStartup C:\Users\Tato- laptop\Documents\Visual Studio 2010\Projects\Student Class\Student Class\LINK
and
Error 2 error LNK1120: 1 unresolved externals C:\Users\Tato- laptop\Documents\Visual Studio 2010\Projects\Student Class\Debug\Student Class.exe 1
My second issues is that the couts in the .cpp file stopped working, i understand im supposed to overload them or something but I dont really understand how
Any help would be appreciated.