Modular Arithmetic addition and subtraction using Crypto++ - c++

I am very new to this, but I am trying to add two Integers in modular format using Crypto++ Library.
My program is very simple,
AutoSeededRandomPool prng;
Integer r0, m;
m = Integer( prng, 64);
r0 = Integer( prng, 64);
cout << "m: " << std::hex << m << endl;
cout << "r0:" << std::hex << r0 << endl;
Integer n1(r0 + m);
But this simply didn't work. It complied fine, but it crashed when I was trying to run it.
Could anyone give a sample code for addition/subtraction using Crypto++ please

Modular Arithmetic (addition/subtraction) using Crypto++
We have closed some of the missing documentation gaps based on this question, so I won't address the sample code. The improved docs are available at Integer Class Reference and Integer on the Crypto++ wiki.
However, there may be a bug or (at least) unexpected results from using the ModularArithmetic class. The class describes itself as "Ring of congruence classes modulo n". Mathematically, a Ring is a group with closure and two well defined operations.
The disconnect is, which two operations are the ones included with ModularArithmetic<Integer>. Based on some sample code, it looks like its Multiply and Exponentiate, which is mostly expected (though it could have been Add and Multiply).
I don't think the mathematical definition of Ring gives ModularArithmetic a license to produce unexpected results. However, ModularArithmetic is kind of unique, and it may be accumulating intermediate results that one must then reduce using Multiply and Exponentiate. (It does accumulate results to speed up operations).
The open question for me is, what do we do... I'm trying to solicit some feedback at the moment on the issue.
Here's the test program:
int main(int argc, char* argv[])
{
Integer m("4294967295"), n("0x1000000000000000000000000000000"), j;
j = 1999;
ModularArithmetic ma(j);
cout << "n+m mod j: " << ma.Add(n, m) << endl;
cout << " cross-check: " << (n+m) % j << endl;
cout << "n-m mod j: " << ma.Subtract(n, m) << endl;
cout << " cross-check: " << (n-m) % j << endl;
cout << "n*m mod j: " << ma.Multiply(n, m) << endl;
cout << " cross-check: " << (n*m) % j << endl;
cout << "n/m mod j: " << ma.Divide(n, m) << endl;
cout << " cross-check: " << (n/m) % j << endl;
cout << "n%m mod j: " << ma.Reduce(n, m) << endl;
cout << " cross-check: " << (n%m) % j << endl;
cout << "n^m mod j: " << ma.Exponentiate(n, m) << endl;
cout << " cross-check: " << a_exp_b_mod_c(n,m,j) << endl;
return 0;
}
Here are the results:
$ ./test.exe
n+m mod j: 1329227995784915872903807064575309872.
cross-check: 1755.
n-m mod j: 1329227995784915872903807055985377281.
cross-check: 50.
n*m mod j: 266.
cross-check: 266.
n/m mod j: 599.
cross-check: 1997.
n%m mod j: 1329227995784915872903807055985377281.
cross-check: 1608.
n^m mod j: 1326.
cross-check: 1326.
EDIT 1
The disconnect is, which two operations are the ones included with ModularArithmetic<Integer>...
So I had a chance to go though the source code and add more missing documentation. Of particular interest is AbstractRing< T > Class Template Reference, which ModularArithmetic inherits from. It confirms that multiply and exponentiation are the operations (and it gives rise to helpers, like Square).
What I am not clear about is why ModularArithmetic is providing Add, Subtract and friends but arriving at unexpected results. It could well be that its effectively accumulating the results and waiting to be reduced with a Multiply or Exponentiate, but I don't see any comments in the source code.
EDIT 2
The reason ModularArithmetic appears to produce incorrect results for Add, Subtract and friends is the class is meant to be fast for specific problems, and it does not perform a full reduction using the Euclidean extended algorithm. Rather, it performs at most one subtraction. That means the accumulated value n to be reduced by the modulus p must be in the range [0, 2p).

Related

print multiple numbers in ascending order in C++

So I'm working on this project where I have to gather 2 integers from a user 3 times (loop), and each time I have to print the two integers in ascending order. The restriction is that you can only have two cout statements within your loop (one is asking for their input and the second is outputting the ascending order).
My only issue with that is, when I think about ascending order, I would do it like (which has two count statements):
if (m<n) {
cout << m << n << endl;
if (m>n){
cout << n << m << endl;
So far, this is what I have:
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z;
for (n=0;n<3;n++){
cout << "Give me two numbers: ";
cin >> m;
cin >> z;
//if (m>z);
//cout << m << z << "sorted is: " << m << z << endl;
// This is where I'm getting stuck because I need two count statements to organize in ascending order as shown above
}
}
So have you considered to change which variable holds the lower number? e.g.
if(m > n){
int temp = n;
n = m;
m = temp;
}
Then you can just use one print
cout << m << " " << n << endl;
This is where I'm getting stuck because I need two count[sic]
statements to organize in ascending order as shown above
You have marked this post as C++:
Additional options to consider:
use algorithm lib:
#include <algorithm>
std::cout << std::min(m,n) << " " << std::max(m,n) << std::endl;
or use conditional / ternary operator in your cout:
std::cout << ((m<n) ? m : n) << " " << ((n<m) ? m : n) << std::endl;
References are sometimes fun ... but perhaps this challenge is too trivial.
// guess m < n
int& first = m;
int& second = n;
if(!(m<n)) { first = n; second = m; }
std::cout << first << " " << second << std::endl;
Pointers can do the same:
// guess m < n
int& first = &m;
int& second = &n;
if(!(m<n)) { first = &n; second = &m; }
std::cout << *first << " " << *second << std::endl;
or you can use
lambda expressions, or
c++ functions, or
c++ class methods
But I think each of these would be directly comparable to either of the first alternatives.

C++ inheritance of private functions while using PCL

I've been trying to use the PCA module from PCL in C++, but it's been a pain. At one point I want to switch the current indices of points that need to be operated on using the setIndices() function, but to actually make the update there is a private inherited function that one HAS to use called initCompute() or else it doesn't change them (or at least that is how I understood it). Never the less, the code as is, doesn't update the indices for some reason. This is the documentation for the class and everything works, but I have no idea how to make a workaround for this function which they intended to be used for these purposes:
http://docs.pointclouds.org/trunk/classpcl_1_1_p_c_a.html
How to deal with this? This is the error while compiling.
In function ‘void clustering(pcl::PointCloud<pcl::PointXYZ>::ConstPtr, pcl::PointCloud<pcl::PointXYZL>::Ptr, pcl::PointCloud<pcl::PointXYZRGB>::Ptr, pcl::PointCloud<pcl::PointXYZ>::Ptr, float)’:
/usr/include/pcl-1.7/pcl/common/impl/pca.hpp:64:1: error: ‘bool pcl::PCA<PointT>::initCompute() [with PointT = pcl::PointXYZ]’ is private
pcl::PCA<PointT>::initCompute ()
This is the code:
pcl::PCA<pcl::PointXYZ> cpca = new pcl::PCA<pcl::PointXYZ>;
cpca.setInputCloud(input);
std::cout << "We're now performing the cluster elimination!" << endl;
Eigen::Matrix3f pca_matrix; //serves to hold the eigenvectors, and never got updated...hence the couts for checking.
for (int i = 0; i < nclusters; ++i, n++)
{
// the next two lines had to be done so, I found that in a forum, the library just behaves a bit strange.
pcl::PointIndices::Ptr pi_ptr(new pcl::PointIndices);
pi_ptr->indices = cluster_indices[i].indices;
cout << "Current size is: " << pi_ptr->indices.size() << endl;//this shows different sizes on every turn
//now can use pi_ptr
cpca.setIndices(pi_ptr);
pca_matrix = cpca.getEigenVectors();
// but here I get the same vectors every time
std::cout << "vector " << n << " " << pca_matrix(0,0) << " " << pca_matrix(0,1) << " " << pca_matrix(0,2) << endl;
std::cout << "vector " << n << " " << pca_matrix(1,0) << " " << pca_matrix(1,1) << " " << pca_matrix(1,2) << endl;
std::cout << "vector " << n << " " << pca_matrix(2,0) << " " << pca_matrix(2,1) << " " << pca_matrix(2,2) << endl;
Anyway, I got annoyed after a while and did the following.
I created a pca object at the beginning of a for loop using a pointer, and then deleted it at the end of the loop with delete. It is some allocing and deallocing going on there which is most likely not optimal, but it did the trick. The PCA object itself was only 144 bytes large, cause it mostly uses pointers to address necessary elements.

What is going on in computer memory here?

So my professor told my class to run this program, it supposedly shows what's going on in computer memory. When I ran it, my output file had the same numbers as my professor's output file for the first like 4 lines and then totally different numbers from then on. But this certainly doesn't seem like it's pulling random numbers, because a lot of the output is 0s and a lot of it are large numbers of similar lengths. Can anyone explain this?
#include <iostream>
#include <fstream> // for files
#include <cstdlib> // for exit
#include <climits> // for INT_MAX etc.
int main( )
{
using namespace std;
ofstream outfile;
outfile.open("Whats_in_computer_memory.txt");
cout << "In this program, we declare a small array and then use array syntax " << endl
<< "to see what is in the computer's memory. " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl;
int a[1];
int histogram[214749];
for (int i = 0; i < 214749; i++ )
{
histogram[i] = 0;
}
cout << "&a[0] = " << &a[0] << endl
<< "&histogram[0] = " << &histogram[0]<< endl
<< " " << endl;
cout << INT_MAX << endl;
for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}
for (int i = 0; i < 2 ; i++ )
{
cout << histogram[ i ] << endl;
}
char dummy;
cin >> dummy;
return 0;
}
a has one element. That means
for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}
is undefined behavior as soon as i >= 1. Once you have undefined behavior anything can happen so we can no longer reason out what is going on.
Your professor is trying to demonstrate that the area of memory around your program contains "stuff" - specifically that the memory around your program isn't zero'd or set to any other default value.
Presumably, this is part of a further point that accessing memory out-of-bounds doesn't guarantee that you'll have any particular value, and as such need to initialise your variables accordingly.
However; the problem is that we consider "accessing out-of-bounds of an array" to be undefined behaviour. Undefined behaviour in the C++ standard means "the compiler can handle this situation in whatever way it considers appropriate". Most compilers will serve you values from nearby memory locations (this being simple to do), but they're not required to do so.
Likewise, some compilers can aggressively optimise-out undefined behaviour (like concluding that i can never be greater than 1 when used to index into a, and adjusting the loop appropriately): compilers are free to assume (for optimisation purposes) that undefined behaviour is never invoked by the programmer. See this page from the LLVM project for more details on undefined behaviour (noting that under "Dereferences of Wild Pointers and Out of Bounds Array Accesses", both the Clang team and g++ have made the same decision with regards to handling out-of-bounds errors: they access nearby memory locations; because it's the simplest thing to do in that case).

Strange output, not as expected

sorry for asking you a stupid question, but I just can't figure out why I keep on getting this output.
So here is my code:
#include <cstdio>
#include <iostream>
using namespace std;
unsigned n = 4242;
int getRemainderOf(int m, int n, int& quotient);
static int l = 0;
int main()
{
int quotient; // the value of which should be changed after calling the func.
for(int i=-1; i<=1; ++i)
{
for(int j=-1; j<=1; ++j)
{
if( i && j )
{
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
}
}
}
return 0;
}
int getRemainderOf(int m, int n, int& quotient)
{
++l;
cout << l <<endl;
quotient = m / n;
cout << " quotient " << quotient <<endl;
return m % n;
}
so what I expected to see in the first line of my output was the remainder and then the quotient that I get after calling the function getRemainderOf(). But instead when I cout the value of quotient like that I see that the value of quotient is a garbage value. So the value of the variable is not changed even though I've passed it to the function by using reference.
The funny thing is that if I cout the remainder (got by calling the function) and the quotient separately I will get it right.
I see that the problem might be in calling the function as a argument of the operator << function but I don't get it why the value of the quotient isn't changed since I call the function before I output it. This operator's associativity is left-to-right so what's wrong?
So could you please tell me what is the reason of this output.
What you've just found is a classic example of one of the quirks of C++. Your program can actually be decomposed into this simple example:
int i = 10;
f(i, ++i);
The compiler has the choice of function argument evaluation from left-to-right, but this is not guaranteed. Here's some standard text:
5.2/4 Postfix Epressions [expr.post]
When a function is called, each parameter shall be initialized with its corresponding argument. [Note: Such initializations are indeterminatly sequenced with respect to each other (1.9) - end note]
Because they are indeterminatly sequenced, the compiler has the freedom of evaluating ++i before the first argument and initializing it with the corresponding function parameter, and then evaluating i and initializing it with its respective parameter next.
The reason function call argument evaluation ambiguity is applicable here is because operator<<() is a function but it's just being called with the operator syntax. For example, this is what your code looks like if we use the operator-id syntax:
std::operator<<(std::operator<<(std::operator<<(std::cout, "(").operator<<(i*3), ",").operator<<(j*7), ")").operator<<(getRemainderOf(i*3, 7*j, quotient)).operator<<(quotient);
These are just chains of function calls with arguments and they obey the same rule as the one above.
The solution is to sequence the act of modifying the object and using it in the operator<<() call. You already achieved this with partitioning the operator<<() call into two statements with the semicolon ;, so the function is guaranteed to be called before quotient is printed.
The order of evaluation of function arguments is unspecified.
In these statements
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
there are called overloaded operators << that are in fact functions. You have to split each statement in two statements. For example
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) ;
cout << " " << quotient <<endl;

What to do when an equation returns nan as an answer?

I've been having a slight issue with my program, what I'm trying to do is develop a way for users to simulate the possible strengths of passwords. This is assuming that all passwords are permutations (weird I know, but I presume that this is to stop data from becoming even more unwieldy.) using the equation...
//n!/(n-r)! when n! = (e^-n)*(n^n) sqrt(2(pi)n). When n is number of characters in use and r is length of password
No matter what I put I receive nan as an answer. I thought that perhaps my equation was off (maybe somehow I was dividing by zero) so I reworked it and simplified it a great deal. But that didn't seem to be the problem, though I feel that this got me closer to being correct. But I had the thought that maybe numeric overflow is having an effect here? But I really don't know how to fix something like that. I tried jumping from different data types but nothing seemed to work.
I have a problem with the modulus too. It returns back numbers less than zero for time, so with my noobish knowledge that tells me that maybe I'm overflowing it again but how else am I going to use % without defining it as an int? Maybe fixing the above problem will work out this one?
I would be beyond grateful for any help given to me. How does one go about dealing with return values of nan? Is there a step by step status quo for solving it? Is it pretty much always overflow or could it be something else?
The code itself.
#include <iostream>
#include <cmath>
using namespace std;
const int SECONDS_IN_YEAR = 31556926;
const int SECONDS_IN_DAY = 86400;
const int SECONDS_IN_HOUR = 3600;
const int SECONDS_IN_MIN = 60;
int main()
{
int passwordLength ,characterSymbols;
double instructionsPerSecond, instructionSuccess;
////////////////////////////////////////////////////////////////////////////////
//Equations needed
// n!/(n-r)!
//n is the number of letters in the alphabet
//and r is the number of letters in the password
// n! = (e^-n)*(n^n) sqrt(2(pi)n)
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
// (n-r)
double characterMinusLength= (characterSymbols-passwordLength);
// (n-r)! = (e^-(n-r)) * ((n-r)^(n-r)) * sqrt(2(pi)(n-r))
double denominatorFactorial = ((pow(M_E, -(characterMinusLength)))*
(pow((characterMinusLength),(characterMinusLength)))
* (sqrt(2*M_PI*(characterMinusLength))));
// n!/(n-r)!
long double passwordPermutation = (numeratorFactorial / denominatorFactorial);
// (passwords)* (instructions/Password) * (seconds/instruction) = sec
int passwordSeconds = (passwordPermutation * instructionSuccess)
*(1/instructionsPerSecond);
int passwordMin = passwordSeconds / SECONDS_IN_MIN ;
int passwordHour = passwordSeconds / SECONDS_IN_HOUR;
int passwordDay = passwordSeconds / SECONDS_IN_DAY ;
int passwordYear = passwordSeconds / SECONDS_IN_YEAR;
////////////////////////////////////////////////////////////////////////////////
//Explain purpose of program
cout << "This program is designed to simulate the strength of passwords." << endl;
//Ask for alphabet
cout << "But first, share with me the max number of characters you'd be using."
<< endl;
cin >> characterSymbols;
//Reflect information
cout << "We will be using " << characterSymbols << " character symbols to "
<< " construct the password.\n" << endl;
///////////////////////////////////////////////////////////////////////////////
//Input length of password
cout << "\n\nWill you give me the length of proposed password?" << endl;
cin >> passwordLength;
//Repeat information
cout << "The password length will be " << passwordLength << "." <<endl;
//cout permutations
cout << "This would lead to " << passwordPermutation << " unique password\n"
<< endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for computer strength
cout << "How powerful is this computer? How many instructions per second " << endl;
cout << "can it accomplish?" << endl;
cin >> instructionsPerSecond;
//Read out computer strength
cout << "The computer can do " << instructionsPerSecond << " instructions/second"
<< endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for instructions/password
cout << "The number of instructions needed to test your password is." << endl
<< endl;
cin >> instructionSuccess;
//reflect
cout << "This computer can do " << instructionSuccess
<< " instructions/password" << endl;
////////////////////////////////////////////////////////////////////////////////
cout << "\n\nThe amount of seconds it'll take to crack this passcode is... "
<< endl << passwordSeconds << " seconds.\n\n\n\n\n" << endl;
////////////////////////////////////////////////////////////////////////////////
//Reflect all information in an easily readable table
cout << "Number of character symbols using... " << characterSymbols << endl;
cout << "Length of password... " << passwordLength << endl;
cout << "Number of permutations... " << passwordPermutation << endl;
cout << "Instructions per second... " << instructionsPerSecond << endl;
cout << "Instructions per password..." << instructionSuccess << endl;
cout << endl << endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Add in conversions for min, hour, day, years
cout << "Number of seconds to break..." << passwordSeconds << endl;
cout << "Converted to minutes..." << passwordMin << endl;
passwordMin = passwordSeconds / SECONDS_IN_MIN;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to hours..." << passwordHour << endl;
passwordHour = passwordSeconds / SECONDS_IN_HOUR;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to days..." << passwordDay << endl;
passwordDay = passwordSeconds / SECONDS_IN_DAY;
passwordSeconds = passwordSeconds % SECONDS_IN_DAY;
cout << "Converted to years..." << passwordYear << endl;
passwordYear = passwordSeconds / SECONDS_IN_YEAR;
passwordSeconds = passwordSeconds % SECONDS_IN_YEAR;
return (0);
}
"nan" stands for "not a number". This is happening because you have declared the variables characterSymbols and passwordLength without giving them an initial value.
You must initialize any variable before you use it - if you don't then you will have undetermined behavior. For example:
int x;
int y;
int z = x + y;
There is no way to predict what z will be equal to here because we don't know what x or y are equal to. In the same way, your code should be something like:
int characterSymbols = 10; //or whatever you want the initial value to be
...
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
In this way, numeratorFactorial will have a valid value.
It appears you think you are declaring "equations" when you are actually declaring variables. You write:
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
But characterSymbols isn't defined, only "declared". characterSymbols is declared above it, but it doesn't have a value... yet. Later on you use cin to get a value into it, but when you first declare numeratorFactorial you can't simply expect the program to insert the value into numeratorFactorial when characterSymbols changes.
Some definitions are probably in order: The statement double numeratorFactorial = some_value; creates a variable named numeratorFactorial and uses some_value to fill that variable immediately. What you want is a function, a logical statement that you can "pass values" to so values are generated when you need them. For example, for your numerator factorial:
double numeratorFactorial(double characterSymbols) {
return (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
}
int main() {
std::cout << "Numerator Factorial test: " << numeratorFactorial(5.0) << std::endl;
}
Note that you cannot declare a function within the main function.
This sort of thing is programming fundamentals, and it seems like you are trying to run before you've learned to walk. Get a good book like C++ Primer and pace yourself.