Calculating d value in RSA - rsa

I saw a couple questions about this but most of them were answered in unhelpful way or didn't get a proper answer at all. I have these variables:
p = 31
q = 23
e - public key exponent = 223
phi - (p-1)*(q-1) = 660
Now I need to calculate d variable (which I know is equal 367). The problem is that I don't know how. I found this equation on the internet but it doesn't work (or I can't use it):
e⋅d=1modϕ(n)
When I see that equation i think that it means this:
d=(1modϕ(n))/e
But apparently it doesn't because 367 (1modϕ(n))/e = 1%660/223 = 1/223 != 367
Maybe I don't understand and I did something wrong - that's why I ask.
I did some more research and I found second equation:
d=1/e mod ϕ(n)
or
d=e^-1 mod ϕ(n)
But in the end it gives the same result:
1/e mod ϕ(n) = 1/223 % 660 = 1/223 != 367
Then I saw some guy saying that to solve that equation you need extended Euclidean algorithm If anyone knows how to use it to solve that problem then I'd be very thankful if you help me.

If you want to calculate something like a / b mod p, you can't just divide it and take division remainder from it. Instead, you have to find such b-1 that b-1 = 1/b mod p (b-1 is a modular multiplicative inverse of b mod p). If p is a prime, you can use Fermat's little theorem. It states that for any prime p, ap = a mod p <=> a(p - 2) = 1/a mod p. So, instead of a / b mod p, you have to compute something like a * b(p - 2) mod p. b(p - 2) can be computed in O(log(p))
using exponentiation by squaring. If p is not a prime, modular multiplicative inverse exists if and only if GCD(b, p) = 1. Here, we can use extended euclidean algorithm to solve equation bx + py = 1 in logarithmic time. When we have bx + py = 1, we can take it mod p and we have bx = 1 mod p <=> x = 1/b mod p, so x is our b-1. If GCD(b, p) ≠ 1, b-1 mod p doesn't exist.
Using either Fermat's theorem or the euclidean algorithm gives us same result in same time complexity, but the euclidean algorithm can also be used when we want to compute something modulo number that's not a prime (but it has to be coprime with numer want to divide by).

Related

Perceptron - MatLab Serious Confusion

This is my first stab at machine learning, and I can implement the code anyway that I want. I have Matlab access, which I think will be simpler than Python, and I have pseudo code for implementing a PLA. The last part of the code, however, absolutely baffles me, though it is simpler than the code I have seen on here thus far. It seems to be calling for the use of variables not declared. Here's what I have. I'll point out the number line at which I get stuck.
1) w <- (n + 1) X m (matrix of small random nums)
2) I <- I augmented with col. of 1s
3) for 1 = 1 to 1000
4) delta_W = (N + 1) X m (matrix of zeros) // weight changes
5) for each pattern 1 <= j <= p
6) Oj = (Ij * w) > 0 // j's are subscript/vector matrix product w/ threshold
7) Dj = = Tj - Oj // diff. between target and actual
8) w = w + Ij(transpose)*Dj // the learning rule
Lines 1 thru 4 are coded.
My questions are on line 5: What does "for each pattern mean" (i.e., how does one say it in code). Also, which j are they interested in, I have a j in the observation matrix and a j in the target matrix. Also, where did "p" come from (I have i's, j's, m's and n's but no p's)? Any thoughts would be appreciated.
"for each pattern" refers to the inputs. All they are saying is to run that loop where Ij is the input to the perceptron.
To write this in MATLAB, it really depends on how your data is oriented. I would store your inputs as a mXn matrix, where m is the number of inputs and n is the size of each input.
Say our inputs look like :
input = [1 5 -1;
2 3 2;
4 5 6;
... ]
First 'augment' this with a column of ones for the bias input:
[r c] = size(input);
input = [input ones(r,1)];
Then, your for loop will simply be:
for inputNumber = 1:r
pattern = input(inputNumber,:);
and you can continue from there.

Matlab : How to represent a real number as binary

Problem : How do I use a continuous map - The Link1: Bernoulli Shift Map to model binary sequence?
Concept :
The Dyadic map also called as the Bernoulli Shift map is expressed as x(k+1) = 2x(k) mod 1. In Link2: Symbolic Dynamics, explains that the Bernoulli Map is a continuous map and is used as the Shift Map. This is explained further below.
A numeric trajectory can be symbolized by partitioning into appropriate regions and assigning it with a symbol. A symbolic orbit is obtained by writing down the sequence of symbols corresponding to the successive partition elements visited by the point in its orbit. One can learn much about the dynamics of the system by studying its symbolic orbits. This link also says that the Bernoulli Shift Map is used to represent symbolic dynamics.
Question :
How is the Bernoulli Shift Map used to generate the binary sequence? I tried like this, but this is not what the document in Link2 explains. So, I took the numeric output of the Map and converted to symbols by thresholding in the following way:
x = rand();
y = mod(2* x,1) % generate the next value after one iteration
y =
0.3295
if y >= 0.5 then s = 1
else s = 0
where 0.5 is the threshold value, called the critical value of the Bernoulli Map.
I need to represent the real number as fractions as explained here on Page 2 of Link2.
Can somebody please show how I can apply the Bernoulli Shift Map to generate symbolized trajectory (also called time series) ?
Please correct me if my understanding is wrong.
How do I convert a real valued numeric time series into symbolized i.e., how do I use the Bernoulli Map to model binary orbit /time series?
You can certainly compute this in real number space, but you risk hitting precision problems (depending on starting point). If you're interested in studying orbits, you may prefer to work in a rational fraction representation. There are more efficient ways to do this, but the following code illustrates one way to compute a series derived from that map. You'll see the period-n definition on page 2 of your Link 2. You should be able to see from this code how you could easily work in real number space as an alternative (in that case, the matlab function rat will recover a rational approximation from your real number).
[EDIT] Now with binary sequence made explicit!
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% * 2
num = num * 2;
% mod 1
if num >= den
num = num - den;
end
% simplify rational fraction
g = gcd(num, den);
if g > 1
num = num / g;
den = den / g;
end
% recover 8-bit binary representation
bits = 8;
q = 2^bits;
x = num / den * q;
b = dec2bin(x, bits);
% display
fprintf('%4i / %4i == 0.%s\n', num, den, b);
end
Ach... for completeness, here's the real-valued version. Pure mathematicians should look away now.
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% use floating point approximation
x = num / den;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% apply map
x = mod(x*2, 1);
% display
[num, den] = rat(x);
fprintf('%i / %i\n', num, den);
end
And, for extra credit, why is this implementation fast but daft? (HINT: try setting num_steps to 50)...
% matlab vectorised version
period = 6;
num = 3;
den = 2^period-1;
x = zeros(1, num_steps);
x(1) = num / den;
y = filter(1, [1 -2], x);
[a, b] = rat(mod(y, 1));
disp([a' b']);
OK, this is supposed to be an answer, not a question, so let's answer my own questions...
It's fast because it uses Matlab's built-in (and highly optimised) filter function to handle the iteration (that is, in practice, the iteration is done in C rather than in M-script). It's always worth remembering filter in Matlab, I'm constantly surprised by how it can be turned to good use for applications that don't look like filtering problems. filter cannot do conditional processing, however, and does not support modulo arithmetic, so how do we get away with it? Simply because this map has the property that whole periods at the input map to whole periods at the output (because the map operation is multiply by an integer).
It's daft because it very quickly hits the aforementioned precision problems. Set num_steps to 50 and watch it start to get wrong answers. What's happening is the number inside the filter operation is getting to be so large (order 10^14) that the bit we actually care about (the fractional part) is no longer representable in the same double-precision variable.
This last bit is something of a diversion, which has more to do with computation than maths - stick to the first implementation if your interest lies in symbol sequences.
If you only want to deal with rational type of output, you'll first have to convert the starting term of your series into a rational number if it is not. You can do that with:
[N,D] = rat(x0) ;
Once you have a numerator N and a denominator D, it is very easy to calculate the series x(k+1)=mod(2*x(k), 1) , and you don't even need a loop.
for the part 2*x(k), it means all the Numerator(k) will be multiplied by successive power of 2, which can be done by matrix multiplication (or bsxfun for the lover of the function):
so 2*x(k) => in Matlab N.*(2.^(0:n-1)) (N is a scalar, the numerator of x0, n is the number of terms you want to calculate).
The Mod1 operation is also easy to translate to rational number: mod(x,1)=mod(Nx,Dx)/Dx (Nx and Dx being the numerator and denominator of x.
If you do not need to simplify the denominator, you could get all the numerators of the series in one single line:
xn = mod( N.*(2.^(0:n-1).'),D) ;
but for visual comfort, it is sometimes better to simplify, so consider the following function:
function y = dyadic_rat(x0,n)
[N,D] = rat(x0) ; %// get Numerator and Denominator of first element
xn = mod( N.*(2.^(0:n-1).'),D) ; %'// calculate all Numerators
G = gcd( xn , D ) ; %// list all "Greatest common divisor"
y = [xn./G D./G].' ; %'// output simplified Numerators and Denominators
If I start with the example given in your wiki link (x0=11/24), I get:
>> y = dyadic_rat(11/24,8)
y =
11 11 5 2 1 2 1 2
24 12 6 3 3 3 3 3
If I start with the example given by Rattus Ex Machina (x0=3/(2^6-1)), I also get the same result:
>> y = dyadic_rat(3/63,8)
y =
1 2 4 8 16 11 1 2
21 21 21 21 21 21 21 21

matlab wrong modulo result when the divident is raised to a power

Just wondering... I tried doing by hand (with the multiply and square method) the operation (111^11)mod143 and I got the result 67. I also checked that this is correct, in many online tools. Yet, in matlab plugging:
mod(111^11,143)
gives 127! Is there any particular reason for this? I didn't find anything in the documentation...
The value of 111^11 (about 3.1518e+022) exceeds the maximum integer that is guaranteed to be represented exactly as a double, which is 2^53 (about 9.0072e+015). So the result is spoilt by insufficient numerical precision.
To achieve the correct result, use symbolic computation:
>> syms x y z
>> r = mod(x^y, z);
>> subs(r, [x y z], [111 11 143])
ans =
67
Alternatively, for this specific operation (modulo of a large number that is expressed as a product of small numbers), you can do the computation very easily using the following fact (where ∗ denotes product):
mod(a∗b, z) = mod(mod(a,z)∗mod(b,z), z)
That is, you can apply the modulo operation to factors of your large number and the final result is unchanged. If you choose factors sufficiently small so that they can be represented exactly as double, you can do the computation numerically without any loss of precision.
For example: using the decomposition 111^11 = 111^4*111^4*111^3, since all factors are small enough, gives the correct result:
>> mod((mod(111^4, 143))^2 * mod(111^3, 143), 143)
ans =
67
Similarly, using 111^2 and 111 as factors,
>> mod((mod(111^2, 143))^5 * mod(111, 143), 143)
ans =
67
from the matlab website they recommend using powermod(b, e, m) (b^e mod m)
"If b and m are numbers, the modular power b^e mod m can also be computed by the direct call b^e mod m. However, powermod(b, e, m) avoids the overhead of computing the intermediate result be and computes the modular power much more efficiently." ...
Another way is to use symfun
syms x y z
f = symfun(mod(x^y,z), [x y z])
f(111,11,143)

Operations with large numbers

I have some numbers a_i (for i=1 to 10000).
I need to compute exp(a_i)/sum(exp(a_j)) using matlab.
Of course, it is impossible to calculate straight away. I found some tricks, the most interesting being:
"Suppose we want to find exp(7.0873e002). This will be a large number indeed but still just barely within matlab's capability of direct calculation. However, we can find the separate exponent and mantissa without calling on 'exp' as follows;
a = 7.0873e2;
x = a/log(10);
D = floor(x); % D will be an integer
F = 10^(x-D); % F will lie in 1 <= F < 10
Then D will be the power of ten and F the mantissa
F = 6.27376373225551 % The mantissa
D = 307 % The exponent (power of ten)
Compare that with the direct answer:
exp(a) = 6.273763732256170e+307"
I tried something similar, but the result in may case is Inf:
a = 7.0873e5;
x = a/log(10);
D = floor(x);
F = 10^(x-D);
exp(a) = Inf
Anyone has an idea?
Your answer is in F and D. Because your a is much larger than the example a (i.e. e5 vs e2) which they state is just barely within Matlab's range, yours must be well out of the range and thus becomes inf. But it doesn't matter because D and F hold your answer, you aren't supposed to be checkin g it against exp(a), the example only calculates exp(a) to demonstrate the proof of concept. But the whole point of this code is to give you a way to find exp of giant numbers.
In your case you get
D =
307797
and
F =
3.374110424643062 % Use format long
thus your answer is 3.374110424643062e+307797

Get values for 2 arguments from 1 equation

I have this equation: p = (1 + (q-1)*B*T) ^ (-1/q-1)
The values p, T are known and the diagram p - T makes curbe. I want to calculate q and B so that curbe be as close to straight line is posible.
Some values are:
T p
1 0,999147061
2 0,997121331
3 0,994562513
Is there any way to make matlab (or sth else) to give me the values of B and q ?