I'm decrypting some java encrypted text with OpenSSL. Reading this post I wrote the following code.
unsigned int i = 0;
printf("Out array - Before\n");
for(i = 0; i < sizeof(out); i++) {
if(i % 32 == 0)
printf("\n");
printf("%02X", out[i]);
}
printf("\n");
AES_set_decrypt_key((const unsigned char *)a.at(3).c_str(), 128, &aesKey_);
for(i = 0; i < sizeof(bytes); i += AES_BLOCK_SIZE) {
std::cout << "Decrypting at " << i << " of " << sizeof(bytes) << "\n";
AES_ecb_encrypt(bytes + i, out + i, &aesKey_, AES_DECRYPT);
}
std::cout << "HEX : " << a.at(2).c_str() << "\n"
<< "Decrypting : " << bytes << "\n"
<< "With Key : " << a.at(3).c_str() << "\n"
<< "Becomes : " << out << "\n";
printf("Out array - AFTER\n");
for(i = 0; i < sizeof(out); i++) {
if(i % 32 == 0)
printf("\n");
printf("%02X", out[i]);
}
printf("\n");
It appears to decrypt the data fine, though the PKCS5-padding gets decrypted along and some extra garbage (I'm assuming this is due to the PKCS5-padding).
Out array - BEFORE 0000000000000000000000000000000000000000000000000000000000000000
Decrypting at 0 of 18
Decrypting at 16 of 18
HEX : B00FE0383F2E3CBB95A5A28FA91923FA00
Decrypting : ��8?.<������#�
With Key : I'm a secret key
Becomes : no passwordHQ�EZ��-�=%.7�n
Out array - AFTER 6E6F2070617373776F72644851030303C7457F5ACCF12DAA053D252E3708846E
The above is output from my code, no passwordHQ (6E6F2070617373776F72644851) is the expected output, but you can see the padding is decoded 030303 followed by the garbage C7457F5ACCF12DAA053D252E3708846E.
So how do I set the padding in OpenSSL?
I expected there to be an AES_set_padding (or similar) function, but I'm obviously missing it in the documentation.
Please try and use the higher level function defined in EVP_*. For those functions PKCS#7 padding is standard. Note that PKCS#5 padding officially is only for 8 byte block ciphers.
After some searching I found that evp.h should contain:
const EVP_CIPHER *EVP_aes_128_ecb(void);
which you should be able to use with
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
unsigned char *key, unsigned char *iv);
additional information about EVP functions does suggest that it shoud automatically use the correct padding. The IV is of course ignored for ECB mode, so any pointer should do.
Related
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.
I am using nettle cryptography library. I could not do GCM mode properly.
Here is how I am doing it.
What am I doing wrong?
#include<iostream>
#include<nettle/gcm.h>
#include<nettle/aes.h>
using namespace std;
int main()
{
unsigned char key[] = "1234567890123456";
unsigned char iv[] = "123456789012";
unsigned char src[33] = "12345678901234567890123456789012";
unsigned char encoded[32], digest[16], datum[8] = {0,}, decoded[32];
struct gcm_key gk, gk2;
struct gcm_ctx gc, gc2;
struct aes128_ctx ac, ac2;
aes128_set_encrypt_key(&ac, key);
gcm_set_key(&gk, &ac, (nettle_cipher_func*)aes128_encrypt);
gcm_set_iv(&gc, &gk, 12, iv);
gcm_update(&gc, &gk, 8, datum);
gcm_encrypt(&gc, &gk, &ac, (nettle_cipher_func*)aes128_encrypt, 32, encoded, src);
gcm_digest(&gc, &gk, &ac, (nettle_cipher_func*)aes128_encrypt, 16, digest);
aes128_set_decrypt_key(&ac2, key);
gcm_set_key(&gk2, &ac2, (nettle_cipher_func*)aes128_decrypt);
gcm_set_iv(&gc2, &gk2, 12, iv);
gcm_update(&gc2, &gk2, 8, datum);
gcm_decrypt(&gc2, &gk2, &ac2, (nettle_cipher_func*)aes128_decrypt, 32, decoded, encoded);
gcm_digest(&gc2, &gk2, &ac2, (nettle_cipher_func*)aes128_decrypt, 16, digest);
for(unsigned char c : src) cerr << hex << +c;
cout << endl;
for(uint8_t c : encoded) cerr << hex << +c;
cout << endl;
for(uint8_t c : decoded) cerr << hex << +c;
cout << endl;
}
and the output is
31323334353637383930313233343536373839303132333435363738393031320
80435d9ceda763309ec12a876556f72c14641344ef19fbc5c9ca2f51ebeef
f064f9e8db7ae3466979c7b79de95ba6c50714023758ad9abd6eac24d6f565
first line is source and last line is decoded one.
They do not match.. Because I am trying to make a template wrapper class of
GCM, I cannot use the gcm-aes functions..
GCM only uses the encrypt function of the underlying cipher, similarly to CTR mode. So you need to replace aes128_set_decrypt_key and aes128_decrypt with aes128_set_encrypt_key and aes128_encrypt in all places (1 and 3, respectively).
Your example works for me after that change.
To get proper authentication, you also need to compare the digest after decryption, preferably using memeql_sec.
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.
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()
I wrote a simple program to implement SSE intrinsics for computing the inner product of two large (100000 or more elements) vectors. The program compares the execution time for both, inner product computed the conventional way and using intrinsics. Everything works out fine, until I insert (just for the fun of it) an inner loop before the statement that computes the inner product. Before I go further, here is the code:
//this is a sample Intrinsics program to compute inner product of two vectors and compare Intrinsics with traditional method of doing things.
#include <iostream>
#include <iomanip>
#include <xmmintrin.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
typedef float v4sf __attribute__ ((vector_size(16)));
double innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume len1 = len2.
float result = 0.0;
for(int i = 0; i < len1; i++) {
for(int j = 0; j < len1; j++) {
result += (arr1[i] * arr2[i]);
}
}
//float y = 1.23e+09;
//cout << "y = " << y << endl;
return result;
}
double sse_v4sf_innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume that len1 = len2.
if(len1 != len2) {
cout << "Lengths not equal." << endl;
exit(1);
}
/*steps:
* 1. load a long-type (4 float) into a v4sf type data from both arrays.
* 2. multiply the two.
* 3. multiply the same and store result.
* 4. add this to previous results.
*/
v4sf arr1Data, arr2Data, prevSums, multVal, xyz;
//__builtin_ia32_xorps(prevSums, prevSums); //making it equal zero.
//can explicitly load 0 into prevSums using loadps or storeps (Check).
float temp[4] = {0.0, 0.0, 0.0, 0.0};
prevSums = __builtin_ia32_loadups(temp);
float result = 0.0;
for(int i = 0; i < (len1 - 3); i += 4) {
for(int j = 0; j < len1; j++) {
arr1Data = __builtin_ia32_loadups(&arr1[i]);
arr2Data = __builtin_ia32_loadups(&arr2[i]); //store the contents of two arrays.
multVal = __builtin_ia32_mulps(arr1Data, arr2Data); //multiply.
xyz = __builtin_ia32_addps(multVal, prevSums);
prevSums = xyz;
}
}
//prevSums will hold the sums of 4 32-bit floating point values taken at a time. Individual entries in prevSums also need to be added.
__builtin_ia32_storeups(temp, prevSums); //store prevSums into temp.
cout << "Values of temp:" << endl;
for(int i = 0; i < 4; i++)
cout << temp[i] << endl;
result += temp[0] + temp[1] + temp[2] + temp[3];
return result;
}
int main() {
clock_t begin, end;
int length = 100000;
float *arr1, *arr2;
double result_Conventional, result_Intrinsic;
// printStats("Allocating memory.");
arr1 = new float[length];
arr2 = new float[length];
// printStats("End allocation.");
srand(time(NULL)); //init random seed.
// printStats("Initializing array1 and array2");
begin = clock();
for(int i = 0; i < length; i++) {
// for(int j = 0; j < length; j++) {
// arr1[i] = rand() % 10 + 1;
arr1[i] = 2.5;
// arr2[i] = rand() % 10 - 1;
arr2[i] = 2.5;
// }
}
end = clock();
cout << "Time to initialize array1 and array2 = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl;
// printStats("Finished initialization.");
// printStats("Begin inner product conventionally.");
begin = clock();
result_Conventional = innerProduct(arr1, length, arr2, length);
end = clock();
cout << "Time to compute inner product conventionally = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl;
// printStats("End inner product conventionally.");
// printStats("Begin inner product using Intrinsics.");
begin = clock();
result_Intrinsic = sse_v4sf_innerProduct(arr1, length, arr2, length);
end = clock();
cout << "Time to compute inner product with intrinsics = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl;
//printStats("End inner product using Intrinsics.");
cout << "Results: " << endl;
cout << " result_Conventional = " << result_Conventional << endl;
cout << " result_Intrinsics = " << result_Intrinsic << endl;
return 0;
}
I use the following g++ invocation to build this:
g++ -W -Wall -O2 -pedantic -march=i386 -msse intrinsics_SSE_innerProduct.C -o innerProduct
Each of the loops above, in both the functions, runs a total of N^2 times. However, given that arr1 and arr2 (the two floating point vectors) are loaded with a value 2.5, the length of the array is 100,000, the result in both cases should be 6.25e+10. The results I get are:
Results:
result_Conventional = 6.25e+10
result_Intrinsics = 5.36871e+08
This is not all. It seems that the value returned from the function that uses intrinsics "saturates" at the value above. I tried putting other values for the elements of the array and different sizes too. But it seems that any value above 1.0 for the array contents and any size above 1000 meets with the same value we see above.
Initially, I thought it might be because all operations within SSE are in floating point, but floating point should be able to store a number that is of the order of e+08.
I am trying to see where I could be going wrong but cannot seem to figure it out. I am using g++ version: g++ (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2).
Any help on this is most welcome.
Thanks,
Sriram.
The problem that you are having is that while a float can store 6.25e+10, it only has a few significant digits of precision.
This means that when you are building a large number by adding lots of small numbers together a bit at a time, you reach a point where the smaller number is smaller than the lowest precision digit in the larger number so adding it up has no effect.
As to why you are not getting this behaviour in the non-intrinsic version, it is likely that result variable is being held in a register which uses a higher precision that the actual storage of a float so it is not being truncated to the precision of a float on every iteration of the loop. You would have to look at the generated assembler code to be sure.