Elliptic Curve Multiplication - java

I am having trouble getting the correct results when performing multiplication of elliptic curve points. I have been able to get addition working but when trying to multiply a point I am confused on the proper way to add to the previous values. I also am doing this without Javas EC points.
Example:
Expected: 12(2,7)=(153,36)
Results: 12(2,7)=(55,121)
private static int a = 11;
private static int mod = 167;
public static void main(String[] args) {
int[] p1 = { 2, 7 };
int[] p2 = addPoints(new int[] { 1, 4 }, new int[] { 3, 1 });
System.out.println("ADDING: (" + p2[0] + "," + p2[1] + ")");
int[] p3 = multiplyPoint(12, p1);
System.out.println("MULTIPLYING: (" + p3[0] + "," + p3[1] + ")");
}
public static int[] multiplyPoint(int iterations, int[] point) {
int[] newPoint = new int[2];
for (int i = 1; i < iterations; i++) {
System.out.println("(" + newPoint[0] + "," + newPoint[1] + ")");
newPoint = addPoints(newPoint, point);
}
return newPoint;
}
public static int[] addPoints(int[] p1, int[] p2) {
int[] p3 = { 0, 0 };
int m;
if (p1[0] == p2[0] && p1[1] == p2[1])
m = mod(((3 * p1[0] * p1[0]) + a) / (2 * p1[1]), mod);
else
m = mod((int) p2[1] - p1[1], mod) / mod(p2[0] - p1[0], mod);
p3[0] = mod((int) (Math.pow(m, 2) - p1[0] - p2[0]), mod);
p3[1] = mod((m * (p1[0] - p3[0]) - p1[1]), mod);
return p3;
}
/**
* Used because Java's default modulus operator does not give the correct
* value for negative numbers
*
* #param value
* Number to perform the mod operation on
* #param divisor
* Mod by
* #return The modulus of number mod divisor... Should now work for any
* number
*/
public static int mod(int value, int divisor) {
return ((value % divisor + divisor) % divisor);
}
Thanks
EDIT:
Still unsuccessful
public static int[] multiplyPoint(int iterations, int[] point) {
int[] newPoint = new int[2];
String binary = Integer.toBinaryString(iterations);
System.out.println(binary);
for (int i = 0; i < binary.length(); i++) {
System.out.println("(" + newPoint[0] + "," + newPoint[1] + ")");
if (binary.charAt(i) == '1')
newPoint = addPoints(newPoint, point);
point = doublePoint(point);
}
return newPoint;
}
public static int[] doublePoint(int[] point) {
int[] newPoint = new int[2];
int m = mod(((3 * point[0] * point[0]) + a) / (2 * point[1]), mod);
newPoint[0] = mod((int) (Math.pow(m, 2) - point[0] - point[0]), mod);
newPoint[1] = mod((m * (point[0] - newPoint[0]) - point[1]), mod);
return newPoint;
}
public static int[] addPoints(int[] p1, int[] p2) {
int[] p3 = new int[2];
int m = mod((int) p2[1] - p1[1], mod) / mod(p2[0] - p1[0], mod);
p3[0] = mod((int) (Math.pow(m, 2) - p1[0] - p2[0]), mod);
p3[1] = mod((m * (p1[0] - p3[0]) - p1[1]), mod);
return p3;
}

Related

Math in Java(Combinatorics)

My problem is:
My math formula is:
In this case X = N; Y = L;U = K;
public class Play {
public static void main(String args[]) {
//n!(n−k−1)!
int n = 10;
int k =2;
int l = 12;
long result;
result = (calculaFator(n) / calculaFator(n-k-1));
result= (long) (result * Math.pow((n-k),(l-k)-1));
System.out.println(result);
}
public static long calculaFator(long x) {
long f = x;
while (x > 1) {
f = f * (x - 1);
x--;
}
return f;
}
}
It should be 721599986, but it is giving me 96636764160
I have some samples:
With n=10, k=2, l=12 it should be 721599986
With n=10, k=2, l=16 it should be 626284798
With n=10, k=1, l=20 it should be 674941304
With n=5, k=2, l=8 it should be 10800
The java codes is working according to your stated formula.
It seems like the formula is wrong rather than the codes. (or expected results or your x,u,y mapping to n,l,k is incorrect?)
int x = 10;
int u = 2;
int y = 12;
long numerator = calculaFator(x);
long denominator = calculaFator(x - u - 1);
int xu1 = x - u - 1;
long result = numerator / denominator;
System.out.println();
System.out.println(x + "!= numerator: " + numerator); //10!= numerator: 3_628_800
System.out.println(xu1 + "!= denominator: " + denominator); //7!= denominator: 5_040
System.out.println("result1: " + result); //result1: 720 (correct)
int xu = x - u;
int yu1 = y - u - 1;
double remainderPlaylist = Math.pow(xu, yu1);
System.out.println(xu + "^" + yu1 + " = " + remainderPlaylist);//8^9 = 1.34217728E8
System.out.println(xu + "^" + yu1 + " = " + (long) remainderPlaylist);//8^9 = 134_217_728 (correct)
long mul = (long) (result * remainderPlaylist);
System.out.println(result + "x" + (long)remainderPlaylist + " = " + mul); //720x134_217_728 = 96_636_764_160 (mathematically correct)

GCD / LCM of two numbers to be evaluated from the input numbers itself

Considering the input given to us as a=21, b=36 and GCD (a,b) is d=3.
If we were supposed to achieve the GCD by solving the equation a * x + b * y = d. How can we evaluate the numerous combinations of positive and negative integers for x & y in this equation to fetch the result that satisfies this equation.
Eg: a=21, b=36, (GCD) d=3
21 * x + 36 * y = 3
x = ? and y = ?
Sample answer: x=-5,y=3
How can I do it in JAVA?
You can do it by Extended Euclidean algorithm. The implementation is here
public class ExtendedEuclid {
// return array [d, a, b] such that d = gcd(p, q), ap + bq = d
static int[] gcd(int p, int q) {
if (q == 0)
return new int[] { p, 1, 0 };
int[] vals = gcd(q, p % q);
int d = vals[0];
int a = vals[2];
int b = vals[1] - (p / q) * vals[2];
return new int[] { d, a, b };
}
public static void main(String[] args) {
int p = Integer.parseInt(args[0]);
int q = Integer.parseInt(args[1]);
int vals[] = gcd(p, q);
System.out.println("gcd(" + p + ", " + q + ") = " + vals[0]);
System.out.println(vals[1] + "(" + p + ") + " + vals[2] + "(" + q + ") = " + vals[0]);
}
}
Input: int vals[] = gcd(21, 36);
Output:
gcd(21,36) = 3
-5(21) + 3(36) = 3

Generating two random prime numbers in JAVA

I'm trying to generate two random prime numbers in JAVA, however, I want the loop to keep repeating itself until both of those two variables are prime numbers, and then they output themselves.
The p and q variables are randomized by the Math.random() function and are in the range of 2 to 128 (excluding the 128).
Here is my code:
int pRandom = (int) (Math.random() * (127 - 2) + 2);
int qRandom = (int) (Math.random() * (127 - 2) + 2);
int p = pRandom;
int q = qRandom;
for (int i = 1; i < p; i++) {
boolean isPPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPPrime = false;
break;
}
}
if (isPPrime){
JOptionPane.showMessageDialog(null, "YAY!");
break;
}
System.out.println("P value: " + p + "\n" + "Q value: " + q);
}
Here is what you want:
public class RandomPrimeGenerator {
public static void main(String[] args) {
while (true) {
int pRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(pRandom)){
System.out.println("Got Random Prime P :"+pRandom);
break;
}
}
while(true){
int qRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(qRandom)){
System.out.println("Got Random Prime Q :"+qRandom);
break;
}
}
}
private static boolean isPrime(int n) {
int i;
for(i=2;i<=Math.sqrt(n);i++){
if(n % i == 0){
return false;
}
}
return true;
}
}

Java optimized Cramers rule function

Recently learned about Cramers rule in precalculus, and decided to make an algorithm in Java to help me understand it better.
The following code works 100% correctly, however it does not use any sort of for loop to do what it does in a much simpler fashion.
Question: Is there a more elegant implementation of Cramers Rule in Java?
I'm thinking that making a basic determinant method, and then doing some column swapping for when I need to take the determinant of Dx, Dy, and Dz. (for Dx, swap column 4 with column 1 of the original matrix, then take determinant and divide by original determinant.)
This sound good?
public static void main(String[] args) {
int[][] matrix = new int[3][3];
matrix[0] = new int[] { 3, 5, -1, -2 };
matrix[1] = new int[] { 1, -4, 2, 13 };
matrix[2] = new int[] { 2, 4, 3, 1 };
int[] r = crame(matrix);
info("x: " + r[0] + ", y: " + r[1] + ", z: " + r[2]);
for(int i = 0; i < matrix.length; i++) {
int[] base = matrix[i];
if(check(base, r, base[3])) {
info("System " + (i+1) + " checks!");
} else {
info("System " + (i+1) + " fails check!");
}
}
}
public static int[] crame(int[][] m) {
int[] result;
if (m.length == 2) {
result = new int[2];
int D = (m[0][0] * m[1][1]) - (m[1][0] * m[0][1]);
int Dx = (m[0][2] * m[1][1]) - (m[1][2] * m[0][1]);
int Dy = (m[0][0] * m[1][2]) - (m[1][0] * m[0][2]);
result[0] = (int) (Dx / D);
result[1] = (int) (Dy / D);
} else if (m.length == 3) {
result = new int[3];
int D = (((m[0][2] * m[1][1] * m[0][2]) + (m[2][1] * m[1][2] * m[0][0]) + (m[2][2]
* m[1][0] * m[0][2])) - ((m[0][0] * m[1][1] * m[2][2])
+ (m[0][1] * m[1][2] * m[0][2]) + (m[0][2] * m[1][0] * m[2][1])));
int Dx = (((m[2][3] * m[1][1] * m[0][2]) + (m[2][1] * m[1][2] * m[0][3]) + (m[2][2]
* m[1][3] * m[0][1])) - ((m[0][3] * m[1][1] * m[2][2])
+ (m[0][1] * m[1][2] * m[2][3]) + (m[0][2] * m[1][3] * m[2][1])));
int Dy = (((m[2][0] * m[1][3] * m[0][2]) + (m[2][3] * m[1][2] * m[0][3]) + (m[2][2]
* m[1][0] * m[0][3])) - ((m[0][0] * m[1][3] * m[2][2])
+ (m[0][3] * m[1][2] * m[2][0]) + (m[0][2] * m[1][0] * m[2][3])));
int Dz = (((m[2][0] * m[1][1] * m[0][3]) + (m[2][1] * m[1][3] * m[0][0]) + (m[2][3]
* m[1][0] * m[0][1])) - ((m[0][0] * m[1][1] * m[2][3])
+ (m[0][1] * m[1][3] * m[2][0]) + (m[0][3] * m[1][0] * m[2][1])));
result[0] = (int) (Dx / D);
result[1] = (int) (Dy / D);
result[2] = (int) (Dz / D);
} else {
return new int[] {};
}
return result;
}
public static int product(int[] a, int[] b) {
int p = 0;
int[] fin = new int[(a.length -1)];
for(int x = 0; x < fin.length; x++) {
fin[x] = a[x] * b[x];
}
for (int f : fin) {
p += f;
}
return p;
}
public static boolean check(int[] a, int[] b, int z) {
return product(a, b) == z;
}
public static void info(String log) {
System.out.println(log);
}
My question pertains to the specific algorithm that can be used to solve systems of equations using Cramers rule only, is there any algorithm that is more elegant? The function is only designed for square matrices.
This is not a homework assignment, after HS I will be studying CS and I've been working on developing algorithms as preliminary practice.
Thank you for checking this out
First of, there is one way in which Cramers rule is perfect: It gives the algebraic solution of a linear system as a rational function in its coefficients.
However, practically, it has its limits. While the most perfect formula for a 2x2 system, and still good for a 3x3 system, its performance, if implemented in the straightforward way, deteriorates with each additional dimension.
An almost literal implementation of Cramers rule can be achieved with the Leverrier-Faddeev algorithm a b. It only requires the computation of matrix products and matrix traces, and manipulations of the matrix diagonal. Not only does it compute the determinant of the matrix A (along with the other coefficients of the characteristic polynomial), it also has the adjugate or co-factor matrix A# in its iteration matrix. The interesting fact about this matrix is that it allows to write the solution of A*x=b as (A#*b)/det(A), that is, the entries of A#*b already are the other determinants required by Cramers rule.
Leverrier-Faddeev requires n4+O(n3) operations. The same results can be obtained by the more complicated Samuelson-Berkowitz algorith, which has one third of that complexity, that is n4/3+O(n3).
The computation of the determinants required in Cramers rule becomes downright trivial if the system (A|b) is first transformed into triangular form. That can be achieved by Gauß elimination, aka LU decomposition (with pivoting for numerical stability) or the QR decomposition (easiest to debug should be the variant with Givens rotations). The efficient application of Cramers rule is then backward substitution in the triangular system.
Your method sounds good to me at least; however, I just may not be aware of any more efficient methods. The not-fun part may be figuring out how to best implement the determinant-calculating method, as apparently it's not an inexpensive operation.
But once you know that that's working, the rest sounds pretty OK to me. Cache the determinant of the original matrix, substitute in columns, etc.
Figured out exactly how to do this effectively.
http://sandsduchon.org/duchon/math/determinantJava.html
Provides a method for seamless determinants, and mentions matrix decomposition. I have not learned this yet as it's not a HS level concept however I did some problems using it and it's a solid method.
Final Code:
public static void main(String[] args) {
int[][] matrix = new int[3][3];
matrix[0] = new int[] { 3, 5, -1, -2 };
matrix[1] = new int[] { 1, -4, 2, 13 };
matrix[2] = new int[] { 2, 4, 3, 1 };
int[] r = crame(matrix);
info("x: " + r[0] + ", y: " + r[1] + ", z: " + r[2]);
for (int i = 0; i < matrix.length; i++) {
int[] base = matrix[i];
if (check(base, r, base[3])) {
info("System " + (i + 1) + " checks!");
} else {
info("System " + (i + 1) + " fails check!");
}
}
}
public static int getDet(int[][] a) {
int n = a.length - 1;
if (n < 0)
return 0;
int M[][][] = new int[n + 1][][];
M[n] = a; // init first, largest, M to a
// create working arrays
for (int i = 0; i < n; i++)
M[i] = new int[i + 1][i + 1];
return getDet(M, n);
} // end method getDecDet double [][] parameter
public static int getDet(int[][][] M, int m) {
if (m == 0)
return M[0][0][0];
int e = 1;
// init subarray to upper left mxm submatrix
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
M[m - 1][i][j] = M[m][i][j];
int sum = M[m][m][m] * getDet(M, m - 1);
// walk through rest of rows of M
for (int i = m - 1; i >= 0; i--) {
for (int j = 0; j < m; j++)
M[m - 1][i][j] = M[m][i + 1][j];
e = -e;
sum += e * M[m][i][m] * getDet(M, m - 1);
} // end for each row of matrix
return sum;
} // end getDecDet double [][][], int
public static int[] crame(int[][] m) {
int[] result;
if (m.length == 2) {
result = new int[m.length];
int D = getDet(m);
for (int i = 0; i < m.length; i++) {
result[i] = getDet(slide(m, i, m.length)) / D;
}
} else if (m.length == 3) {
result = new int[m.length];
int D = getDet(m);
for (int i = 0; i < m.length; i++) {
result[i] = (getDet(slide(m, i, m.length)) / D);
}
} else {
return new int[] {};
}
return result;
}
public static int[][] slide(int[][] base, int col, int fin) {
int[][] copy = new int[base.length][];
for (int i = 0; i < base.length; i++) {
int[] aMatrix = base[i];
int aLength = aMatrix.length;
copy[i] = new int[aLength];
System.arraycopy(aMatrix, 0, copy[i], 0, aLength);
}
for (int i = 0; i < base.length; i++) {
copy[i][col] = base[i][fin];
}
return copy;
}
public static int product(int[] a, int[] b) {
int p = 0;
int[] fin = new int[(a.length - 1)];
for (int x = 0; x < fin.length; x++) {
fin[x] = a[x] * b[x];
}
for (int f : fin) {
p += f;
}
return p;
}
public static boolean check(int[] a, int[] b, int z) {
return product(a, b) == z;
}
public static void info(String log) {
System.out.println(log);
}

TEA Encryption in JAVA

I want to encrypt 4 number, but so far only 2 of them are being encrypted. I have tried placing the encrypt method into the loop but it doesnt encrypt and decrypt more than 2 number. Anyone is able to help on this?
public class TEA {
private static int delta = 0x9E3779B9; /* a key schedule constant */
private static int[] key = { 78945677, 87678687, 234234, 234234 };
public void encrypt(int[] v, int[] k) {
int v0 = v[0], v1 = v[1], sum = 0, n = 32;
int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
while (n-- > 0) {
sum += delta;
v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1);
v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3);
}
v[0] = v0;
v[1] = v1;
System.out.println(v0 + "," + v1);
}
public void decrypt(int[] v, int[] k) {
int v0 = v[0], v1 = v[1], sum = 0xC6EF3720, n = 32; /* set up */
int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
while (n-- > 0) {
v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3);
v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1);
sum -= delta;
}
v[0] = v0;
v[1] = v1;
System.out.println(v0 + "," + v1);
}
public static void main(String[] args) throws IOException {
TEA tea = new TEA();
int n = 0;
int cc[] = new int[100];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("Enter 4 number to encrypt: ");
n = input.nextInt();
cc[i] = n;
}
tea.encrypt(cc, key);
tea.decrypt(cc, key);
}
}
Both encrypt() and decrypt() work with first two elements.
So you have to either shift arrays in a calling method in cycle, or introduce a cycle over consecutive pairs in encrypt/decrypt method like
for (int idx = 0; idx < v.length; idx *= 2)
{
int v0 = v[idx], v1 = v[idx + 1], sum = 0, n = 32;
...
}
UPDATE
According to Wikipedia example, the method expects only two integers (and not any length array). You need pass your numbers by pairs, like
for (int idx = 0; idx < 4; idx =* 2)
{
int[] tmp = {cc[idx], cc[idx + 1};
tea.encrypt(tmp, key);
cc[idx] = tmp[0];
cc[idx + 1] = tmp[1];
}
As a result, for each pair of integers you will receive another pair of integers but encrypted.

Categories