I have encrypted 2 numbers using paillier cryptosystem. encrypted value of the numbers are bigInteger when I want to divide them the value is the decimal number
for example: first encrypted value of a 9 is 12446486760457687016046
and encrypted value of 3 is 98647617673416817617. the result of division is likely to be decimal. and final result is 0 in this case because paillier get bigInteger as parameter. how can I divide them?
public class Paillier {
/**
* p and q are two large primes.
* lambda = lcm(p-1, q-1) = (p-1)*(q-1)/gcd(p-1, q-1).
*/
private BigInteger p, q, lambda;
/**
* n = p*q, where p and q are two large primes.
*/
public BigInteger n;
/**
* nsquare = n*n
*/
public BigInteger nsquare;
/**
* a random integer in Z*_{n^2} where gcd (L(g^lambda mod n^2), n) = 1.
*/
private BigInteger g;
/**
* number of bits of modulus
*/
private int bitLength;
/**
* Constructs an instance of the Paillier cryptosystem.
* #param bitLengthVal number of bits of modulus
* #param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
*/
public Paillier(int bitLengthVal, int certainty) {
KeyGeneration(bitLengthVal, certainty);
}
/**
* Constructs an instance of the Paillier cryptosystem with 512 bits of modulus and at least 1-2^(-64) certainty of primes generation.
*/
public Paillier() {
KeyGeneration(512, 64);
}
/**
* Sets up the public key and private key.
* #param bitLengthVal number of bits of modulus.
* #param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
*/
public void KeyGeneration(int bitLengthVal, int certainty) {
bitLength = bitLengthVal;
/*Constructs two randomly generated positive BigIntegers that are probably prime, with the specified bitLength and certainty.*/
p = new BigInteger(bitLength / 2, certainty, new Random());
q = new BigInteger(bitLength / 2, certainty, new Random());
n = p.multiply(q);
nsquare = n.multiply(n);
g = new BigInteger("2");
lambda = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)).divide(
p.subtract(BigInteger.ONE).gcd(q.subtract(BigInteger.ONE)));
/* check whether g is good.*/
if (g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).gcd(n).intValue() != 1) {
System.out.println("g is not good. Choose g again.");
System.exit(1);
}
}
/**
* Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function explicitly requires random input r to help with encryption.
* #param m plaintext as a BigInteger
* #param r random plaintext to help with encryption
* #return ciphertext as a BigInteger
*/
public BigInteger Encryption(BigInteger m, BigInteger r) {
return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);
}
/**
* Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function automatically generates random input r (to help with encryption).
* #param m plaintext as a BigInteger
* #return ciphertext as a BigInteger
*/
public BigInteger Encryption(BigInteger m) {
BigInteger r = new BigInteger(bitLength, new Random());
return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);
}
/**
* Decrypts ciphertext c. plaintext m = L(c^lambda mod n^2) * u mod n, where u = (L(g^lambda mod n^2))^(-1) mod n.
* #param c ciphertext as a BigInteger
* #return plaintext as a BigInteger
*/
public BigInteger Decryption(BigInteger c) {
BigInteger u = g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).modInverse(n);
return c.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).multiply(u).mod(n);
}
/**
* main function
* #param str intput string
*/
public static void main(String[] str) {
/* instantiating an object of Paillier cryptosystem*/
Paillier paillier = new Paillier();
BigInteger o1 = (paillier.Encryption(new BigInteger("9")));
BigInteger o2 = (paillier.Encryption(new BigInteger("3")));
BigInteger od = o2.divide(o1);
System.out.println(paillier.Decryption(od));
As I explained before, in cryptographic applications, it is common to use the multiplicative inverse instead of division.
In grade school, I learned to divide 9 by 3: 9 ÷ 3 = 3. A bit later I learned that multiplying by the reciprocal of the divisor would do the same thing: 9 × ⅓ = 3. For rational numbers, ⅓ is the multiplicative inverse of 3: 3 × ⅓ = 1
In modular arithmetic, the multiplicative inverse is analogous to a reciprocal. Suppose I'm working with numbers modulo 256. I want to "divide" by 3. As above, I can do it using the multiplicative inverse of the "divisor". 3 × 171 mod 256 = 1, so 171 is the multiplicative inverse of 3. But wait, 9 × 171 = 1539. Shouldn't it be 3? Oh, wait, we forgot that we are working modulo 256: 1539 mod 256 = 3.
In your example, you have two numbers that could be used as a modulus, n or nsquare. I believe that if you study a bit, you'll discover which to use when performing homomorphic arithmetic with Paillier. Then you can use the modInverse() function to perform your "subtraction".
Paillier paillier = new Paillier();
BigInteger o1 = (paillier.Encryption(new BigInteger("9")));
BigInteger o2 = (paillier.Encryption(new BigInteger("3")));
BigInteger od = o1.multiply(o2.modInverse(???));
System.out.println(paillier.Decryption(od));
Related
I have written my own routines for manipulating vectors and matrices including a number of math utilities.
I'd far rather use JavaFX without its scene graph and use my own routines, is it possible to manipulate just a single (4x4) matrix for each Shape3D you wish to render?
In order to Transform a Node directly rather than making it a child of a scene graph of transforms (for example and X,Y,Z axis rotation and a translation etc) you can use a single Affine matrix to do all the transformations (orientation/translation)
For example parent a Shape3D to this class then parent the Pivot to the root of the scene
package uk.co.bedroomcoders.jfx3dedit;
import javafx.scene.Group;
import javafx.scene.transform.Affine;
import javafx.scene.transform.MatrixType;
import com.sun.javafx.geom.Vec3d;
public class Pivot extends Group {
private final double[] idt={1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
public double rx,ry,rz;
public Affine matrix=new Affine(idt,MatrixType.MT_3D_4x4,0);
public Pivot() {
super();
getTransforms().setAll(matrix);
}
public Pivot(double x, double y, double z) {
this();
matrix.setTx(x);
matrix.setTy(y);
matrix.setTz(z);
}
public void setPosition(double x, double y, double z) {
matrix.setTx(x);
matrix.setTy(y);
matrix.setTz(z);
}
public Vec3d getPosition() {
return new Vec3d(matrix.getTx(),matrix.getTy(),matrix.getTz());
}
// set to eular rotation retaining translation (TODO reimplement fromQuat)
public void updateFromEular(double rx, double ry, double rz) {
double cx = Math.cos(rx);
double cy = Math.cos(ry);
double cz = Math.cos(rz);
double sx = Math.sin(rx);
double sy = Math.sin(ry);
double sz = Math.sin(rz);
matrix.setMxx(cy*cz); matrix.setMxy((sx * sy * cz) + (cx * sz)); matrix.setMxz(-(cx * sy * cz) + (sx * sz));
matrix.setMyx(-cy*sz); matrix.setMyy(-(sx * sy * sz) + (cx * cz)); matrix.setMyz((cx * sy * sz) + (sx * cz));
matrix.setMzx(sy); matrix.setMzy(-sx*cy); matrix.setMzz(cx*cy);
}
// make this pivot face the a point
public void lookAt(Vec3d centre, Vec3d up) {
final Vec3d f = new Vec3d(), s = new Vec3d(), u = new Vec3d();
final Vec3d t = new Vec3d(), eye = new Vec3d();
eye.set(matrix.getTx(),matrix.getTy(),matrix.getTz());
f.set(centre);
f.sub(eye);
f.normalize();
up.normalize();
t.set(f);
s.cross(t,up);
s.normalize();
t.set(s);
u.cross(t,f);
u.normalize();
matrix.setMxx( s.x); matrix.setMxy( u.x); matrix.setMxz( f.x);
matrix.setMyx( s.y); matrix.setMyy( u.y); matrix.setMyz( f.y);
matrix.setMzx( s.z); matrix.setMzy( u.z); matrix.setMzz( f.z);
}
}
I'm just curious why row starts with 1 and column with 0. Is there any special reason or am I missing something important? Why not just both start with 0 or 1 (consistency).
/**
* Set a cell value by using numeric cell coordinates
*
* #param string $pColumn Numeric column coordinate of the cell (A = 0)
* #param string $pRow Numeric row coordinate of the cell
* #param mixed $pValue Value of the cell
* #param bool $returnCell Return the worksheet (false, default) or
the cell (true)
* #return PHPExcel_Worksheet|PHPExcel_Cell
Depending on the last parameter being specified
*/
public function setCellValueByColumnAndRow($pColumn = 0,
$pRow = 1,
$pValue = null,
$returnCell = false)
{
$cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue);
return ($returnCell) ? $cell : $this;
}
The reason is backward compatibility with earlier versions after what was originally a bad decision based on the old PEAR SEW that also had zero-based column IDs
While preparing for an exam I came across a question about hash tables.
I am given a table of length 11 with the following hash function:
h(k,i) = ( k mod 13 + i * (1 + k mod 7) ) mod 11
The hash table is then resized to size 12. So the new hash function becomes:
h'(k,i) = ( k mod 13 + i * (1 + k mod 7) ) mod 12
Which problems occur?
The problem is that the hash function becomes worse.
In the first case, the distribution of different combinations of k and i is very even among the 11 hash bins. In the second case, the distribution is not so even - particularly, the number of combinations of k and i for which the result of the hash function will be 0 is noticably higher.
Of course, during an exam, one would probably have to argue why it is this way. It's somehow related to
k mod 13 being a value between 0 and 12
k mod 7 being a value between 0 and 6 (which divides 12)
maybe, somehow: 11 is a prime number and 12 has many divisors...
but (at least for me) it is hard to find a convincing reasoning that goes beyond these trivial insights. Maybe you have another idea based on that.
import java.util.LinkedHashMap;
import java.util.Map;
public class HashTest
{
public static void main(String[] args)
{
int maxK = 30;
int maxI = 30;
System.out.println(computeFrequencies(h0, maxK, maxI));
System.out.println(computeFrequencies(h1, maxK, maxI));
}
private static Map<Integer, Integer> computeFrequencies(
Hash hash, int maxK, int maxI)
{
Map<Integer, Integer> frequencies =
new LinkedHashMap<Integer, Integer>();
for (int k=0; k<maxK; k++)
{
for (int i=0; i<maxI; i++)
{
int value = hash.compute(k, i);
Integer count = frequencies.get(value);
if (count == null)
{
count = 0;
}
frequencies.put(value, count+1);
}
}
return frequencies;
}
private static interface Hash
{
int compute(int k, int i);
}
private static final Hash h0 = new Hash()
{
#Override
public int compute(int k, int i)
{
return ((k % 13) + i * (1 + (k % 7))) % 11;
}
};
private static final Hash h1 = new Hash()
{
#Override
public int compute(int k, int i)
{
return ((k % 13) + i * (1 + (k % 7))) % 12;
}
};
}
how to calculate pow and round off with BigInteger data type
below is code but when we go with quick watch it's showing {0}.my concern is how to get the value and how to round off this " BigInteger_getpow" value
double a=1;
double b=2;
int k=50;
BigInteger BigInteger_x = (BigInteger)(a/b);
BigInteger BigInteger_getpow = BigInteger.Pow(BigInteger_x , k);
To implement a 2D animation I am looking for interpolating values between two key frames with the velocity of change defined by a Bezier curve. The problem is Bezier curve is represented in parametric form whereas requirement is to be able to evaluate the value for a particular time.
To elaborate, lets say the value of 10 and 40 is to be interpolated across 4 seconds with the value changing not constantly but as defined by a bezier curve represented as 0,0 0.2,0.3 0.5,0.5 1,1.
Now if I am drawing at 24 frames per second, I need to evaluate the value for every frame. How can I do this ? I looked at De Casteljau algorithm and thought that dividing the curve into 24*4 pieces for 4 seconds would solve my problem but that sounds erroneous as time is along the "x" axis and not along the curve.
To further simplify
If I draw the curve in a plane, the x axis represents the time and the y axis the value I am looking for. What I actually require is to to be able to find out "y" corresponding to "x". Then I can divide x in 24 divisions and know the value for each frame
I was facing the same problem: Every animation package out there seems to use Bézier curves to control values over time, but there is no information out there on how to implement a Bézier curve as a y(x) function. So here is what I came up with.
A standard cubic Bézier curve in 2D space can be defined by the four points P0=(x0, y0) .. P3=(x3, y3).
P0 and P3 are the end points of the curve, while P1 and P2 are the handles affecting its shape. Using a parameter t ϵ [0, 1], the x and y coordinates for any given point along the curve can then be determined using the equations
A) x = (1-t)3x0 + 3t(1-t)2x1 + 3t2(1-t)x2 + t3x3 and
B) y = (1-t)3y0 + 3t(1-t)2y1 + 3t2(1-t)y2 + t3y3.
What we want is a function y(x) that, given an x coordinate, will return the corresponding y coordinate of the curve. For this to work, the curve must move monotonically from left to right, so that it doesn't occupy the same x coordinate more than once on different y positions. The easiest way to ensure this is to restrict the input points so that x0 < x3 and x1, x2 ϵ [x0, x3]. In other words, P0 must be to the left of P3 with the two handles between them.
In order to calculate y for a given x, we must first determine t from x. Getting y from t is then a simple matter of applying t to equation B.
I see two ways of determining t for a given y.
First, you might try a binary search for t. Start with a lower bound of 0 and an upper bound of 1 and calculate x for these values for t via equation A. Keep bisecting the interval until you get a reasonably close approximation. While this should work fine, it will neither be particularly fast nor very precise (at least not both at once).
The second approach is to actually solve equation A for t. That's a bit tough to implement because the equation is cubic. On the other hand, calculation becomes really fast and yields precise results.
Equation A can be rewritten as
(-x0+3x1-3x2+x3)t3 + (3x0-6x1+3x2)t2 + (-3x0+3x1)t + (x0-x) = 0.
Inserting your actual values for x0..x3, we get a cubic equation of the form at3 + bt2 + c*t + d = 0 for which we know there is only one solution within [0, 1]. We can now solve this equation using an algorithm like the one posted in this Stack Overflow answer.
The following is a little C# class demonstrating this approach. It should be simple enough to convert it to a language of your choice.
using System;
public class Point {
public Point(double x, double y) {
X = x;
Y = y;
}
public double X { get; private set; }
public double Y { get; private set; }
}
public class BezierCurve {
public BezierCurve(Point p0, Point p1, Point p2, Point p3) {
P0 = p0;
P1 = p1;
P2 = p2;
P3 = p3;
}
public Point P0 { get; private set; }
public Point P1 { get; private set; }
public Point P2 { get; private set; }
public Point P3 { get; private set; }
public double? GetY(double x) {
// Determine t
double t;
if (x == P0.X) {
// Handle corner cases explicitly to prevent rounding errors
t = 0;
} else if (x == P3.X) {
t = 1;
} else {
// Calculate t
double a = -P0.X + 3 * P1.X - 3 * P2.X + P3.X;
double b = 3 * P0.X - 6 * P1.X + 3 * P2.X;
double c = -3 * P0.X + 3 * P1.X;
double d = P0.X - x;
double? tTemp = SolveCubic(a, b, c, d);
if (tTemp == null) return null;
t = tTemp.Value;
}
// Calculate y from t
return Cubed(1 - t) * P0.Y
+ 3 * t * Squared(1 - t) * P1.Y
+ 3 * Squared(t) * (1 - t) * P2.Y
+ Cubed(t) * P3.Y;
}
// Solves the equation ax³+bx²+cx+d = 0 for x ϵ ℝ
// and returns the first result in [0, 1] or null.
private static double? SolveCubic(double a, double b, double c, double d) {
if (a == 0) return SolveQuadratic(b, c, d);
if (d == 0) return 0;
b /= a;
c /= a;
d /= a;
double q = (3.0 * c - Squared(b)) / 9.0;
double r = (-27.0 * d + b * (9.0 * c - 2.0 * Squared(b))) / 54.0;
double disc = Cubed(q) + Squared(r);
double term1 = b / 3.0;
if (disc > 0) {
double s = r + Math.Sqrt(disc);
s = (s < 0) ? -CubicRoot(-s) : CubicRoot(s);
double t = r - Math.Sqrt(disc);
t = (t < 0) ? -CubicRoot(-t) : CubicRoot(t);
double result = -term1 + s + t;
if (result >= 0 && result <= 1) return result;
} else if (disc == 0) {
double r13 = (r < 0) ? -CubicRoot(-r) : CubicRoot(r);
double result = -term1 + 2.0 * r13;
if (result >= 0 && result <= 1) return result;
result = -(r13 + term1);
if (result >= 0 && result <= 1) return result;
} else {
q = -q;
double dum1 = q * q * q;
dum1 = Math.Acos(r / Math.Sqrt(dum1));
double r13 = 2.0 * Math.Sqrt(q);
double result = -term1 + r13 * Math.Cos(dum1 / 3.0);
if (result >= 0 && result <= 1) return result;
result = -term1 + r13 * Math.Cos((dum1 + 2.0 * Math.PI) / 3.0);
if (result >= 0 && result <= 1) return result;
result = -term1 + r13 * Math.Cos((dum1 + 4.0 * Math.PI) / 3.0);
if (result >= 0 && result <= 1) return result;
}
return null;
}
// Solves the equation ax² + bx + c = 0 for x ϵ ℝ
// and returns the first result in [0, 1] or null.
private static double? SolveQuadratic(double a, double b, double c) {
double result = (-b + Math.Sqrt(Squared(b) - 4 * a * c)) / (2 * a);
if (result >= 0 && result <= 1) return result;
result = (-b - Math.Sqrt(Squared(b) - 4 * a * c)) / (2 * a);
if (result >= 0 && result <= 1) return result;
return null;
}
private static double Squared(double f) { return f * f; }
private static double Cubed(double f) { return f * f * f; }
private static double CubicRoot(double f) { return Math.Pow(f, 1.0 / 3.0); }
}
You have a few options:
Let's say your curve function F(t) takes a parameter t that ranges from 0 to 1 where F(0) is the beginning of the curve and F(1) is the end of the curve.
You could animate motion along the curve by incrementing t at a constant change per unit of time.
So t is defined by function T(time) = Constant*time
For example, if your frame is 1/24th of a second, and you want to move along the curve at a rate of 0.1 units of t per second, then each frame you increment t by 0.1 (t/s) * 1/24 (sec/frame).
A drawback here is that your actual speed or distance traveled per unit time will not be constant. It will depends on the positions of your control points.
If you want to scale speed along the curve uniformly you can modify the constant change in t per unit time. However, if you want speeds to vary dramatically you will find it difficult to control the shape of the curve. If you want the velocity at one endpoint to be much larger, you must move the control point further away, which in turn pulls the shape of the curve towards that point. If this is a problem, you may consider using a non constant function for t. There are a variety of approaches with different trade-offs, and we need to know more details about your problem to suggest a solution. For example, in the past I have allowed users to define the speed at each keyframe and used a lookup table to translate from time to parameter t such that there is a linear change in speed between keyframe speeds (it's complicated).
Another common hangup: If you are animating by connecting several Bezier curves, and you want the velocity to be continuous when moving between curves, then you will need to constrain your control points so they are symmetrical with the adjacent curve. Catmull-Rom splines are a common approach.
I've answered a similar question here. Basically if you know the control points before hand then you can transform the f(t) function into a y(x) function. To not have to do it all by hand you can use services like Wolfram Alpha to help you with the math.