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

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?

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.

How to calculate 2 to-the-power N where N is a very large number

I need to find 2 to-the-power N where N is a very large number (Java BigInteger type)
Java BigInteger Class has pow method but it takes only integer value as exponent.
So, I wrote a method as follows:
static BigInteger twoToThePower(BigInteger n)
{
BigInteger result = BigInteger.valueOf(1L);
while (n.compareTo(BigInteger.valueOf((long) Integer.MAX_VALUE)) > 0)
{
result = result.shiftLeft(Integer.MAX_VALUE);
n = n.subtract(BigInteger.valueOf((long) Integer.MAX_VALUE));
}
long k = n.longValue();
result = result.shiftLeft((int) k);
return result;
}
My code works fine, I am just sharing my idea and curious to know if there is any other better idea?
Thank you.
You cannot use BigInteger to store the result of your computation. From the javadoc :
BigInteger must support values in the range -2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values outside of that range.
This is the reason why the pow method takes an int. On my machine, BigInteger.ONE.shiftLeft(Integer.MAX_VALUE) throws a java.lang.ArithmeticException (message is "BigInteger would overflow supported range").
Emmanuel Lonca's answer is correct. But, by Manoj Banik's idea, I would like to share my idea too.
My code do the same thing as Manoj Banik's code in faster way. The idea is init the buffer, and put the bit 1 in to correct location. I using the shift left operator on 1 byte instead of shiftLeft method.
Here is my code:
static BigInteger twoToThePower(BigInteger n){
BigInteger eight = BigInteger.valueOf(8);
BigInteger[] devideResult = n.divideAndRemainder(eight);
BigInteger bufferSize = devideResult[0].add(BigInteger.ONE);
int offset = devideResult[1].intValue();
byte[] buffer = new byte[bufferSize.intValueExact()];
buffer[0] = (byte)(1 << offset);
return new BigInteger(1,buffer);
}
But it still slower than BigInteger.pow
Then, I found that class BigInteger has a method called setBit. It also accepts parameter type int like the pow method. Using this method is faster than BigInteger.pow.
The code can be:
static BigInteger twoToThePower(BigInteger n){
return BigInteger.ZERO.setBit(n.intValueExact());
}
Class BigInteger has a method called modPow also. But It need one more parameter. This means you should specify the modulus and your result should be smaller than this modulus. I did not do a performance test for modPow, but I think it should slower than the pow method.
By using repeated squaring you can achieve your goal. I've posted below sample code to understand the logic of repeated squaring.
static BigInteger pow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE;
while (exponent.signum() > 0) {
if (exponent.testBit(0)) result = result.multiply(base);
base = base.multiply(base);
exponent = exponent.shiftRight(1);
}
return result;
}
An interesting question. Just to add a little more information to the fine accepted answer, examining the openjdk 8 source code for BigInteger reveals that the bits are stored in an array final int[] mag;. Since arrays can contain at most Integer.MAX_VALUE elements this immediately puts a theoretical bound on this particular implementation of BigInteger of 2(32 * Integer.MAX_VALUE). So even your method of repeated left-shifting can only exceed the size of an int by at most a factor of 32.
So, are you ready to produce your own implementation of BigInteger?

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.

Java Card RSAPrivateCrtKey Private Exponent "d"

Base on http://www.win.tue.nl/pinpasjc/docs/apis/jc222/javacard/security/RSAPrivateCrtKey.html I could get :
P, the prime factor p
Q, the prime factor q
PQ = q-1 mod p
DP1 = d mod (p - 1)
DQ1 = d mod (q - 1)
by calling every getter. But, how do I get the private exponent "d"? Should I do the calculation of private exponent "d" by manual, or is there any easy way to get private exponent "d" from RSAPrivateCrtKey?
This is just for exercise anyway, so it won't do any harm.
EDIT:
I really need private exponent "d" to make a PEM file from XML. FYI, this is just an exercise, I just want to proof the truth of RSAPrivateCrtKey in Java Card is the same with RSAPrivateCrtKey in real world (as in OpenSSL, etc). Is there any other way to proof it? Or, is there any other way to make PEM file from RSAPrivateCrtKey without private exponent "d"?
This one should work (derived from Bouncy Castle's RSAKeyPairGenerator.java and verified with one RSA private key):
public static BigInteger getPrivateExponent(byte[] publicExponentBytes, byte[] pBytes, byte[] qBytes) {
BigInteger e = new BigInteger(1, publicExponentBytes);
BigInteger p = new BigInteger(1, pBytes);
BigInteger q = new BigInteger(1, qBytes);
BigInteger pSub1 = p.subtract(BigInteger.ONE);
BigInteger qSub1 = q.subtract(BigInteger.ONE);
BigInteger phi = pSub1.multiply(qSub1);
return e.modInverse(phi);
}
Good luck!
You won't need the private exponent since you build your key pair using javacard.security.KeyBuilder with TYPE_RSA_CRT_PRIVATE option. Calling buildKey method would then return an instance of RSAPrivateCrtKey, which have enough public methods to perform any computation.
If you want some details about the algorithm itself (and how can you find d, p, q, etc.), you can find numerous articles in the web, such as this one:
http://www.techscience.com/doi/10.3970/icces.2008.005.255.pdf

How to generate the discrete logarithm within 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.

Categories