How to generate the discrete logarithm within java - java

I am looking for a short and simple algorithm for java that will help with finding the LOGa(x) in a cyclic group Z*p.
my method
would be log(prime_number, a, x)
this would compute the LOGaX in a cyclic group Z*p.
How would i go about doing this in an exhaustive search, or is there any simple way,
so I have gone with the exhaustive search, just to help me understand the discrete log.
//log(p,a,x) will return logaX in the cyclic group Z*p where p is
//prime and a is a generator
public static BigInteger log(BigInteger p,BigInteger a,BigInteger x){
boolean logFound = false;
Random r = new Random();
BigInteger k = new BigInteger(p.bitCount(),r);
while(!logFound){
if(a.modPow(k, p).equals(x)){
logFound = true;
}else{
k = new BigInteger(p.bitCount(),r);
}
}
//i dont think this is right
return a
}
So i want to return the LOGaX of the cyclic group Z*p, am i doing this here or what am i missing?
so i now return k and i am now doing a exhaustive search
#pauloEbermann i dont understand what i should do with k=k.multiply(a).mod(p)
my new code looks like this
//log(p,a,x) will return LOGaX in the cyclic group Z*p where p is
//prime and a is a generator
public static BigInteger log(BigInteger p,BigInteger a,BigInteger x){
boolean logFound = false;
Random r = new Random();
BigInteger k = BigInteger.ONE;
while(!logFound){
if(a.modPow(k, p).equals(x)){
logFound = true;
}else{
k = k.add(BigInteger.ONE);
}
}
return k;
}
with this test data
public static void main(String[] args) {
BigInteger p = new BigInteger("101");
BigInteger a = new BigInteger("3");
BigInteger x = new BigInteger("34");
System.out.println(log(p,a,x));
}
So this returns k = 99
this means that the log3(34) mod 101 is equal to 99 would i be right in saying this?

http://en.wikipedia.org/wiki/Discrete_logarithm lists 7 algorithms for computing the discrete logarithm.
For understanding the discrete logarithm itself, I would use pen and paper and construct a table of all powers of a generator of a small cyclic group. The logarithm is the inverse, so you already have your table for logarithms if you flip the columns.
The naive algorithm works like this, only that you do not store the table but simply loop and multiply by a until the current power matches x and output the number of multiplications plus done plus one as the logarithm of x base a.

Related

How to Generate a Random Number, Which is an Element of Zn (Partially Blind Signature Program) [duplicate]

This question already has answers here:
How to generate a random BigInteger value in Java?
(8 answers)
Closed 2 years ago.
I am trying to implement a partially blind signature scheme in Java from a paper. In equation (1), it requires two random elements r and u to be generated, which must be an element of Zn.
r, u ∈ Zn
This is in an RSA scheme where the modulus n = p.q.
I am not entirely sure how this may be achieved - do I just need to generate a random number, which is not divisible by p nor q? I assume this could be done using BigInteger gcd, but I am not sure this is correct.
So far, the parameters I have generated are as follows (with e being a BigInteger with a value of 3):
do {
p = BigInteger.probablePrime(bitlength, rnd);
q = BigInteger.probablePrime(bitlength, rnd);
n = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
} while (phi.gcd(e).compareTo(BigInteger.ONE) > 0);
d = e.modInverse(phi);
I do not believe the value of phi is relevant to this question, it is just part of my RSA parameter generation.
Ideally, there would be a library that can handle said generation of r, u for me, but I have been unsuccessful finding any.
It is fairly easy to devise an easy and fast algorithm to generate a random element of Zn:
public BigInteger getBiasedRandomModN(BigInteger n) {
BigInteger r = new BigInteger(n.bitLength(), new SecureRandom());
return r.mod(n);
}
The problem with this code is that it is biased. BigInteger only allows us to generate random numbers based on the bit length. If we only generate r based on a bit less than that of n, some values of Zn cannot be reached. If we simply use all of the bits of n but take the mod (as shown in the code) the low values of r will appear more often.
The way to solve that is to generate r so often until it is appears within the bounds of n:
public BigInteger getRandomModN(BigInteger n) {
SecureRandom rnd = new SecureRandom();
BigInteger r;
do {
r = new BigInteger(n.bitLength(), rnd);
} while (r.compareTo(n) >= 0);
return r;
}
Keep in mind that this code might run very long if n is slightly higher than a power of 2. It is best to choose p and q in a certain way that this doesn't happen.

more efficient Fibonacci for BigInteger

I am working on a class project to create a more efficient Fibonacci than the recursive version of Fib(n-1) + Fib(n-2). For this project I need to use BigInteger. So far I have had the idea to use a map to store the previous fib numbers.
public static BigInteger theBigFib(BigInteger n) {
Map<BigInteger, BigInteger> store = new TreeMap<BigInteger, BigInteger>();
if (n.intValue()<= 2){
return BigInteger.ONE;
}else if(store.containsKey(n)){
return store.get(n);
}else{
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
BigInteger val = theBigFib(n.subtract(one)).add(theBigFib(n.subtract(two)));
store.put(n,val);
return val;
}
}
I think that the map is storing more than it should be. I also think this line
BigInteger val = theBigFib(n.subtract(one)).add(theBigFib(n.subtract(two)));
is an issue. If anyone could shed some light on what i'm doing wrong or possible another solution to make it faster than the basic code.
Thanks!
You don't need all the previous BigIntegers, you just need the last 2.
Instead of a recursive solution you can use a loop.
public static BigInteger getFib(int n) {
BigInteger a = new BigInteger.ONE;
BigInteger b = new BigInteger.ONE;
if (n < 2) {
return a;
}
BigInteger c = null;
while (n-- >= 2) {
c = a.add(b);
a = b;
b = c;
}
return c;
}
If you want to store all the previous values, you can use an array instead.
static BigInteger []memo = new BigInteger[MAX];
public static BigInteger getFib(int n) {
if (n < 2) {
return new BigInteger("1");
}
if (memo[n] != null) {
return memo[n];
}
memo[n] = getFib(n - 1).add(getFib(n - 2));
return memo[n];
}
If you just want the nth Fib value fast and efficient.
You can use the matrix form of fibonacci.
A = 1 1
1 0
A^n = F(n + 1) F(n)
F(n) F(n - 1)
You can efficiently calculate A^n using Exponentiation by Squaring.
I believe the main issue in your code is that you create a new Map on each function call. Note that it's still local variable, despite that your method is static. So, you're guaranteed that the store.containsKey(n) condition never holds and your solution is not better than naive. I.e. it still has exponential complexity of n. More precisely, it takes about F(n) steps to get to the answer (basically because all "ones" that make up your answer are returned by some function call).
I'd suggest making the variable a static field instead of a local variable. Then number of calls should become linear instead of exponential and you will see a significant improvement. Other solutions include for loop with three variables which iteratively calculate Fibonacci numbers from 0, 1, 2 up to n-th and the best solutions I know involve matrix exponentiation or explicit formula with real numbers (which is bad for precision), but it's a question better suited for computer science StackExchange website, imho.

Calculate g^r from g^(xr) and x using Java BigInteger

I am trying to implement a ElGamal-like crypto algorithm using Java's BigInteger objects.
q is a safe prime in the form 2p+1
g is a generator of the group
I want to calculate calculate but i am having troubles. Using modInverse i can calculate but if i use this value with modPow i only get wrong results.
The only Example i found on the web is this one where the author uses modInverse to calculate :
BigInteger temp = c1.modPow(a,p);
temp = temp.modInverse(p);
// Print this out.
System.out.println("Here is c1^ -a = "+temp);
I tried some variants (including using modPow with -1) but just cannot get it to work. I think the math should be right but any help is appreciated.
Here is my code:
final static BigInteger q = new BigInteger("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624225795083");
final static BigInteger p = new BigInteger("89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112897541");
final static BigInteger g = new BigInteger("117265744532406309959187881490003058805548219220442880294934902019840205433866971629230940840348591638390822573295684678850519428432938503385192533090834775615734759306193531798190548626342600942782601381215002354918333367595380233608085319759193895027739039963819751637948789055533978566423454988608037601806");
/**
* #param args
*/
public static void main(String[] args) {
BigInteger x = new BigInteger("1143167411333064507035595976576260123572705969224418468247407610494944119131645169381885774886951623439260024159767473519706771572117243833759909829897948112642480886709322424314787175230081859236165044801596619590783556439791012887937120324676147585272259948372265307207312838134079528284932292492131276823586631161241002772401238870376093826305673839039010423270418706970005486897400");
BigInteger r = new BigInteger("28622599320501138892999789676320846139720948572640603818980549097364886339367");
// g^(xr) = g^(x*r)
BigInteger g_xr = g.modPow(x.multiply(r), q);
// 1/x
BigInteger x_inverse = x.modInverse(q);
System.out.println(x.multiply(x_inverse).mod(q)); // -> 1 --> correct
// g^r = g^(xr) ^ (1/x)
BigInteger g_r = g_xr.modPow(x_inverse, q); // FIXME: wrong result
System.out.println(g_r); //result
System.out.println(g.modPow(r, q)); // expected result
}
The multiplicative group is of order q−1 — that is to say, gq−1 = 1 mod q. Thus, what you need to find is not the inverse of x modulo q, but modulo q−1.
(Also, user1008646 is right that gxr = (gx)r ≠ gxgr = gx+r.)
Edit: To summarize the discussion below, the paper describing the algorithm the OP is implementing has a typo: instead of working in , he needs to work in the order-p subgroup of it. (Also, the paper is using p and q in the opposite sense to the way the OP is using them here.)
I'm not familiar with BigInteger, but I believe g^x * g^r = g^(x+r).
It looks like you're basing your code on g^x * g^r = g^(x*r).
Does that help?

Random permutation of integers using a random number generator

This is my homework assignment:
Random r = new Random();
public int get100RandomNumber() {
return 1 + r.nextInt(100);
}
You are given a pre-defined function named getrand100() (above) which
returns an integer which is one random number from 1-100. You can call
this function as many times as you want but beware that this function
is quite resource intensive. You cannot use any other random
generator. You cannot change the definition of getrand100().
Output: Print numbers 1-20 in random order. (Not 20 random numbers)
What I have tried..
public class MyClass {
static Random r = new Random();
static HashSet<Integer>;
public static void main(String args[]) {
myMethod();
System.out.println(s);
}
public static void myMethod() {
boolean b = false;
s = new HashSet<Integer>();
int i = getRand100();
if (i >= 20)
i = i % 20;
int j = 0;
int k, l;
while (s.size() <= 20)
{
System.out.println("occurence no" + ++j);
System.out.println("occurence value" + i);
b = s.add(i);
while (!b) {
k = ++i;
if(k<=20)
b = s.add(k);
if(b==true)
break;
if (!b) {
l = --i;
if(i>=1&&i<=20)
b = s.add(l);
if(b==true)
break;
}
}
}
System.out.println(s);
}
public static int getRand100()
{
return r.nextInt(100) + 1;
}
}
Thanks for any help!
I believe you are asking how to use a random number generator to print out the numbers 1 to 20 in a random order. This is also known as a "random permutation". The Fischer-Yates shuffle is such an algorithm.
However, to implement the algorithm, you first of all need a random number generator that can pick one out of N items with equal probability where N ranges from 2 up to the size of the set to shuffle, while you only have one that can pick one out of 100 items with equal probability. That can easily be obtained by a combination of modulo arithmetic and "rerolling".
Assuming you are allowed to use the ArrayList class, I'd recommend filling a list with the numbers you want (1 to 20 in this case), then randomly pick numbers from the list and remove them. Using getRand100() % theList.size() should be sufficiently random for your cause and you only need to call it 19 times. When only one element is left, there's no need to "randomly" pick it from the list anymore. ;-)
I believe that I've come up with a way to convert any number between 1 and n! (assuming the number of items is known) to a unique permutation of n items.
In essence, this allows for an "immediate" randomization of an entire deck without having to use any shuffling algorithms. For now, it runs in O(n^2) and requires using BigInteger packages (ie. in Java or Javascript), but I'm looking for ways to optimize the runtime (although, honestly 2500 iterations is nothing these days anyway). Regardless, when given at least 226 bits of valid, random data, the function is able to generate a shuffled array of 52 integers in under 10 ms.
The method is similar to that used to convert a decimal number to binary (continually dividing by 2, etc). I'm happy to provide my code upon request; I find it interesting that I haven't come across it before.

BigIntegers to the power of BigIntegers

I am trying to implement either the Fermat, Miller-Rabin, or AKS algorithm in Java using the BigInteger class.
I think I have the Fermat test implemented except that the BigInteger class doesn't allow taking BigIntegers to the power of BigIntegers (one can only take BigIntegers to the power of primitive ints). Is there a way around this?
The problematic line is denoted in my code:
public static boolean fermatPrimalityTest(BigInteger n)
{
BigInteger a;
Random rand = new Random();
int maxIterations = 100000;
for (int i = 0; i < maxIterations; i++) {
a = new BigInteger(2048, rand);
// PROBLEM WITH a.pow(n) BECAUSE n IS NOT A BigInteger
boolean test = ((a.pow(n)).minus(BigInteger.ONE)).equals((BigInteger.ONE).mod(n));
if (!test)
return false;
}
return true;
}
I think BigInteger.modPow might be what you're looking for. Note the "mod m" in Fermat's test.
One of the primality tests is built into BigInteger.isProbablePrime(). Not sure which one, you'd have to look at the source.
Also, you can raise a number to a power by multiplying. For example: 2^100 = 2^50 * 2^50. So pull out pieces of your BigInteger power and loop until you've used it up. But are you sure you don't mean to use BigInteger.modPow(), which takes BigIntegers? It looks like you are, based on your test.
You'll have to implement your own pow() method. Look at the sources of BigInteger.pow() as a starting point.

Categories