repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/ImmutableQuadraticElement.java | package it.unisa.dia.gas.plaf.jpbc.field.quadratic;
import it.unisa.dia.gas.jpbc.Element;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ImmutableQuadraticElement<E extends Element> extends QuadraticElement<E> {
public ImmutableQuadraticElement(QuadraticElement<E> element) {
super(element.getField());
this.x = (E) element.getX().getImmutable();
this.y = (E) element.getY().getImmutable();
this.immutable = true;
}
@Override
public QuadraticElement duplicate() {
return super.duplicate();
}
@Override
public Element getImmutable() {
return (QuadraticElement) this;
}
@Override
public QuadraticElement set(Element e) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement set(int value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement set(BigInteger value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement setToZero() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement setToOne() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement setToRandom() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source, int offset) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public QuadraticElement twice() {
return (QuadraticElement) super.duplicate().twice().getImmutable();
}
@Override
public QuadraticElement mul(int z) {
return (QuadraticElement) super.duplicate().mul(z).getImmutable();
}
@Override
public QuadraticElement square() {
return (QuadraticElement) super.duplicate().square().getImmutable();
}
@Override
public QuadraticElement invert() {
return (QuadraticElement) super.duplicate().invert().getImmutable();
}
@Override
public QuadraticElement negate() {
return (QuadraticElement) super.duplicate().negate().getImmutable();
}
@Override
public QuadraticElement add(Element e) {
return (QuadraticElement) super.duplicate().add(e).getImmutable();
}
@Override
public QuadraticElement sub(Element e) {
return (QuadraticElement) super.duplicate().sub(e).getImmutable();
}
@Override
public QuadraticElement mul(Element e) {
return (QuadraticElement) super.duplicate().mul(e).getImmutable();
}
@Override
public QuadraticElement mul(BigInteger n) {
return (QuadraticElement) super.duplicate().mul(n).getImmutable();
}
@Override
public QuadraticElement mulZn(Element e) {
return (QuadraticElement) super.duplicate().mulZn(e).getImmutable();
}
@Override
public QuadraticElement sqrt() {
return (QuadraticElement) super.duplicate().sqrt().getImmutable();
}
@Override
public QuadraticElement powZn(Element n) {
return (QuadraticElement) super.duplicate().powZn(n).getImmutable();
}
@Override
public QuadraticElement setFromHash(byte[] source, int offset, int length) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytesCompressed(byte[] source) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytesCompressed(byte[] source, int offset) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytesX(byte[] source) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytesX(byte[] source, int offset) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public Element pow(BigInteger n) {
return (QuadraticElement) super.duplicate().pow(n).getImmutable();
}
@Override
public Element halve() {
return (QuadraticElement) super.duplicate().halve().getImmutable();
}
@Override
public Element div(Element element) {
return (QuadraticElement) super.duplicate().div(element).getImmutable();
}
}
| 4,850 | 27.203488 | 87 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/QuadraticElement.java | package it.unisa.dia.gas.plaf.jpbc.field.quadratic;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractPointElement;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class QuadraticElement<E extends Element> extends AbstractPointElement<E, QuadraticField> {
public QuadraticElement(QuadraticField field) {
super(field);
this.x = (E) field.getTargetField().newElement();
this.y = (E) field.getTargetField().newElement();
}
public QuadraticElement(QuadraticElement element) {
super(element.getField());
this.x = (E) element.x.duplicate();
this.y = (E) element.y.duplicate();
}
public QuadraticField getField() {
return field;
}
@Override
public Element getImmutable() {
return new ImmutableQuadraticElement<E>(this);
}
public QuadraticElement duplicate() {
return new QuadraticElement(this);
}
public QuadraticElement set(Element e) {
QuadraticElement element = (QuadraticElement) e;
this.x.set(element.x);
this.y.set(element.y);
return this;
}
public QuadraticElement set(int value) {
x.set(value);
y.setToZero();
return this;
}
public QuadraticElement set(BigInteger value) {
x.set(value);
y.setToZero();
return this;
}
public boolean isZero() {
return x.isZero() && y.isZero();
}
public boolean isOne() {
return x.isOne() && y.isZero();
}
public QuadraticElement setToZero() {
x.setToZero();
y.setToZero();
return this;
}
public QuadraticElement setToOne() {
x.setToOne();
y.setToZero();
return this;
}
public QuadraticElement setToRandom() {
x.setToRandom();
y.setToRandom();
return this;
}
public int setFromBytes(byte[] source, int offset) {
int len;
len = x.setFromBytes(source, offset);
len += y.setFromBytes(source, offset + len);
return len;
}
public QuadraticElement twice() {
x.twice();
y.twice();
return this;
}
public QuadraticElement mul(int z) {
x.mul(z);
y.mul(z);
return this;
}
public QuadraticElement square() {
Element e0 = x.duplicate().square();
Element e1 = y.duplicate().square();
e1.mul(field.getTargetField().getNqr());
e0.add(e1);
e1.set(x).mul(y);
e1.twice();
x.set(e0);
y.set(e1);
return this;
}
public QuadraticElement invert() {
Element e0 = x.duplicate().square();
Element e1 = y.duplicate().square();
e1.mul(field.getTargetField().getNqr());
e0.sub(e1);
e0.invert();
x.mul(e0);
e0.negate();
y.mul(e0);
return this;
}
public QuadraticElement negate() {
x.negate();
y.negate();
return this;
}
public QuadraticElement add(Element e) {
QuadraticElement element = (QuadraticElement) e;
x.add(element.x);
y.add(element.y);
return this;
}
public QuadraticElement sub(Element e) {
QuadraticElement element = (QuadraticElement) e;
x.sub(element.x);
y.sub(element.y);
return this;
}
public QuadraticElement mul(Element e) {
QuadraticElement element = (QuadraticElement) e;
Element e0 = x.duplicate().add(y);
Element e1 = element.x.duplicate().add(element.y);
Element e2 = e0.duplicate().mul(e1);
e0.set(x).mul(element.x);
e1.set(y).mul(element.y);
x.set(e1).mul(field.getTargetField().getNqr()).add(e0);
e2.sub(e0);
y.set(e2).sub(e1);
return this;
}
public QuadraticElement mul(BigInteger n) {
x.mul(n);
y.mul(n);
return this;
}
public QuadraticElement mulZn(Element e) {
x.mulZn(e);
y.mulZn(e);
return this;
}
public boolean isSqr() {
Element e0 = x.duplicate().square();
Element e1 = y.duplicate().square();
e1.mul(field.getTargetField().getNqr());
e0.sub(e1);
return e0.isSqr();
}
public QuadraticElement sqrt() {
Element e0 = x.duplicate().square();
Element e1 = y.duplicate().square();
e1.mul(field.getTargetField().getNqr());
e0.sub(e1);
e0.sqrt();
e1.set(x).add(e0);
Element e2 = x.getField().newElement().set(2).invert();
e1.mul(e2);
if (!e1.isSqr())
e1.sub(e0);
e0.set(e1).sqrt();
e1.set(e0).add(e0);
e1.invert();
y.mul(e1);
x.set(e0);
return this;
}
public boolean isEqual(Element e) {
if (e == this)
return true;
if (!(e instanceof QuadraticElement))
return false;
QuadraticElement element = (QuadraticElement) e;
return x.isEqual(element.x) && y.isEqual(element.y);
}
public QuadraticElement powZn(Element n) {
pow(n.toBigInteger());
return this;
}
public BigInteger toBigInteger() {
return x.toBigInteger();
}
public byte[] toBytes() {
byte[] xBytes = x.toBytes();
byte[] yBytes = y.toBytes();
byte[] result = new byte[xBytes.length + yBytes.length];
System.arraycopy(xBytes, 0, result, 0, xBytes.length);
System.arraycopy(yBytes, 0, result, xBytes.length, yBytes.length);
return result;
}
public QuadraticElement setFromHash(byte[] source, int offset, int length) {
int k = length / 2;
x.setFromHash(source, offset, k);
y.setFromHash(source, offset + k, k);
return this;
}
public int sign() {
int res = x.sign();
if (res == 0)
return y.sign();
return res;
}
public String toString() {
return String.format("{x=%s,y=%s}", x, y);
}
} | 6,165 | 20.787986 | 98 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/QuadraticField.java | package it.unisa.dia.gas.plaf.jpbc.field.quadratic;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class QuadraticField<F extends Field, E extends QuadraticElement> extends AbstractFieldOver<F, E> {
protected BigInteger order;
protected int fixedLengthInBytes;
public QuadraticField(SecureRandom random, F targetField) {
super(random, targetField);
this.order = targetField.getOrder().multiply(targetField.getOrder());
if (targetField.getLengthInBytes() < 0) {
//f->length_in_bytes = fq_length_in_bytes;
fixedLengthInBytes = -1;
} else {
fixedLengthInBytes = 2 * targetField.getLengthInBytes();
}
}
public E newElement() {
return (E) new QuadraticElement(this);
}
public BigInteger getOrder() {
return order;
}
public E getNqr() {
throw new IllegalStateException("Not implemented yet!!!");
}
public int getLengthInBytes() {
return fixedLengthInBytes;
}
} | 1,205 | 24.659574 | 106 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/vector/ImmutableVectorElement.java | package it.unisa.dia.gas.plaf.jpbc.field.vector;
import it.unisa.dia.gas.jpbc.Element;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ImmutableVectorElement<E extends Element> extends VectorElement<E> {
public ImmutableVectorElement(VectorElement element) {
super(element.getField());
this.coeff.clear();
for (int i = 0; i < field.n; i++)
coeff.add((E) element.getAt(i).getImmutable());
this.immutable = true;
}
@Override
public VectorElement<E> duplicate() {
return super.duplicate();
}
@Override
public VectorElement<E> getImmutable() {
return this;
}
@Override
public VectorElement set(Element e) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement set(int value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement set(BigInteger value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement twice() {
return (VectorElement) duplicate().twice().getImmutable();
}
@Override
public VectorElement setToZero() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement setToOne() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement setToRandom() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source, int offset) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public VectorElement square() {
return (VectorElement) duplicate().square().getImmutable();
}
@Override
public VectorElement invert() {
return (VectorElement) duplicate().invert().getImmutable();
}
@Override
public VectorElement negate() {
return (VectorElement) duplicate().negate().getImmutable();
}
@Override
public VectorElement add(Element e) {
return (VectorElement) duplicate().add(e).getImmutable();
}
@Override
public VectorElement mul(Element e) {
return (VectorElement) duplicate().mul(e).getImmutable();
}
@Override
public VectorElement mul(BigInteger n) {
return (VectorElement) duplicate().mul(n).getImmutable();
}
@Override
public VectorElement mulZn(Element e) {
return (VectorElement) duplicate().mulZn(e).getImmutable();
}
@Override
public VectorElement powZn(Element e) {
return (VectorElement) duplicate().powZn(e).getImmutable();
}
@Override
public VectorElement setFromHash(byte[] source, int offset, int length) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public Element pow(BigInteger n) {
return duplicate().pow(n).getImmutable();
}
@Override
public Element halve() {
return duplicate().halve().getImmutable();
}
@Override
public VectorElement sub(Element element) {
return (VectorElement) duplicate().sub(element).getImmutable();
}
@Override
public Element div(Element element) {
return duplicate().div(element).getImmutable();
}
@Override
public VectorElement mul(int z) {
return (VectorElement) duplicate().mul(z).getImmutable();
}
@Override
public VectorElement sqrt() {
return (VectorElement) duplicate().sqrt().getImmutable();
}
}
| 3,926 | 24.666667 | 81 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/vector/VectorElement.java | package it.unisa.dia.gas.plaf.jpbc.field.vector;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractVectorElement;
import java.math.BigInteger;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class VectorElement<E extends Element> extends AbstractVectorElement<E, VectorField> {
public VectorElement(VectorField field) {
super(field);
for (int i = 0; i < field.n; i++)
coeff.add((E) field.getTargetField().newElement());
}
public VectorElement(VectorElement element) {
super(element.getField());
for (int i = 0; i < field.n; i++)
coeff.add((E) element.getAt(i).duplicate());
}
public VectorElement(VectorField field, List<E> coeff) {
super(field);
this.field = field;
this.coeff = coeff;
}
public VectorField getField() {
return field;
}
public VectorElement<E> duplicate() {
return new VectorElement<E>(this);
}
public VectorElement<E> getImmutable() {
return new ImmutableVectorElement<E>(this);
}
public VectorElement<E> set(Element e) {
VectorElement<E> element = (VectorElement<E>) e;
for (int i = 0; i < coeff.size(); i++) {
coeff.get(i).set(element.coeff.get(i));
}
return this;
}
public VectorElement<E> set(int value) {
coeff.get(0).set(value);
for (int i = 1; i < field.n; i++) {
coeff.get(i).setToZero();
}
return this;
}
public VectorElement<E> set(BigInteger value) {
coeff.get(0).set(value);
for (int i = 1; i < field.n; i++) {
coeff.get(i).setToZero();
}
return this;
}
public VectorElement<E> setToRandom() {
for (int i = 0; i < field.n; i++) {
coeff.get(i).setToRandom();
}
return this;
}
public VectorElement<E> setFromHash(byte[] source, int offset, int length) {
for (int i = 0; i < field.n; i++) {
coeff.get(i).setFromHash(source, offset, length);
}
return this;
}
public VectorElement<E> setToZero() {
for (int i = 0; i < field.n; i++) {
coeff.get(i).setToZero();
}
return this;
}
public boolean isZero() {
for (int i = 0; i < field.n; i++) {
if (!coeff.get(i).isZero())
return false;
}
return true;
}
public VectorElement<E> setToOne() {
coeff.get(0).setToOne();
for (int i = 1; i < field.n; i++) {
coeff.get(i).setToZero();
}
return this;
}
public boolean isOne() {
if (!coeff.get(0).isOne())
return false;
for (int i = 1; i < field.n; i++) {
if (!coeff.get(i).isZero())
return false;
}
return true;
}
public VectorElement<E> map(Element e) {
coeff.get(0).set(e);
for (int i = 1; i < field.n; i++) {
coeff.get(i).setToZero();
}
return this;
}
public VectorElement<E> twice() {
for (int i = 0; i < field.n; i++) {
coeff.get(i).twice();
}
return this;
}
public VectorElement<E> square() {
for (int i = 0; i < field.n; i++) {
coeff.get(i).square();
}
return this;
}
public VectorElement<E> invert() {
throw new IllegalStateException("Not implemented yet!!!");
}
public VectorElement<E> negate() {
for (Element e : coeff) {
e.negate();
}
return this;
}
public VectorElement<E> add(Element e) {
VectorElement<E> element = (VectorElement<E>) e;
for (int i = 0; i < field.n; i++) {
coeff.get(i).add(element.coeff.get(i));
}
return this;
}
public VectorElement<E> sub(Element e) {
VectorElement<E> element = (VectorElement<E>) e;
for (int i = 0; i < field.n; i++) {
coeff.get(i).sub(element.coeff.get(i));
}
return this;
}
public VectorElement<E> mul(Element e) {
throw new IllegalStateException("Not implemented yet!!!");
}
public VectorElement<E> mul(int z) {
for (int i = 0; i < field.n; i++) {
coeff.get(i).mul(z);
}
return this;
}
public VectorElement<E> mul(BigInteger n) {
for (int i = 0; i < field.n; i++) {
coeff.get(i).mul(n);
}
return this;
}
public VectorElement<E> powZn(Element e) {
for (int i = 0; i < field.n; i++) {
coeff.get(i).powZn(e);
}
return this;
}
public ElementPowPreProcessing getElementPowPreProcessing() {
return new VectorElementPowPreProcessing(this);
}
public VectorElement<E> sqrt() {
throw new IllegalStateException("Not implemented yet!!!");
}
public boolean isSqr() {
throw new IllegalStateException("Not implemented yet!!!");
}
public int sign() {
throw new IllegalStateException("Not implemented yet!!!");
}
public boolean isEqual(Element e) {
if (e == this)
return true;
if ((e instanceof VectorElement))
return false;
VectorElement<E> element = (VectorElement<E>) e;
for (int i = 0; i < field.n; i++) {
if (!coeff.get(i).isEqual(element.coeff.get(i)))
return false;
}
return true;
}
public int setFromBytes(byte[] source) {
return setFromBytes(source, 0);
}
public int setFromBytes(byte[] source, int offset) {
int len = offset;
for (int i = 0, size = coeff.size(); i < size; i++) {
len += coeff.get(i).setFromBytes(source, len);
}
return len - offset;
}
public byte[] toBytes() {
byte[] buffer = new byte[field.getLengthInBytes()];
int targetLB = field.getTargetField().getLengthInBytes();
for (int len = 0, i = 0, size = coeff.size(); i < size; i++, len += targetLB) {
byte[] temp = coeff.get(i).toBytes();
System.arraycopy(temp, 0, buffer, len, targetLB);
}
return buffer;
}
public BigInteger toBigInteger() {
return coeff.get(0).toBigInteger();
}
public String toString() {
StringBuffer buffer = new StringBuffer("[");
for (Element e : coeff) {
buffer.append(e).append(", ");
}
buffer.append("]");
return buffer.toString();
}
} | 6,764 | 22.408304 | 93 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/vector/VectorElementPowPreProcessing.java | package it.unisa.dia.gas.plaf.jpbc.field.vector;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;
import it.unisa.dia.gas.jpbc.Field;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class VectorElementPowPreProcessing implements ElementPowPreProcessing {
protected VectorField field;
protected ElementPowPreProcessing[] processings;
public VectorElementPowPreProcessing(VectorElement vector) {
this.field = vector.getField();
this.processings = new ElementPowPreProcessing[vector.getSize()];
for (int i = 0; i < processings.length; i++) {
processings[i] = vector.getAt(i).getElementPowPreProcessing();
}
}
public Element pow(BigInteger n) {
List<Element> coeff = new ArrayList<Element>(processings.length);
for (ElementPowPreProcessing processing : processings) {
coeff.add(processing.pow(n));
}
return new VectorElement(field, coeff);
}
public Element powZn(Element n) {
List<Element> coeff = new ArrayList<Element>(processings.length);
for (ElementPowPreProcessing processing : processings) {
coeff.add(processing.powZn(n));
}
return new VectorElement(field, coeff);
}
public byte[] toBytes() {
throw new IllegalStateException("Not implemented yet!!!");
}
public Field getField() {
return field;
}
}
| 1,542 | 29.86 | 79 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/vector/VectorField.java | package it.unisa.dia.gas.plaf.jpbc.field.vector;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class VectorField<F extends Field> extends AbstractFieldOver<F, VectorElement> {
protected int n, lenInBytes;
public VectorField(SecureRandom random, F targetField, int n) {
super(random, targetField);
this.n = n;
this.lenInBytes = n * targetField.getLengthInBytes();
}
public VectorElement newElement() {
return new VectorElement(this);
}
public BigInteger getOrder() {
throw new IllegalStateException("Not implemented yet!!!");
}
public VectorElement getNqr() {
throw new IllegalStateException("Not implemented yet!!!");
}
public int getLengthInBytes() {
return lenInBytes;
}
public int getN() {
return n;
}
}
| 1,015 | 21.577778 | 87 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/AbstractZElement.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractElement;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractField;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public abstract class AbstractZElement<F extends AbstractField> extends AbstractElement<F> {
public BigInteger value;
protected AbstractZElement(F field) {
super(field);
}
}
| 448 | 22.631579 | 92 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/ImmutableZrElement.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.jpbc.Element;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ImmutableZrElement extends ZrElement {
public ImmutableZrElement(ZrElement zrElement) {
super(zrElement);
this.immutable = true;
}
@Override
public Element getImmutable() {
return this;
}
@Override
public ZrElement duplicate() {
return super.duplicate();
}
@Override
public ZrElement set(Element value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement set(int value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement set(BigInteger value) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement setToZero() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement setToOne() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement setToRandom() {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement setFromHash(byte[] source, int offset, int length) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public int setFromBytes(byte[] source, int offset) {
throw new IllegalStateException("Invalid call on an immutable element");
}
@Override
public ZrElement twice() {
return (ZrElement) super.duplicate().twice().getImmutable();
}
@Override
public ZrElement mul(int z) {
return (ZrElement) super.duplicate().mul(z).getImmutable();
}
@Override
public ZrElement square() {
return (ZrElement) super.duplicate().square().getImmutable();
}
@Override
public ZrElement invert() {
return (ZrElement) super.duplicate().invert().getImmutable();
}
@Override
public ZrElement halve() {
return (ZrElement) super.duplicate().halve().getImmutable();
}
@Override
public ZrElement negate() {
return (ZrElement) super.duplicate().negate().getImmutable();
}
@Override
public ZrElement add(Element element) {
return (ZrElement) super.duplicate().add(element).getImmutable();
}
@Override
public ZrElement sub(Element element) {
return (ZrElement) super.duplicate().sub(element).getImmutable();
}
@Override
public ZrElement div(Element element) {
return (ZrElement) super.duplicate().div(element).getImmutable();
}
@Override
public ZrElement mul(Element element) {
return (ZrElement) super.duplicate().mul(element).getImmutable();
}
@Override
public ZrElement mul(BigInteger n) {
return (ZrElement) super.duplicate().mul(n).getImmutable();
}
@Override
public ZrElement mulZn(Element z) {
return (ZrElement) super.duplicate().mulZn(z).getImmutable();
}
@Override
public ZrElement sqrt() {
return (ZrElement) super.duplicate().sqrt().getImmutable();
}
@Override
public ZrElement pow(BigInteger n) {
return (ZrElement) super.duplicate().pow(n).getImmutable();
}
@Override
public ZrElement powZn(Element n) {
return (ZrElement) super.duplicate().powZn(n).getImmutable();
}
}
| 3,764 | 24.439189 | 80 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/SymmetricZrElement.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.util.Arrays;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class SymmetricZrElement<F extends SymmetricZrField> extends AbstractZElement<F> {
protected BigInteger order;
protected BigInteger halfOrder;
public SymmetricZrElement(F field) {
super(field);
this.value = BigInteger.ZERO;
this.order = field.getOrder();
this.halfOrder = field.halfOrder;
}
public SymmetricZrElement(F field, BigInteger value) {
super(field);
this.order = field.getOrder();
this.halfOrder = field.halfOrder;
set(value);
}
public SymmetricZrElement(SymmetricZrElement<F> zrElement) {
super(zrElement.getField());
this.order = zrElement.field.getOrder();
this.halfOrder = zrElement.field.halfOrder;
this.value = zrElement.value.mod(order);
}
public F getField() {
return field;
}
@Override
public Element getImmutable() {
throw new IllegalArgumentException("Not implemented yet!!!");
}
public SymmetricZrElement duplicate() {
return new SymmetricZrElement(this);
}
public SymmetricZrElement set(Element value) {
this.value = ((AbstractZElement) value).value.mod(order);
return mod();
}
public SymmetricZrElement set(int value) {
this.value = BigInteger.valueOf(value).mod(order);
return mod();
}
public SymmetricZrElement set(BigInteger value) {
this.value = value.mod(order);
return mod();
}
public boolean isZero() {
return BigInteger.ZERO.equals(value);
}
public boolean isOne() {
return BigInteger.ONE.equals(value);
}
public SymmetricZrElement twice() {
// this.value = value.multiply(BigIntegerUtils.TWO).mod(order);
this.value = value.add(value).mod(order);
return mod();
}
public SymmetricZrElement mul(int z) {
this.value = this.value.multiply(BigInteger.valueOf(z)).mod(order);
return mod();
}
public SymmetricZrElement setToZero() {
this.value = BigInteger.ZERO;
return this;
}
public SymmetricZrElement setToOne() {
this.value = BigInteger.ONE;
return this;
}
public SymmetricZrElement setToRandom() {
this.value = BigIntegerUtils.getRandom(order, field.getRandom());
return mod();
}
public SymmetricZrElement setFromHash(byte[] source, int offset, int length) {
int i = 0, n, count = (order.bitLength() + 7) / 8;
byte[] buf = new byte[count];
byte counter = 0;
boolean done = false;
for (; ; ) {
if (length >= count - i) {
n = count - i;
done = true;
} else n = length;
System.arraycopy(source, offset, buf, i, n);
i += n;
if (done)
break;
buf[i] = counter;
counter++;
i++;
if (i == count) break;
}
assert (i == count);
//mpz_import(z, count, 1, 1, 1, 0, buf);
BigInteger z = new BigInteger(1, buf);
while (z.compareTo(order) > 0) {
z = z.divide(BigIntegerUtils.TWO);
}
this.value = z;
return this;
}
public int setFromBytes(byte[] source) {
return setFromBytes(source, 0);
}
public int setFromBytes(byte[] source, int offset) {
byte[] buffer = Arrays.copyOf(source, offset, field.getLengthInBytes());
value = new BigInteger(1, buffer).mod(order);
mod();
return buffer.length;
}
public SymmetricZrElement square() {
// value = value.modPow(BigIntegerUtils.TWO, order);
value = value.multiply(value).mod(order);
return mod();
}
public SymmetricZrElement invert() {
value = value.modInverse(order);
return mod();
}
public SymmetricZrElement halve() {
value = value.multiply(field.twoInverse).mod(order);
return mod();
}
public SymmetricZrElement negate() {
if (isZero()) {
value = BigInteger.ZERO;
return this;
}
value = order.subtract(value);
return mod();
}
public SymmetricZrElement add(Element element) {
value = value.add(((AbstractZElement) element).value).mod(order);
return mod();
}
public SymmetricZrElement sub(Element element) {
value = value.subtract(((SymmetricZrElement) element).value).mod(order);
return mod();
}
public SymmetricZrElement div(Element element) {
value = value.multiply(((SymmetricZrElement) element).value.modInverse(order)).mod(order);
return mod();
}
public SymmetricZrElement mul(Element element) {
value = value.multiply(((AbstractZElement) element).value).mod(order);
return mod();
}
public SymmetricZrElement mul(BigInteger n) {
this.value = this.value.multiply(n).mod(order);
return mod();
}
public SymmetricZrElement mulZn(Element z) {
this.value = this.value.multiply(z.toBigInteger()).mod(order);
return mod();
}
public boolean isSqr() {
return BigInteger.ZERO.equals(value) || BigIntegerUtils.legendre(value, order) == 1;
}
public SymmetricZrElement sqrt() {
// Apply the Tonelli-Shanks Algorithm
Element e0 = field.newElement();
Element nqr = field.getNqr();
Element gInv = nqr.duplicate().invert();
// let q be the order of the field
// q - 1 = 2^s t, for some t odd
BigInteger t = order.subtract(BigInteger.ONE);
int s = BigIntegerUtils.scanOne(t, 0);
t = t.divide(BigInteger.valueOf(2 << (s - 1)));
BigInteger e = BigInteger.ZERO;
BigInteger orderMinusOne = order.subtract(BigInteger.ONE);
for (int i = 2; i <= s; i++) {
e0.set(gInv).pow(e);
e0.mul(this).pow(orderMinusOne.divide(BigInteger.valueOf(2 << (i - 1))));
if (!e0.isOne())
e = e.setBit(i - 1);
}
e0.set(gInv).pow(e);
e0.mul(this);
t = t.add(BigInteger.ONE);
t = t.divide(BigIntegerUtils.TWO);
e = e.divide(BigIntegerUtils.TWO);
// TODO(-):
// (suggested by Hovav Shacham) replace next three lines with
// element_pow2_mpz(x, e0, t, nqr, e);
// once sliding windows are implemented for pow2
e0.pow(t);
set(nqr).pow(e).mul(e0);
return this;
}
public SymmetricZrElement pow(BigInteger n) {
this.value = this.value.modPow(n, order);
return mod();
}
public SymmetricZrElement powZn(Element n) {
return pow(n.toBigInteger());
}
public boolean isEqual(Element e) {
return this == e || (e instanceof SymmetricZrElement && value.compareTo(((SymmetricZrElement) e).value) == 0);
}
public BigInteger toBigInteger() {
return value;
}
@Override
public byte[] toBytes() {
byte[] bytes = value.toByteArray();
if (bytes.length > field.getLengthInBytes()) {
// strip the zero prefix
if (bytes[0] == 0 && bytes.length == field.getLengthInBytes() + 1) {
// Remove it
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
} else
throw new IllegalStateException("result has more than FixedLengthInBytes.");
} else if (bytes.length < field.getLengthInBytes()) {
byte[] result = new byte[field.getLengthInBytes()];
System.arraycopy(bytes, 0, result, field.getLengthInBytes() - bytes.length, bytes.length);
return result;
}
return bytes;
}
public int sign() {
if (isZero())
return 0;
if (field.isOrderOdd()) {
return BigIntegerUtils.isOdd(value) ? 1 : -1;
} else {
return value.add(value).compareTo(order);
}
}
public String toString() {
return value.toString();
}
private final SymmetricZrElement mod() {
if (this.value.compareTo(halfOrder) > 0)
this.value = this.value.subtract(order);
return this;
}
}
| 8,569 | 24.430267 | 118 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/SymmetricZrField.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractField;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class SymmetricZrField extends AbstractField<SymmetricZrElement> {
protected BigInteger order;
protected BigInteger halfOrder;
protected SymmetricZrElement nqr;
protected int fixedLengthInBytes;
protected BigInteger twoInverse;
public SymmetricZrField(BigInteger order) {
this(new SecureRandom(), order, null);
}
public SymmetricZrField(SecureRandom random, BigInteger order) {
this(random, order, null);
}
public SymmetricZrField(BigInteger order, BigInteger nqr) {
this(new SecureRandom(), order, nqr);
}
public SymmetricZrField(SecureRandom random, BigInteger order, BigInteger nqr) {
super(random);
this.order = order;
this.orderIsOdd = BigIntegerUtils.isOdd(order);
this.fixedLengthInBytes = (order.bitLength() + 7) / 8;
this.twoInverse = BigIntegerUtils.TWO.modInverse(order);
this.halfOrder = order.divide(BigInteger.valueOf(2));
if (nqr != null)
this.nqr = newElement().set(nqr);
}
public SymmetricZrElement newElement() {
return new SymmetricZrElement(this);
}
public BigInteger getOrder() {
return order;
}
public SymmetricZrElement getNqr() {
if (nqr == null) {
nqr = newElement();
do {
nqr.setToRandom();
} while (nqr.isSqr());
}
return nqr.duplicate();
}
public int getLengthInBytes() {
return fixedLengthInBytes;
}
}
| 1,833 | 24.123288 | 84 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/ZElement.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.util.Arrays;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ZElement extends AbstractZElement<ZField> {
public ZElement(ZField field) {
super(field);
this.value = BigInteger.ZERO;
}
public ZElement(ZField field, BigInteger value) {
super(field);
this.value = value;
}
public ZElement(ZElement zrElement) {
super(zrElement.getField());
this.value = zrElement.value;
}
public ZField getField() {
return field;
}
@Override
public Element getImmutable() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement duplicate() {
return new ZElement(this);
}
public ZElement set(Element value) {
this.value = ((AbstractZElement) value).value;
return this;
}
public ZElement set(int value) {
this.value = BigInteger.valueOf(value);
return this;
}
public ZElement set(BigInteger value) {
this.value = value;
return this;
}
public boolean isZero() {
return BigInteger.ZERO.equals(value);
}
public boolean isOne() {
return BigInteger.ONE.equals(value);
}
public ZElement twice() {
// this.value = value.multiply(BigIntegerUtils.TWO);
this.value = value.add(value);
return this;
}
public ZElement mul(int z) {
this.value = this.value.multiply(BigInteger.valueOf(z));
return this;
}
public ZElement setToZero() {
this.value = BigInteger.ZERO;
return this;
}
public ZElement setToOne() {
this.value = BigInteger.ONE;
return this;
}
public ZElement setToRandom() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement setFromHash(byte[] source, int offset, int length) {
throw new IllegalStateException("Not implemented yet!!!");
}
public int setFromBytes(byte[] source) {
return setFromBytes(source, 0);
}
public int setFromBytes(byte[] source, int offset) {
byte[] buffer = Arrays.copyOf(source, offset, field.getLengthInBytes());
value = new BigInteger(1, buffer);
return buffer.length;
}
public ZElement square() {
// value = value.modPow(BigIntegerUtils.TWO, order);
value = value.multiply(value);
return this;
}
public ZElement invert() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement halve() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement negate() {
value = value.multiply(BigInteger.valueOf(-1));
return this;
}
public ZElement add(Element element) {
value = value.add(((AbstractZElement)element).value);
return this;
}
public ZElement sub(Element element) {
value = value.subtract(((AbstractZElement)element).value);
return this;
}
public ZElement div(Element element) {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement mul(Element element) {
value = value.multiply(((AbstractZElement)element).value);
return this;
}
public ZElement mul(BigInteger n) {
this.value = this.value.multiply(n);
return this;
}
public ZElement mulZn(Element z) {
this.value = this.value.multiply(z.toBigInteger());
return this;
}
public boolean isSqr() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement sqrt() {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement pow(BigInteger n) {
throw new IllegalStateException("Not implemented yet!!!");
}
public ZElement powZn(Element n) {
return pow(n.toBigInteger());
}
public boolean isEqual(Element e) {
return this == e || (e instanceof ZElement && value.compareTo(((ZElement) e).value) == 0);
}
public BigInteger toBigInteger() {
return value;
}
@Override
public byte[] toBytes() {
throw new IllegalStateException("Not implemented yet!!!");
}
public int sign() {
return value.signum();
}
public String toString() {
return value.toString();
}
}
| 4,561 | 20.620853 | 98 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/ZField.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractField;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ZField extends AbstractField<ZElement> {
public ZField() {
this(new SecureRandom());
}
public ZField(SecureRandom random) {
super(random);
}
public ZElement newElement() {
return new ZElement(this);
}
public BigInteger getOrder() {
return BigInteger.ZERO;
}
public ZElement getNqr() {
throw new IllegalStateException("Not implemented yet!!!");
}
public int getLengthInBytes() {
return -1;
}
}
| 739 | 17.974359 | 66 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/ZrElement.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.util.Arrays;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ZrElement<F extends ZrField> extends AbstractZElement<F> {
protected BigInteger order;
public ZrElement(F field) {
super(field);
this.value = BigInteger.ZERO;
this.order = field.getOrder();
}
public ZrElement(F field, BigInteger value) {
super(field);
this.value = value;
this.order = field.getOrder();
}
public ZrElement(ZrElement<F> zrElement) {
super(zrElement.getField());
this.value = zrElement.value;
this.order = zrElement.field.getOrder();
}
public F getField() {
return field;
}
@Override
public Element getImmutable() {
return new ImmutableZrElement(this);
}
public ZrElement<F> duplicate() {
return new ZrElement<F>(this);
}
public ZrElement set(Element value) {
this.value = value.toBigInteger().mod(order);
return this;
}
public ZrElement set(int value) {
this.value = BigInteger.valueOf(value).mod(order);
return this;
}
public ZrElement set(BigInteger value) {
this.value = value.mod(order);
return this;
}
public boolean isZero() {
return BigInteger.ZERO.equals(value);
}
public boolean isOne() {
return BigInteger.ONE.equals(value);
}
public ZrElement twice() {
// this.value = value.multiply(BigIntegerUtils.TWO).mod(order);
this.value = value.add(value).mod(order);
return this;
}
public ZrElement mul(int z) {
this.value = this.value.multiply(BigInteger.valueOf(z)).mod(order);
return this;
}
public ZrElement setToZero() {
this.value = BigInteger.ZERO;
return this;
}
public ZrElement setToOne() {
this.value = BigInteger.ONE;
return this;
}
public ZrElement setToRandom() {
this.value = BigIntegerUtils.getRandom(order, field.getRandom());
return this;
}
public ZrElement setFromHash(byte[] source, int offset, int length) {
int i = 0, n, count = (order.bitLength() + 7) / 8;
byte[] buf = new byte[count];
byte counter = 0;
boolean done = false;
for (;;) {
if (length >= count - i) {
n = count - i;
done = true;
} else n = length;
System.arraycopy(source, offset, buf, i, n);
i += n;
if (done)
break;
buf[i] = counter;
counter++;
i++;
if (i == count) break;
}
assert (i == count);
//mpz_import(z, count, 1, 1, 1, 0, buf);
BigInteger z = new BigInteger(1, buf);
while (z.compareTo(order) > 0) {
z = z.divide(BigIntegerUtils.TWO);
}
this.value = z;
return this;
}
public int setFromBytes(byte[] source) {
return setFromBytes(source, 0);
}
public int setFromBytes(byte[] source, int offset) {
byte[] buffer = Arrays.copyOf(source, offset, field.getLengthInBytes());
value = new BigInteger(1, buffer).mod(order);
return buffer.length;
}
public ZrElement square() {
// value = value.modPow(BigIntegerUtils.TWO, order);
value = value.multiply(value).mod(order);
return this;
}
public ZrElement invert() {
try {
value = value.modInverse(order);
} catch (Exception e) {
e.printStackTrace();
throw (RuntimeException) e;
}
return this;
}
public ZrElement halve() {
value = value.multiply(((ZrField) field).twoInverse).mod(order);
return this;
}
public ZrElement negate() {
if (isZero()) {
value = BigInteger.ZERO;
return this;
}
value = order.subtract(value);
return this;
}
public ZrElement add(Element element) {
value = value.add(((AbstractZElement)element).value).mod(order);
return this;
}
public ZrElement sub(Element element) {
value = value.subtract(((ZrElement)element).value).mod(order);
return this;
}
public ZrElement div(Element element) {
value = value.multiply(((ZrElement)element).value.modInverse(order)).mod(order);
return this;
}
public ZrElement mul(Element element) {
value = value.multiply(((AbstractZElement)element).value).mod(order);
return this;
}
public ZrElement mul(BigInteger n) {
this.value = this.value.multiply(n).mod(order);
return this;
}
public ZrElement mulZn(Element z) {
this.value = this.value.multiply(z.toBigInteger()).mod(order);
return this;
}
public boolean isSqr() {
return BigInteger.ZERO.equals(value) || BigIntegerUtils.legendre(value, order) == 1;
}
public ZrElement sqrt() {
// Apply the Tonelli-Shanks Algorithm
Element e0 = field.newElement();
Element nqr = field.getNqr();
Element gInv = nqr.duplicate().invert();
// let q be the order of the field
// q - 1 = 2^s t, for some t odd
BigInteger t = order.subtract(BigInteger.ONE);
int s = BigIntegerUtils.scanOne(t, 0);
t = t.divide(BigInteger.valueOf(2 << (s - 1)));
BigInteger e = BigInteger.ZERO;
BigInteger orderMinusOne = order.subtract(BigInteger.ONE);
for (int i = 2; i <= s; i++) {
e0.set(gInv).pow(e);
e0.mul(this).pow(orderMinusOne.divide(BigInteger.valueOf(2 << (i - 1))));
if (!e0.isOne())
e = e.setBit(i - 1);
}
e0.set(gInv).pow(e);
e0.mul(this);
t = t.add(BigInteger.ONE);
t = t.divide(BigIntegerUtils.TWO);
e = e.divide(BigIntegerUtils.TWO);
// TODO(-):
// (suggested by Hovav Shacham) replace next three lines with
// element_pow2_mpz(x, e0, t, nqr, e);
// once sliding windows are implemented for pow2
e0.pow(t);
set(nqr).pow(e).mul(e0);
return this;
}
public ZrElement pow(BigInteger n) {
this.value = this.value.modPow(n, order);
return this;
}
public ZrElement powZn(Element n) {
return pow(n.toBigInteger());
}
public boolean isEqual(Element e) {
return this == e || (e instanceof ZrElement && value.compareTo(((ZrElement) e).value) == 0);
}
public BigInteger toBigInteger() {
return value;
}
@Override
public byte[] toBytes() {
byte[] bytes = value.toByteArray();
if (bytes.length > field.getLengthInBytes()) {
// strip the zero prefix
if (bytes[0] == 0 && bytes.length == field.getLengthInBytes() + 1) {
// Remove it
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
} else
throw new IllegalStateException("result has more than FixedLengthInBytes.");
} else if (bytes.length < field.getLengthInBytes()) {
byte[] result = new byte[field.getLengthInBytes()];
System.arraycopy(bytes, 0, result, field.getLengthInBytes() - bytes.length, bytes.length);
return result;
}
return bytes;
}
public int sign() {
if (isZero())
return 0;
if (field.isOrderOdd()) {
return BigIntegerUtils.isOdd(value) ? 1 : -1;
} else {
return value.add(value).compareTo(order);
}
}
public String toString() {
return value.toString();
}
}
| 7,988 | 23.282675 | 102 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/z/ZrField.java | package it.unisa.dia.gas.plaf.jpbc.field.z;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractField;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ZrField extends AbstractField<ZrElement> {
protected BigInteger order;
protected ZrElement nqr;
protected int fixedLengthInBytes;
protected BigInteger twoInverse;
public ZrField(BigInteger order) {
this(new SecureRandom(), order, null);
}
public ZrField(SecureRandom random, BigInteger order) {
this(random, order, null);
}
public ZrField(BigInteger order, BigInteger nqr) {
this(new SecureRandom(), order, nqr);
}
public ZrField(SecureRandom random, BigInteger order, BigInteger nqr) {
super(random);
this.order = order;
this.orderIsOdd = BigIntegerUtils.isOdd(order);
this.fixedLengthInBytes = (order.bitLength() + 7) / 8;
this.twoInverse = BigIntegerUtils.TWO.modInverse(order);
if (nqr != null)
this.nqr = newElement().set(nqr);
}
public ZrElement<ZrField> newElement() {
return new ZrElement<ZrField>(this);
}
public BigInteger getOrder() {
return order;
}
public ZrElement getNqr() {
if (nqr == null) {
nqr = newElement();
do {
nqr.setToRandom();
} while (nqr.isSqr());
}
return nqr.duplicate();
}
public int getLengthInBytes() {
return fixedLengthInBytes;
}
} | 1,656 | 23.367647 | 75 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/AbstractPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.PairingMap;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public abstract class AbstractPairing implements Pairing {
protected SecureRandom random;
protected Field G1, G2, GT, Zr;
protected PairingMap pairingMap;
protected AbstractPairing(SecureRandom random) {
this.random = (random == null) ? new SecureRandom() : random;
}
protected AbstractPairing() {
this(new SecureRandom());
}
public boolean isSymmetric() {
return true;
}
public Field getG1() {
return G1;
}
public Field getG2() {
return G2;
}
public Field getZr() {
return Zr;
}
public int getDegree() {
return 2;
}
public Field getFieldAt(int index) {
switch (index) {
case 0:
return Zr;
case 1:
return G1;
case 2:
return G2;
case 3:
return GT;
default:
throw new IllegalArgumentException("invalid index");
}
}
public Field getGT() {
return GT;
}
public Element pairing(Element in1, Element in2) {
if (!G1.equals(in1.getField()))
throw new IllegalArgumentException("pairing 1st input mismatch");
if (!G2.equals(in2.getField()))
throw new IllegalArgumentException("pairing 2nd input mismatch");
if (in1.isZero() || in2.isZero())
return GT.newElement().setToZero();
return pairingMap.pairing((Point) in1, (Point) in2);
}
public PairingPreProcessing getPairingPreProcessingFromElement(Element in1) {
if (!G1.equals(in1.getField()))
throw new IllegalArgumentException("pairing 1st input mismatch");
return pairingMap.pairing((Point) in1);
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source) {
return pairingMap.pairing(source, 0);
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source, int offset) {
return pairingMap.pairing(source, offset);
}
public boolean isAlmostCoddh(Element a, Element b, Element c, Element d) {
return pairingMap.isAlmostCoddh(a, b, c, d);
}
public int getFieldIndex(Field field) {
if (field == Zr)
return 0;
if (field == G1)
return 1;
if (field == G2)
return 2;
if (field == GT)
return 3;
return -1;
}
public boolean isProductPairingSupported() {
return pairingMap.isProductPairingSupported();
}
public Element pairing(Element[] in1, Element[] in2) {
if (in1.length != in2.length)
throw new IllegalArgumentException("Array lengths mismatch.");
for (int i = 0; i < in1.length; i++) {
if (!G1.equals(in1[i].getField()))
throw new IllegalArgumentException("pairing 1st input mismatch");
if (!G2.equals(in2[i].getField()))
throw new IllegalArgumentException("pairing 2nd input mismatch");
if (in1[i].isZero() || in2[i].isZero())
return GT.newElement().setToZero();
}
return pairingMap.pairing(in1, in2);
}
public int getPairingPreProcessingLengthInBytes() {
return pairingMap.getPairingPreProcessingLengthInBytes();
}
public PairingMap getPairingMap() {
return pairingMap;
}
public void setPairingMap(PairingMap pairingMap) {
this.pairingMap = pairingMap;
}
}
| 3,748 | 24.678082 | 93 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/PairingFactory.java | package it.unisa.dia.gas.plaf.jpbc.pairing;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.plaf.jpbc.pairing.a.TypeAPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.a1.TypeA1Pairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.d.TypeDPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.e.TypeEPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.f.TypeFPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.g.TypeGPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.immutable.ImmutableParing;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class PairingFactory {
private static final PairingFactory INSTANCE = new PairingFactory();
public static PairingFactory getInstance() {
return INSTANCE;
}
public static Pairing getPairing(PairingParameters parameters) {
return getInstance().initPairing(parameters);
}
public static Pairing getPairing(String parametersPath) {
return getInstance().initPairing(parametersPath);
}
public static Pairing getPairing(PairingParameters parameters, SecureRandom random) {
return getInstance().initPairing(parameters, random);
}
public static Pairing getPairing(String parametersPath, SecureRandom random) {
return getInstance().initPairing(parametersPath, random);
}
public static PairingParameters getPairingParameters(String parametersPath) {
return getInstance().loadParameters(parametersPath);
}
private boolean usePBCWhenPossible = false;
private boolean reuseInstance = true;
private boolean pbcAvailable = false;
private boolean immutable = false;
private Map<PairingParameters, Pairing> instances;
private Map<String, PairingCreator> creators;
private SecureRandomCreator secureRandomCreator;
private PairingFactory() {
this.instances = new HashMap<PairingParameters, Pairing>();
this.creators = new HashMap<String, PairingCreator>();
this.secureRandomCreator = new DefaultSecureRandomCreator();
PairingCreator defaultCreator = new EllipticCurvesPairingCreator();
creators.put("a", defaultCreator);
creators.put("a1", defaultCreator);
creators.put("d", defaultCreator);
creators.put("e", defaultCreator);
creators.put("f", defaultCreator);
creators.put("g", defaultCreator);
creators.put("ctl13", new CTL13MultilinearPairingCreator());
}
public Pairing initPairing(String parametersPath) {
return initPairing(loadParameters(parametersPath), secureRandomCreator.newSecureRandom());
}
public Pairing initPairing(PairingParameters parameters) {
return initPairing(parameters, secureRandomCreator.newSecureRandom());
}
public Pairing initPairing(String parametersPath, SecureRandom random) {
return initPairing(loadParameters(parametersPath), random);
}
public Pairing initPairing(PairingParameters parameters, SecureRandom random) {
if (parameters == null)
throw new IllegalArgumentException("parameters cannot be null.");
if (random == null)
random = secureRandomCreator.newSecureRandom();
Pairing pairing = null;
if (reuseInstance) {
pairing = instances.get(parameters);
if (pairing != null)
return pairing;
}
String type = parameters.getString("type");
PairingCreator creator = creators.get(type);
if (creator == null)
throw new IllegalArgumentException("Type not supported. Type = " + type);
pairing = creator.create(type, random, parameters);
if (pairing == null)
throw new IllegalArgumentException("Cannot create pairing instance. Type = " + type);
if (immutable)
pairing = new ImmutableParing(pairing);
if (reuseInstance)
instances.put(parameters, pairing);
return pairing;
}
public PairingParameters loadParameters(String path) {
PropertiesParameters curveParams = new PropertiesParameters();
curveParams.load(path);
return curveParams;
}
public boolean isPBCAvailable() {
return pbcAvailable;
}
public boolean isUsePBCWhenPossible() {
return usePBCWhenPossible;
}
public void setUsePBCWhenPossible(boolean usePBCWhenPossible) {
this.usePBCWhenPossible = usePBCWhenPossible;
}
public boolean isReuseInstance() {
return reuseInstance;
}
public void setReuseInstance(boolean reuseInstance) {
this.reuseInstance = reuseInstance;
}
public boolean isImmutable() {
return immutable;
}
public void setImmutable(boolean immutable) {
this.immutable = immutable;
}
public void addPairingCreator(String type, PairingCreator creator) {
creators.put(type, creator);
}
public static interface PairingCreator {
Pairing create(String type, SecureRandom random, PairingParameters pairingParameters);
}
public static class CTL13MultilinearPairingCreator implements PairingCreator {
private Method getPairingMethod;
private Throwable throwable;
public CTL13MultilinearPairingCreator() {
try {
Class pbcPairingFactoryClass = Class.forName("it.unisa.dia.gas.plaf.jpbc.mm.clt13.pairing.CTL13PairingFactory");
getPairingMethod = pbcPairingFactoryClass.getMethod("getPairing", SecureRandom.class, PairingParameters.class);
} catch (Exception e) {
throwable = e;
}
}
public Pairing create(String type, SecureRandom random, PairingParameters parameters) {
try {
return (Pairing) getPairingMethod.invoke(null, random, parameters);
} catch (Exception e) {
// Ignore
e.printStackTrace();
}
return null;
}
public Throwable getThrowable() {
return throwable;
}
}
public class EllipticCurvesPairingCreator implements PairingCreator {
private Method getPairingMethod;
private Throwable pbcPairingFailure;
public EllipticCurvesPairingCreator() {
// Try to load jpbc-pbc factory
try {
Class pbcPairingFactoryClass = Class.forName("it.unisa.dia.gas.plaf.jpbc.pbc.PBCPairingFactory");
Method isPBCAvailable = pbcPairingFactoryClass.getMethod("isPBCAvailable", null);
pbcAvailable = ((Boolean) isPBCAvailable.invoke(null));
if (pbcAvailable)
getPairingMethod = pbcPairingFactoryClass.getMethod("getPairing", PairingParameters.class);
} catch (Exception e) {
pbcAvailable = false;
pbcPairingFailure = e;
}
}
public Pairing create(String type, SecureRandom random, PairingParameters parameters) {
Pairing pairing = null;
// Handle bilinear maps parameters
if (usePBCWhenPossible && pbcAvailable)
pairing = getPBCPairing(parameters);
if (pairing == null) {
if ("a".equalsIgnoreCase(type))
pairing = new TypeAPairing(random, parameters);
else if ("a1".equalsIgnoreCase(type))
pairing = new TypeA1Pairing(random, parameters);
else if ("d".equalsIgnoreCase(type))
pairing = new TypeDPairing(random, parameters);
else if ("e".equalsIgnoreCase(type))
pairing = new TypeEPairing(random, parameters);
else if ("f".equalsIgnoreCase(type))
return new TypeFPairing(random, parameters);
else if ("g".equalsIgnoreCase(type))
return new TypeGPairing(random, parameters);
else
throw new IllegalArgumentException("Type not supported. Type = " + type);
}
return pairing;
}
public Pairing getPBCPairing(PairingParameters parameters) {
try {
return (Pairing) getPairingMethod.invoke(null, parameters);
} catch (Exception e) {
// Ignore
e.printStackTrace();
}
return null;
}
public Throwable getPbcPairingFailure() {
return pbcPairingFailure;
}
}
public static interface SecureRandomCreator {
SecureRandom newSecureRandom();
}
public static class DefaultSecureRandomCreator implements SecureRandomCreator {
public SecureRandom newSecureRandom() {
return new SecureRandom();
}
}
}
| 9,085 | 31.566308 | 128 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a/TypeACurveGenerator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.io.Base64;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeACurveGenerator implements PairingParametersGenerator {
protected SecureRandom random;
protected int rbits, qbits;
protected boolean generateCurveFieldGen;
public TypeACurveGenerator(SecureRandom random, int rbits, int qbits, boolean generateCurveFieldGen) {
this.random = random;
this.rbits = rbits;
this.qbits = qbits;
this.generateCurveFieldGen = generateCurveFieldGen;
}
public TypeACurveGenerator(int rbits, int qbits) {
this(new SecureRandom(), rbits, qbits, false);
}
public TypeACurveGenerator(int rbits, int qbits, boolean generateCurveFieldGen) {
this(new SecureRandom(), rbits, qbits, generateCurveFieldGen);
}
public PairingParameters generate() {
boolean found = false;
BigInteger q;
BigInteger r;
BigInteger h = null;
int exp1=0, exp2=0;
int sign0=0, sign1=0;
do {
// r is picked to be a Solinas prime, that is,
// r has the form 2a +- 2b +- 1 for some integers 0 < b < a.
r = BigInteger.ZERO;
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
exp2 = rbits - 1;
sign1 = 1;
} else {
exp2 = rbits;
sign1 = -1;
}
r = r.setBit(exp2);
q = BigInteger.ZERO;
exp1 = (random.nextInt(Integer.MAX_VALUE) % (exp2 - 1)) + 1;
q = q.setBit(exp1);
if (sign1 > 0) {
r = r.add(q);
} else {
r = r.subtract(q);
}
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
sign0 = 1;
r = r.add(BigInteger.ONE);
} else {
sign0 = -1;
r = r.subtract(BigInteger.ONE);
}
if (!r.isProbablePrime(10))
continue;
for (int i = 0; i < 10; i++) {
q = BigInteger.ZERO;
int bit = qbits - rbits - 4 + 1;
if (bit < 3)
bit = 3;
q = q.setBit(bit);
// we randomly generate h where where h is a multiple of four and sufficiently large to
// guarantee (hr)^2 is big enough to resist finite field attacks.
// If h is constrained to be a multiple of three as well, then cube roots are extremely easy to
// compute in Fq: for all x \in Fq we see x^(-(q-2)/3) is the cube root of x,
h = BigIntegerUtils.getRandom(q, random).multiply(BigIntegerUtils.TWELVE);
// Next it is checked that q = hr ?1 is prime, if it is the case we have finished.
// Also, we choose q = -1 mod 12 so F_q2 can be implemented as F_q[i] (where i = sqrt(-1)).
// Look at the class DegreeTwoExtensionQuadraticField and DegreeTwoExtensionQuadraticElement
q = h.multiply(r).subtract(BigInteger.ONE);
if (q.isProbablePrime(10)) {
found = true;
break;
}
}
} while (!found);
PropertiesParameters params = new PropertiesParameters();
params.put("type", "a");
params.put("q", q.toString());
params.put("r", r.toString());
params.put("h", h.toString());
params.put("exp1", String.valueOf(exp1));
params.put("exp2", String.valueOf(exp2));
params.put("sign0", String.valueOf(sign0));
params.put("sign1", String.valueOf(sign1));
if (generateCurveFieldGen) {
Field Fq = new ZrField(random, q);
CurveField curveField = new CurveField<Field>(random, Fq.newOneElement(), Fq.newZeroElement(), r, h);
params.put("genNoCofac", Base64.encodeBytes(curveField.getGenNoCofac().toBytes()));
}
return params;
}
public static void main(String[] args) {
if (args.length < 2)
throw new IllegalArgumentException("Too few arguments. Usage <rbits> <qbits>");
if (args.length > 2)
throw new IllegalArgumentException("Too many arguments. Usage <rbits> <qbits>");
Integer rBits = Integer.parseInt(args[0]);
Integer qBits = Integer.parseInt(args[1]);
TypeACurveGenerator generator = new TypeACurveGenerator(rBits, qBits, true);
PairingParameters curveParams = generator.generate();
System.out.println(curveParams.toString(" "));
}
}
| 5,156 | 34.565517 | 113 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a/TypeAPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.DegreeTwoExtensionQuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeAPairing extends AbstractPairing {
public static final String NAF_MILLER_PROJECTTIVE_METHOD = "naf-miller-projective";
public static final String MILLER_PROJECTTIVE_METHOD = "miller-projective";
public static final String MILLER_AFFINE_METHOD = "miller-affine";
protected int exp2;
protected int exp1;
protected int sign1;
protected BigInteger r;
protected BigInteger q;
protected BigInteger h;
protected BigInteger phikOnr;
protected byte[] genNoCofac;
protected Field Fq;
protected Field<? extends Point> Fq2;
protected Field<? extends Point> Eq;
public TypeAPairing(SecureRandom random, PairingParameters params) {
super(random);
initParams(params);
initMap(params);
initFields();
}
public TypeAPairing(PairingParameters params) {
this(new SecureRandom(), params);
}
protected void initParams(PairingParameters curveParams) {
// validate the type
String type = curveParams.getString("type");
if (type == null || !"a".equalsIgnoreCase(type))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'a'.");
// load params
exp2 = curveParams.getInt("exp2");
exp1 = curveParams.getInt("exp1");
sign1 = curveParams.getInt("sign1");
r = curveParams.getBigInteger("r"); // r = 2^exp2 + sign1 * 2^exp1 + sign0 * 1
q = curveParams.getBigInteger("q"); // we work in E(F_q) (and E(F_q^2))
h = curveParams.getBigInteger("h"); // r * h = q + 1
genNoCofac = curveParams.getBytes("genNoCofac", null);
}
protected void initFields() {
// Init Zr
Zr = initFp(r);
// Init Fq
Fq = initFp(q);
// Init Eq
Eq = initEq();
// Init Fq2
Fq2 = initFi();
// k=2, hence phi_k(q) = q + 1, phikOnr = (q+1)/r
phikOnr = h;
// Init G1, G2, GT
G1 = Eq;
G2 = G1;
GT = initGT();
}
protected Field initFp(BigInteger order) {
return new ZrField(random, order);
}
protected Field<? extends Point> initEq() {
// Remember the curve is: y^2 = x^3 + ax
return new CurveField<Field>(random,
Fq.newOneElement(), // a
Fq.newZeroElement(), // b
r, // order
h, // cofactor (r*h)=q+1=#E(F_q)
genNoCofac);
}
protected Field<? extends Point> initFi() {
return new DegreeTwoExtensionQuadraticField<Field>(random, Fq);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fq2);
}
protected void initMap(PairingParameters curveParams) {
String method = curveParams.getString("method", NAF_MILLER_PROJECTTIVE_METHOD);
if (NAF_MILLER_PROJECTTIVE_METHOD.endsWith(method)) {
pairingMap = new TypeATateNafProjectiveMillerPairingMap(this);
} else if (MILLER_PROJECTTIVE_METHOD.equals(method))
pairingMap = new TypeATateProjectiveMillerPairingMap(this);
else if (MILLER_AFFINE_METHOD.equals(method))
pairingMap = new TypeATateAffineMillerPairingMap(this);
else
throw new IllegalArgumentException("Pairing method not recognized. Method = " + method);
}
}
| 4,125 | 30.496183 | 102 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a/TypeATateAffineMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.DegreeTwoExtensionQuadraticElement;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingPreProcessing;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeATateAffineMillerPairingMap extends AbstractMillerPairingMap {
protected final TypeAPairing pairing;
protected int pairingPreProcessingTableLength = -1;
protected int pairingPreProcessingLengthInBytes = -1;
public TypeATateAffineMillerPairingMap(final TypeAPairing pairing) {
super(pairing);
this.pairing = pairing;
}
/**
* in1, in2 are from E(F_q), out from F_q^2
*/
public Element pairing(final Point in1, final Point in2) {
// could save a couple of inversions by avoiding
// this function and rewriting lineStep() to handle projective coords
// convert V from weighted projective (Jacobian) to affine
// i.e. (X, Y, Z) --> (X/Z^2, Y/Z^3)
// also sets z to 1
Point V = (Point) in1.duplicate();
Element Vx = V.getX();
Element Vy = V.getY();
Element z = pairing.Fq.newOneElement();
Element z2 = pairing.Fq.newOneElement();
Element Qx = in2.getX();
Element Qy = in2.getY();
// The coefficients of the line equation
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = pairing.Fq.newOneElement();
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
// Temp element
Element e0 = pairing.Fq.newElement();
// Remember that r = 2^exp2 + sign1 * 2^exp1 + sign0 * 1 (Solinas prime)
int i = 0;
int n = pairing.exp1;
for (; i < n; i++) {
// f = f^2 g_V,V(Q)
// where g_V,V = tangent at V
f.square();
tangentStep(f0, a, b, c, Vx, Vy, curveA, e0, Qx, Qy, f);
V.twice();
}
// Move to affine
pointToAffine(Vx, Vy, z, z2, e0);
Element f1;
Point V1 = pairing.Eq.newElement();
if (pairing.sign1 < 0) {
V1.set(V).negate();
f1 = f.duplicate().invert();
} else {
V1.set(V);
f1 = f.duplicate();
}
n = pairing.exp2;
for (; i < n; i++) {
f.square();
tangentStep(f0, a, b, c, Vx, Vy, curveA, e0, Qx, Qy, f);
V.twice();
}
f.mul(f1);
lineStep(f0, a, b, c, Vx, Vy, V1.getX(), V1.getY(), e0, Qx, Qy, f);
// Do final pow
Point out = pairing.Fq2.newElement();
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public boolean isProductPairingSupported() {
return true;
}
public Element pairing(Element[] in1, Element[] in2) {
// could save a couple of inversions by avoiding
// this function and rewriting lineStep() to handle projective coords
// convert V from weighted projective (Jacobian) to affine
// i.e. (X, Y, Z) --> (X/Z^2, Y/Z^3)
// also sets z to 1
Field refField = in1[0].getField();
Element[] Vs = new Element[in1.length];
Element[] V1s = new Element[in1.length];
for(int i=0; i< in1.length; i++){
Vs[i] = in1[i].duplicate();
V1s[i] = in1[i].getField().newElement();
}
// The coefficients of the line equation
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = pairing.Fq.newOneElement();
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
// Temp element
Element e0 = pairing.Fq.newElement();
// Remember that r = 2^exp2 + sign1 * 2^exp1 + sign0 * 1 (Solinas prime)
int i = 0;
int n = pairing.exp1;
for (; i < n; i++) {
// f = f^2 g_V,V(Q)
// where g_V,V = tangent at V
f.square();
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
refField.twice(Vs);
}
Element f1;
if (pairing.sign1 < 0) {
for (int j = 0; j < V1s.length; j++) {
V1s[j].set(Vs[j]).negate();
}
f1 = f.duplicate().invert();
} else {
for (int j = 0; j < V1s.length; j++) {
V1s[j].set(Vs[j]);
}
f1 = f.duplicate();
}
n = pairing.exp2;
for (; i < n; i++) {
f.square();
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
refField.twice(Vs);
}
f.mul(f1);
lineStep(f0, a, b, c, Vs, V1s, e0, in2, f);
// Do final pow
Point out = pairing.Fq2.newElement();
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public void finalPow(Element element) {
Element t0, t1;
t0 = element.getField().newElement();
t1 = element.getField().newElement();
tatePow((Point) t0, (Point) element, (Point) t1, pairing.phikOnr);
element.set(t0);
}
public int getPairingPreProcessingLengthInBytes() {
if (pairingPreProcessingLengthInBytes == -1){
pairingPreProcessingTableLength = pairing.exp2 + 1;
pairingPreProcessingLengthInBytes = 4 + (pairingPreProcessingTableLength * 3 * pairing.Fq.getLengthInBytes());
}
return pairingPreProcessingLengthInBytes;
}
public PairingPreProcessing pairing(Point in1) {
return new TypeAMillerAffinePairingPreProcessing(in1);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new TypeAMillerAffinePairingPreProcessing(source, offset);
}
public Element tatePow(Element element) {
Element t0, t1;
t0 = element.getField().newElement();
t1 = element.getField().newElement();
tatePow((DegreeTwoExtensionQuadraticElement) t0, (DegreeTwoExtensionQuadraticElement) element, (DegreeTwoExtensionQuadraticElement) t1, pairing.phikOnr);
element.set(t0);
return element;
}
final void tatePow(Point out, Point in, Point temp, BigInteger cofactor) {
Element in1 = in.getY();
//simpler but slower:
//element_pow_mpz(out, f, tateExp);
//1. Exponentiate by q-1
//which is equivalent to the following
temp.set(in).invert();
in1.negate();
in.mul(temp);
/* element_invert(temp, in);
element_neg(in1, in1);
element_mul(in, in, temp);
*/
//2. Exponentiate by (q+1)/r
//Instead of:
// element_pow_mpz(out, in, cofactor);
//we use Lucas sequences (see "Compressed Pairings", Scott and Barreto)
lucasOdd(out, in, temp, cofactor);
}
protected void millerStep(Point out, Element a, Element b, Element c, Element Qx, Element Qy) {
// we will map Q via (x,y) --> (-x, iy)
// hence:
// Re(a Qx + b Qy + c) = -a Q'x + c and
// Im(a Qx + b Qy + c) = b Q'y
Element re = out.getX();
Element im = out.getY();
re.set(c).sub(im.set(a).mul(Qx));
im.set(b).mul(Qy);
}
public int getPairingPreProcessingTableLength() {
getPairingPreProcessingLengthInBytes();
return pairingPreProcessingTableLength;
}
public class TypeAMillerAffinePairingPreProcessing extends AbstractMillerPairingPreProcessing {
public TypeAMillerAffinePairingPreProcessing(byte[] source, int offset) {
super(pairing, source, offset);
}
public TypeAMillerAffinePairingPreProcessing(Point in1) {
super(in1, getPairingPreProcessingTableLength());
Point V = (Point) in1.duplicate();
Point V1 = pairing.Eq.newElement();
Element Vx = V.getX();
Element Vy = V.getY();
Element V1x = V1.getX();
Element V1y = V1.getY();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = pairing.Fq.newOneElement();
Element temp = pairing.Fq.newElement();
int n = pairing.exp1, i;
for (i = 0; i < n; i++) {
computeTangent(processingInfo, a, b, c, Vx, Vy, curveA, temp);
V.twice();
}
if (pairing.sign1 < 0) {
V1.set(V).negate();
} else {
V1.set(V);
}
n = pairing.exp2;
for (; i < n; i++) {
computeTangent(processingInfo, a, b, c, Vx, Vy, curveA, temp);
V.twice();
}
computeLine(processingInfo, a, b, c, Vx, Vy, V1x, V1y, temp);
}
public Element pairing(Element in2) {
//TODO: use proj coords here too to shave off a little time
Point pointIn2 = (Point) in2;
Element Qx = pointIn2.getX();
Element Qy = pointIn2.getY();
int i, n;
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
Point out = pairing.Fq2.newElement();
n = pairing.exp1;
for (i = 0; i < n; i++) {
f.square();
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
}
if (pairing.sign1 < 0) {
out.set(f).invert();
} else {
out.set(f);
}
n = pairing.exp2;
for (; i < n; i++) {
f.square();
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
}
f.mul(out);
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(
TypeATateAffineMillerPairingMap.this,
(GTFiniteField) pairing.getGT(),
out
);
}
}
} | 11,062 | 30.518519 | 161 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a/TypeATateNafProjectiveMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeATateNafProjectiveMillerPairingMap extends AbstractMillerPairingMap {
protected final TypeAPairing pairing;
protected final byte[] r;
protected int pairingPreProcessingTableLength = -1;
protected int pairingPreProcessingLengthInBytes = -1;
public TypeATateNafProjectiveMillerPairingMap(TypeAPairing pairing) {
super(pairing);
this.pairing = pairing;
this.r = BigIntegerUtils.naf(pairing.r, (byte) 2);
}
/**
* in1, in2 are from E(F_q), out from F_q^2
*/
public Element pairing(Point P, Point Q) {
Point f = pairing.Fq2.newOneElement();
Point u = pairing.Fq2.newElement();
JacobPoint V = new JacobPoint(P.getX(), P.getY(), P.getX().getField().newOneElement());
Point nP = (Point) P.duplicate().negate();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
for (int i = r.length - 2; i >= 0; i--) {
twice(V, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.square().mul(u);
switch (r[i]) {
case 1:
add(V, P, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.mul(u);
break;
case -1:
add(V, nP, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.mul(u);
break;
}
}
Point out = pairing.Fq2.newElement();
tatePow(out, f, pairing.phikOnr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public void finalPow(Element element) {
Element t0 = element.getField().newElement();
tatePow((Point) t0, (Point) element, pairing.phikOnr);
element.set(t0);
}
public int getPairingPreProcessingLengthInBytes() {
if (pairingPreProcessingLengthInBytes == -1){
pairingPreProcessingTableLength = r.length - 1 + BigIntegerUtils.hammingWeight(r, r.length - 2);
pairingPreProcessingLengthInBytes = 4 + (pairingPreProcessingTableLength * 3 * pairing.Fq.getLengthInBytes());
}
return pairingPreProcessingLengthInBytes;
}
public PairingPreProcessing pairing(Point in1) {
return new TypeATateNafProjectiveMillerPairingPreProcessing(in1);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new TypeATateNafProjectiveMillerPairingPreProcessing(source, offset);
}
protected final void millerStep(Point out, Element a, Element b, Element c, Element Qx, Element Qy) {
out.getX().set(c).add(a.duplicate().mul((Qx)));
out.getY().set(b).mul(Qy);
}
final void tatePow(Point out, Point in, BigInteger cofactor) {
Element in1 = in.getY();
//simpler but slower:
//element_pow_mpz(out, f, tateExp);
//1. Exponentiate by q-1
//which is equivalent to the following
Point temp = (Point) in.duplicate().invert();
in1.negate();
in.mul(temp);
//2. Exponentiate by (q+1)/r
//Instead of:
// element_pow_mpz(out, in, cofactor);
//we use Lucas sequences (see "Compressed Pairings", Scott and Barreto)
lucasOdd(out, in, temp, cofactor);
}
/**
* point doubling in Jacobian coordinates
*/
final void twice(JacobPoint V, Element a, Element b, Element c) {
//if(V.isInfinity())
// return;
Element x = V.getX();
Element y = V.getY();
Element z = V.getZ();
//t1 = y^2
Element t1 = y.duplicate().square();
//t2 = 4 x t1 = 4 x y^2
Element t2 = x.duplicate().mul(t1).twice().twice();
//t4 = z^2
b.set(z).square();
//t5 = 3 x^2 + a t4^2 = 3 x^2 + a z^4
a.set(x).square().mul(3).add(b.duplicate().square());
c.set(a).mul(x).sub(t1).sub(t1);
//x3 = (3 x^2 + a z^4)^2 - 2 (4 x y^2)
//z3 = 2 y z
z.mul(y).twice();
//y3 = 3 x^2 + a z^4 (4 x y^2 - x3) - 8 y^4
V.setX(a.duplicate().square().sub(t2.duplicate().twice()));
V.setY(a.duplicate().mul(t2.duplicate().sub(V.getX())).sub(t1.duplicate().square().twice().twice().twice()));
a.mul(b);
b.mul(z);
}
/**
* add two point, save result in the first argument
*/
final void add(JacobPoint V, Point P, Element a, Element b, Element c) {
Element x1 = V.getX();
Element y1 = V.getY();
Element z1 = V.getZ();
Element x = P.getX();
Element y = P.getY();
//t1=z1^2
Element t1 = z1.duplicate().square();
//t2=z1t1
Element t2 = z1.duplicate().mul(t1);
//t3=xt1
Element t3 = x.duplicate().mul(t1);
//t4=Yt2
Element t4 = y.duplicate().mul(t2);
//t5=t3-x1
Element t5 = t3.duplicate().sub(x1);
//t6=t4-y1
Element t6 = t4.duplicate().sub(y1);
//t7=t5^2
Element t7 = t5.duplicate().square();
//t8=t5t7
Element t8 = t5.duplicate().mul(t7);
//t9=x1t7
Element t9 = x1.duplicate().mul(t7);
//x3=t6^2-(t8+2t9)
Element x3 = t6.duplicate().square().sub(t8.duplicate().add(t9.duplicate().twice()));
//y3=t6(t9-x3)-y1t8
Element y3 = t6.duplicate().mul(t9.duplicate().sub(x3)).sub((y1.duplicate().mul(t8)));
//z3=z1t5
Element z3 = z1.duplicate().mul(t5);
V.setX(x3);
V.setY(y3);
V.setZ(z3);
a.set(t6);
b.set(z3);
c.set(t6).mul(x).sub(z3.duplicate().mul(y));
//(z3 Q.y)i -(z3 y - t6 (Q.x + x))
// u.getX().set(Q.getX().duplicate().add(x).mul(t6).sub(z3.duplicate().mul(y)));
// u.getY().set(z3.duplicate().mul(Q.getY()));
}
public int getPairingPreProcessingTableLength() {
getPairingPreProcessingLengthInBytes();
return pairingPreProcessingTableLength;
}
public class TypeATateNafProjectiveMillerPairingPreProcessing extends AbstractMillerPairingPreProcessing {
public TypeATateNafProjectiveMillerPairingPreProcessing(byte[] source, int offset) {
super(pairing, source, offset);
}
public TypeATateNafProjectiveMillerPairingPreProcessing(Point in1) {
super(in1, getPairingPreProcessingTableLength());
JacobPoint V = new JacobPoint(in1.getX(), in1.getY(), in1.getX().getField().newOneElement());
Point nP = (Point) in1.duplicate().negate();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
for (int i = r.length - 2; i >= 0; i--) {
twice(V, a, b, c);
processingInfo.addRow(a, b, c);
switch (r[i]) {
case 1:
add(V, in1, a, b, c);
processingInfo.addRow(a, b, c);
break;
case -1:
add(V, nP, a, b, c);
processingInfo.addRow(a, b, c);
break;
}
}
}
public Element pairing(Element in2) {
Point Q = (Point) in2;
Point f = pairing.Fq2.newOneElement();
Point u = pairing.Fq2.newElement();
for (int i = r.length - 2, coeffIndex = 0; i >= 0; i--) {
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.square().mul(u);
coeffIndex++;
switch (r[i]) {
case 1:
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.mul(u);
coeffIndex++;
break;
case -1:
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.mul(u);
coeffIndex++;
break;
}
}
Point out = pairing.Fq2.newElement();
tatePow(out, f, pairing.phikOnr);
return new GTFiniteElement(TypeATateNafProjectiveMillerPairingMap.this, (GTFiniteField) pairing.getGT(), out);
}
}
}
| 9,348 | 31.461806 | 169 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a/TypeATateProjectiveMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingPreProcessing;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeATateProjectiveMillerPairingMap extends AbstractMillerPairingMap {
protected TypeAPairing pairing;
protected int pairingPreProcessingTableLength = -1;
protected int pairingPreProcessingLenghtInBytes = -1;
public TypeATateProjectiveMillerPairingMap(TypeAPairing pairing) {
super(pairing);
this.pairing = pairing;
}
/**
* in1, in2 are from E(F_q), out from F_q^2
*/
public Element pairing(Point in1, Point in2) {
// could save a couple of inversions by avoiding
// this function and rewriting lineStep() to handle projective coords
// convert V from weighted projective (Jacobian) to affine
// i.e. (X, Y, Z) --> (X/Z^2, Y/Z^3)
// also sets z to 1
Point V = (Point) in1.duplicate();
Element Vx = V.getX();
Element Vy = V.getY();
Element z = pairing.Fq.newOneElement();
Element z2 = pairing.Fq.newOneElement();
Element Qx = in2.getX();
Element Qy = in2.getY();
// The coefficients of the line equation
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
// Temp element
Element e0 = pairing.Fq.newElement();
// Remember that r = 2^exp2 + sign1 * 2^exp1 + sign0 * 1 (Solinas prime)
int i = 0;
int n = pairing.exp1;
for (; i < n; i++) {
// f = f^2 g_V,V(Q)
// where g_V,V = tangent at V
f.square();
tangentStepProjective(f0, a, b, c, Vx, Vy, z, z2, e0, Qx, Qy, f);
twiceProjective(e0, a, b, c, Vx, Vy, z, z2);
}
// Move to affine
pointToAffine(Vx, Vy, z, z2, e0);
Element f1;
Point V1 = pairing.Eq.newElement();
if (pairing.sign1 < 0) {
V1.set(V).negate();
f1 = f.duplicate().invert();
} else {
V1.set(V);
f1 = f.duplicate();
}
n = pairing.exp2;
for (; i < n; i++) {
f.square();
tangentStepProjective(f0, a, b, c, Vx, Vy, z, z2, e0, Qx, Qy, f);
twiceProjective(e0, a, b, c, Vx, Vy, z, z2);
}
f.mul(f1);
// Move to affine again
pointToAffine(Vx, Vy, z, z2, e0);
lineStep(f0, a, b, c, Vx, Vy, V1.getX(), V1.getY(), e0, Qx, Qy, f);
// Do final pow
Point out = pairing.Fq2.newElement();
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
@Override
public int getPairingPreProcessingLengthInBytes() {
if (pairingPreProcessingLenghtInBytes == -1){
pairingPreProcessingTableLength = pairing.exp2 + 1;
pairingPreProcessingLenghtInBytes = 4 + (pairingPreProcessingTableLength * 3 * pairing.Fq.getLengthInBytes());
}
return pairingPreProcessingLenghtInBytes;
}
public void finalPow(Element element) {
Element t0 = element.getField().newElement();
tatePow((Point) t0, (Point) element, pairing.phikOnr);
element.set(t0);
}
public PairingPreProcessing pairing(Point in1) {
return new TypeATateProjectiveMillerPairingPreProcessing(in1);
}
public boolean isProductPairingSupported() {
return true;
}
public Element pairing(Element[] in1, Element[] in2) {
// could save a couple of inversions by avoiding
// this function and rewriting lineStep() to handle projective coords
// convert V from weighted projective (Jacobian) to affine
// i.e. (X, Y, Z) --> (X/Z^2, Y/Z^3)
// also sets z to 1
Field refField = in1[0].getField();
CurveElement[] Vs = new CurveElement[in1.length];
CurveElement[] V1s = new CurveElement[in1.length];
for(int i=0; i< in1.length; i++){
Vs[i] = (CurveElement) in1[i].duplicate();
V1s[i] = (CurveElement) in1[i].getField().newElement();
}
// The coefficients of the line equation
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = pairing.Fq.newOneElement();
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
// Temp element
Element e0 = pairing.Fq.newElement();
// Remember that r = 2^exp2 + sign1 * 2^exp1 + sign0 * 1 (Solinas prime)
int i = 0;
int n = pairing.exp1;
for (; i < n; i++) {
// f = f^2 g_V,V(Q)
// where g_V,V = tangent at V
f.square();
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
refField.twice(Vs);
}
Element f1;
if (pairing.sign1 < 0) {
for (int j = 0; j < V1s.length; j++) {
V1s[j].set(Vs[j]).negate();
}
f1 = f.duplicate().invert();
} else {
for (int j = 0; j < V1s.length; j++) {
V1s[j].set(Vs[j]);
}
f1 = f.duplicate();
}
n = pairing.exp2;
for (; i < n; i++) {
f.square();
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
refField.twice(Vs);
}
f.mul(f1);
lineStep(f0, a, b, c, Vs, V1s, e0, in2, f);
// Do final pow
Point out = pairing.Fq2.newElement();
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new TypeATateProjectiveMillerPairingPreProcessing(source, offset);
}
protected final void millerStep(Point out, Element a, Element b, Element c, Element Qx, Element Qy) {
// we will map Q via (x,y) --> (-x, iy)
// hence:
// Re(a Qx + b Qy + c) = -a Q'x + c and
// Im(a Qx + b Qy + c) = b Q'y
Element rePart = out.getX();
Element imPart = out.getY();
rePart.set(c).sub(imPart.set(a).mul(Qx));
imPart.set(b).mul(Qy);
}
final void tatePow(Point out, Point in, Point temp, BigInteger cofactor) {
Element in1 = in.getY();
//simpler but slower:
//element_pow_mpz(out, f, tateExp);
//1. Exponentiate by q-1
//which is equivalent to the following
temp.set(in).invert();
in1.negate();
in.mul(temp);
//2. Exponentiate by (q+1)/r
//Instead of:
// element_pow_mpz(out, in, cofactor);
//we use Lucas sequences (see "Compressed Pairings", Scott and Barreto)
lucasOdd(out, in, temp, cofactor);
}
final void tatePow(Point out, Point in, BigInteger cofactor) {
Element in1 = in.getY();
//simpler but slower:
//element_pow_mpz(out, f, tateExp);
//1. Exponentiate by q-1
//which is equivalent to the following
Point temp = (Point) in.duplicate().invert();
in1.negate();
in.mul(temp);
//2. Exponentiate by (q+1)/r
//Instead of:
// element_pow_mpz(out, in, cofactor);
//we use Lucas sequences (see "Compressed Pairings", Scott and Barreto)
lucasOdd(out, in, temp, cofactor);
}
final void twiceProjective(Element e0, Element a, Element b, Element c, Element Vx, Element Vy, Element z, Element z2) {
// e0 = 3x^2 + cca z^4 (cca = 1)
e0.set(Vx).square().add(a.set(e0).twice()).add(a.set(z2).square());
// z = 2 y z
z.mul(Vy).twice();
z2.set(z).square();
//a = 4 x y^2
b.set(Vy).square();
a.set(Vx).mul(b).twice().twice();
// x_out = e0^2 - 2 a
c.set(a).twice();
Vx.set(e0).square().sub(c);
//b = 8y^4
b.square().twice().twice().twice();
//y_out = e0(a - x_out) - b
a.sub(Vx);
e0.mul(a);
Vy.set(e0).sub(b);
}
public int getPairingPreProcessingTableLength() {
getPairingPreProcessingLengthInBytes();
return pairingPreProcessingTableLength;
}
public class TypeATateProjectiveMillerPairingPreProcessing extends AbstractMillerPairingPreProcessing {
public TypeATateProjectiveMillerPairingPreProcessing(byte[] source, int offset) {
super(pairing, source, offset);
}
public TypeATateProjectiveMillerPairingPreProcessing(Point in1) {
super(in1, getPairingPreProcessingTableLength());
Point V = (Point) in1.duplicate();
Point V1 = pairing.Eq.newElement();
Element Vx = V.getX();
Element Vy = V.getY();
Element V1x = V1.getX();
Element V1y = V1.getY();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = pairing.Fq.newOneElement();
Element temp = pairing.Fq.newElement();
int n = pairing.exp1, i;
for (i = 0; i < n; i++) {
computeTangent(processingInfo, a, b, c, Vx, Vy, curveA, temp);
V.twice();
}
if (pairing.sign1 < 0) {
V1.set(V).negate();
} else {
V1.set(V);
}
n = pairing.exp2;
for (; i < n; i++) {
computeTangent(processingInfo, a, b, c, Vx, Vy, curveA, temp);
V.twice();
}
computeLine(processingInfo, a, b, c, Vx, Vy, V1x, V1y, temp);
}
public Element pairing(Element in2) {
//TODO: use proj coords here too to shave off a little time
Point pointIn2 = (Point) in2;
Element Qx = pointIn2.getX();
Element Qy = pointIn2.getY();
int i, n;
Point f0 = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
Point out = pairing.Fq2.newElement();
for (i = 0, n = pairing.exp1; i < n; i++) {
f.square();
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
}
if (pairing.sign1 < 0) {
out.set(f).invert();
} else {
out.set(f);
}
for (n = pairing.exp2; i < n; i++) {
f.square();
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
}
f.mul(out);
millerStep(f0, processingInfo.table[i][0], processingInfo.table[i][1], processingInfo.table[i][2], Qx, Qy);
f.mul(f0);
tatePow(out, f, f0, pairing.phikOnr);
return new GTFiniteElement(
TypeATateProjectiveMillerPairingMap.this,
(GTFiniteField) pairing.getGT(),
out
);
}
}
}
| 11,942 | 30.101563 | 124 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a1/TypeA1CurveGenerator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a1;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeA1CurveGenerator implements PairingParametersGenerator {
protected SecureRandom random;
protected int numPrimes, bits;
public TypeA1CurveGenerator(SecureRandom random, int numPrimes, int bits) {
this.random = random;
this.numPrimes = numPrimes;
this.bits = bits;
}
public TypeA1CurveGenerator(int numPrimes, int bits) {
this(new SecureRandom(), numPrimes, bits);
}
public PairingParameters generate() {
BigInteger[] primes = new BigInteger[numPrimes];
BigInteger order, n, p;
long l;
while (true) {
// System.out.printf("Finding order...%n");
while (true) {
order = BigInteger.ONE;
for (int i = 0; i < numPrimes; i++) {
boolean isNew = false;
while (!isNew) {
// primes[i] = BigIntegerUtils.generateSolinasPrime(bits, random);
primes[i] = BigInteger.probablePrime(bits, random);
isNew = true;
for (int j = 0; j < i; j++) {
if (primes[i].equals(primes[j])) {
isNew = false;
break;
}
}
}
order = order.multiply(primes[i]);
}
break;
// if ((order.bitLength() + 7) / 8 == order.bitLength() / 8)
// break;
}
// System.out.printf("order= %s%n", order);
// If order is even, ideally check all even l, not just multiples of 4
// System.out.printf("Finding l...%n");
l = 4;
n = order.multiply(BigIntegerUtils.FOUR);
p = n.subtract(BigInteger.ONE);
while (!p.isProbablePrime(10)) {
p = p.add(n);
l += 4;
}
// System.out.printf("l=%d%n",l);
// System.out.printf("lhs=%d, rhs=%d%n",(p.bitLength() + 7) / 8, (p.bitLength() / 8));
// if ((p.bitLength() + 7) / 8 == p.bitLength() / 8)
// break;
break;
// System.out.printf("No way, repeat!%n");
}
// System.out.printf("order hamming weight=%d%n", BigIntegerUtils.hammingWeight(order));
PropertiesParameters params = new PropertiesParameters();
params.put("type", "a1");
params.put("p", p.toString());
params.put("n", order.toString());
for (int i = 0; i < primes.length; i++) {
params.put("n" + i, primes[i].toString());
}
params.put("l", String.valueOf(l));
return params;
}
public static void main(String[] args) {
TypeA1CurveGenerator generator = new TypeA1CurveGenerator(3, 512);
PairingParameters curveParams = generator.generate();
System.out.println(curveParams.toString(" "));
}
}
| 3,438 | 31.443396 | 97 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a1/TypeA1Pairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a1;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.DegreeTwoExtensionQuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeA1Pairing extends AbstractPairing {
public static final String NAF_MILLER_PROJECTTIVE_METHOD = "naf-miller-projective";
public static final String MILLER_AFFINE_METHOD = "miller-affine";
protected BigInteger r;
protected BigInteger p;
protected long l;
protected BigInteger phikOnr;
protected Field Fp;
protected Field<? extends Point> Fq2;
protected Field<? extends Point> Eq;
public TypeA1Pairing(PairingParameters params) {
this(new SecureRandom(), params);
}
public TypeA1Pairing(SecureRandom random, PairingParameters params) {
super(random);
initParams(params);
initMap(params);
initFields();
}
protected void initParams(PairingParameters curveParams) {
// validate the type
String type = curveParams.getString("type");
if (type == null || !"a1".equalsIgnoreCase(type))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'a1'.");
// load params
p = curveParams.getBigInteger("p");
r = curveParams.getBigInteger("n");
l = curveParams.getLong("l");
}
protected void initFields() {
// Init Zr
Zr = initFp(r);
// Init Fp
Fp = initFp(p);
//k=2, hence phi_k(q) = q + 1, phikOnr = (q+1)/r
phikOnr = BigInteger.valueOf(l);
// Init Eq
Eq = initEq();
// Init Fq2
Fq2 = initFi();
// Init G1, G2, GT
G1 = Eq;
G2 = G1;
GT = initGT();
}
protected Field initFp(BigInteger order) {
return new ZrField(random, order);
}
protected Field<? extends Point> initEq() {
return new CurveField<Field>(random, Fp.newOneElement(), Fp.newZeroElement(), r, phikOnr);
}
protected Field<? extends Point> initFi() {
return new DegreeTwoExtensionQuadraticField<Field>(random, Fp);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fq2);
}
protected void initMap(PairingParameters curveParams) {
String method = curveParams.getString("method", NAF_MILLER_PROJECTTIVE_METHOD);
if (NAF_MILLER_PROJECTTIVE_METHOD.endsWith(method)) {
pairingMap = new TypeA1TateNafProjectiveMillerPairingMap(this);
} else if (MILLER_AFFINE_METHOD.equals(method))
pairingMap = new TypeA1TateAffineMillerPairingMap(this);
else
throw new IllegalArgumentException("Pairing method not recognized. Method = " + method);
}
} | 3,195 | 28.321101 | 103 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a1/TypeA1TateAffineMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a1;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeA1TateAffineMillerPairingMap extends AbstractMillerPairingMap<Element> {
protected TypeA1Pairing pairing;
public TypeA1TateAffineMillerPairingMap(TypeA1Pairing pairing) {
super(pairing);
this.pairing = pairing;
}
public Element pairing(Point in1, Point in2) {
Element Px = in1.getX();
Element Py = in1.getY();
Element Qx = in2.getX();
Element Qy = in2.getY();
Point V = (Point) in1.duplicate();
Element Vx = V.getX();
Element Vy = V.getY();
Element a = pairing.Fp.newElement();
Element b = pairing.Fp.newElement();
Element c = pairing.Fp.newElement();
Element curveA = pairing.Fp.newOneElement();
Element e0 = pairing.Fp.newElement();
Point<Element> f0 = pairing.Fq2.newElement();
Point out = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
tangentStep(f0, a, b, c, Vx, Vy, curveA, e0, Qx, Qy, f);
V.twice();
if (pairing.r.testBit(m)) {
lineStep(f0, a, b, c, Vx, Vy, Px, Py, e0, Qx, Qy, f);
V.add(in1);
}
f.square();
}
tangentStep(f0, a, b, c, Vx, Vy, curveA, e0, Qx, Qy, f);
// Tate exponentiation.
// Simpler but slower:
// element_pow_mpz(out, f, p->tateExp);
// Use this trick instead:
f0.set(f).invert();
f.getY().negate();
f.mul(f0);
out.set(f).pow(pairing.phikOnr);
/* We could use this instead but p->h is small so this does not help much
a_tateexp(out, f, f0, p->h);
*/
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public boolean isProductPairingSupported() {
return true;
}
public Element pairing(Element[] in1, Element[] in2) {
Field refField = in1[0].getField();
CurveElement[] Vs = new CurveElement[in1.length];
for (int i = 0; i < in1.length; i++) {
Vs[i] = (CurveElement) in1[i].duplicate();
}
Element a = pairing.Fp.newElement();
Element b = pairing.Fp.newElement();
Element c = pairing.Fp.newElement();
Element curveA = pairing.Fp.newOneElement();
Element e0 = pairing.Fp.newElement();
Point<Element> f0 = pairing.Fq2.newElement();
Point out = pairing.Fq2.newElement();
Point f = pairing.Fq2.newOneElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
refField.twice(Vs);
if (pairing.r.testBit(m)) {
lineStep(f0, a, b, c, Vs, in1, e0, in2, f);
refField.add(Vs, in1);
}
f.square();
}
tangentStep(f0, a, b, c, Vs, curveA, e0, in2, f);
// Tate exponentiation.
// Simpler but slower:
// element_pow_mpz(out, f, p->tateExp);
// Use this trick instead:
f0.set(f).invert();
f.getY().negate();
f.mul(f0);
out.set(f).pow(pairing.phikOnr);
/* We could use this instead but p->h is small so this does not help much
a_tateexp(out, f, f0, p->h);
*/
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public void finalPow(Element element) {
Element t0, t1;
t0 = element.getField().newElement();
t1 = element.getField().newElement();
tatePow((Point) t0, (Point) element, (Point) t1, pairing.phikOnr);
element.set(t0);
}
public Element tatePow(Element element) {
Element t0, t1;
t0 = element.getField().newElement();
t1 = element.getField().newElement();
tatePow((Point) t0, (Point) element, (Point) t1, pairing.phikOnr);
element.set(t0);
return element;
}
final void tatePow(Point out, Point in, Point temp, BigInteger cofactor) {
Element in1 = in.getY();
//simpler but slower:
//element_pow_mpz(out, f, tateExp);
//1. Exponentiate by q-1
//which is equivalent to the following
temp.set(in).invert();
in1.negate();
in.mul(temp);
/* element_invert(temp, in);
element_neg(in1, in1);
element_mul(in, in, temp);
*/
//2. Exponentiate by (q+1)/r
//Instead of:
// element_pow_mpz(out, in, cofactor);
//we use Lucas sequences (see "Compressed Pairings", Scott and Barreto)
lucasOdd(out, in, temp, cofactor);
}
protected void millerStep(Point out, Element a, Element b, Element c, Element Qx, Element Qy) {
// we will map Q via (x,y) --> (-x, iy)
// hence:
// Re(a Qx + b Qy + c) = -a Q'x + c and
// Im(a Qx + b Qy + c) = b Q'y
Element rePart = out.getX();
Element imPart = out.getY();
rePart.set(c).sub(imPart.set(a).mul(Qx));
imPart.set(b).mul(Qy);
}
}
| 5,618 | 28.11399 | 99 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a1/TypeA1TateNafProjectiveMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.a1;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeA1TateNafProjectiveMillerPairingMap extends AbstractMillerPairingMap {
protected final TypeA1Pairing pairing;
protected final byte[] r;
protected int pairingPreProcessingTableLength = -1;
protected int pairingPreProcessingLengthInBytes = -1;
public TypeA1TateNafProjectiveMillerPairingMap(TypeA1Pairing pairing) {
super(pairing);
this.pairing = pairing;
this.r = BigIntegerUtils.naf(pairing.r, (byte) 2);
}
/**
* in1, in2 are from E(F_q), out from F_q^2
*/
public Element pairing(Point P, Point Q) {
Point f = pairing.Fq2.newOneElement();
Point u = pairing.Fq2.newElement();
JacobPoint V = new JacobPoint(P.getX(), P.getY(), P.getX().getField().newOneElement());
Point nP = (Point) P.duplicate().negate();
Element a = pairing.Fp.newElement();
Element b = pairing.Fp.newElement();
Element c = pairing.Fp.newElement();
for (int i = r.length - 2; i >= 0; i--) {
twice(V, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.square().mul(u);
switch (r[i]) {
case 1:
add(V, P, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.mul(u);
break;
case -1:
add(V, nP, a, b, c);
millerStep(u, a, b, c, Q.getX(), Q.getY());
f.mul(u);
break;
}
}
Point out = pairing.Fq2.newElement();
tatePow(out, f);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public void finalPow(Element element) {
Element t0 = element.getField().newElement();
tatePow((Point) t0, (Point) element);
element.set(t0);
}
public int getPairingPreProcessingLengthInBytes() {
if (pairingPreProcessingLengthInBytes == -1){
pairingPreProcessingTableLength = r.length - 1 + BigIntegerUtils.hammingWeight(r, r.length - 2);
pairingPreProcessingLengthInBytes = 4 + (pairingPreProcessingTableLength * 3 * pairing.Fp.getLengthInBytes());
}
return pairingPreProcessingLengthInBytes;
}
public PairingPreProcessing pairing(Point in1) {
return new TypeA1TateNafProjectiveMillerPairingPreProcessing(in1);
}
protected final void millerStep(Point out, Element a, Element b, Element c, Element Qx, Element Qy) {
out.getX().set(c).add(a.duplicate().mul((Qx)));
out.getY().set(b).mul(Qy);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new TypeA1TateNafProjectiveMillerPairingPreProcessing(source, offset);
}
final void tatePow(Point out, Point in) {
out.set(in).invert();
in.getY().negate();
in.mul(out);
out.set(in).pow(pairing.phikOnr);
}
/**
* used by tate pairing, point doubling in Jacobian coordinates, and return the value of f
*/
final void twice(JacobPoint V, Element a, Element b, Element c) {
//if(V.isInfinity())
// return;
Element x = V.getX();
Element y = V.getY();
Element z = V.getZ();
//t1 = y^2
Element t1 = y.duplicate().square();
//t2 = 4 x t1 = 4 x y^2
Element t2 = x.duplicate().mul(t1).twice().twice();
//t4 = z^2
Element t4 = z.duplicate().square();
//t5 = 3 x^2 + a t4^2 = 3 x^2 + a z^4
Element t5 = x.duplicate().square().mul(3).add(t4.duplicate().square());
//x3 = (3 x^2 + a z^4)^2 - 2 (4 x y^2)
Element x3 = t5.duplicate().square().sub(t2.duplicate().twice());
//y3 = 3 x^2 + a z^4 (4 x y^2 - x3) - 8 y^4
Element y3 = t5.duplicate().mul(t2.duplicate().sub(x3)).sub(t1.duplicate().square().twice().twice().twice());
//z3 = 2 y z
Element z3 = y.duplicate().mul(z).twice();
V.setX(x3);
V.setY(y3);
V.setZ(z3);
b.set(z3.duplicate().mul(t4));
// a.set(Q.getX().duplicate().mul(t4).add(x).mul(t5));
// c.set(t1.twice());
a.set(t5).mul(t4);
c.set(t5).mul(x).sub(t1).sub(t1);
// (2 y z * z^2 * Q.y)i - (2 y^2 - ((3 x^2 + a z^4) (z^2 Q.x + x)))
// (2 y z * z^2 * Q.y)i - (2 y^2 - ((3 x^2 + a z^4)x + (3 x^2 + a z^4)(z^2 Q.x)))
// u.getX().set(t4.duplicate().mul(Q.getX()).add(x).mul(t5).sub(t1).sub(t1));
// u.getY().set(z3.duplicate().mul(t4).mul(Q.getY()));
}
/**
* used by Tate paring, add two point, save result in the first argument, return the value of f
*/
final void add(JacobPoint V, Point P, Element a, Element b, Element c) {
Element x1 = V.getX();
Element y1 = V.getY();
Element z1 = V.getZ();
Element x = P.getX();
Element y = P.getY();
//t1=z1^2
Element t1 = z1.duplicate().square();
//t2=z1t1
Element t2 = z1.duplicate().mul(t1);
//t3=xt1
Element t3 = x.duplicate().mul(t1);
//t4=Yt2
Element t4 = y.duplicate().mul(t2);
//t5=t3-x1
Element t5 = t3.duplicate().sub(x1);
//t6=t4-y1
Element t6 = t4.duplicate().sub(y1);
//t7=t5^2
Element t7 = t5.duplicate().square();
//t8=t5t7
Element t8 = t5.duplicate().mul(t7);
//t9=x1t7
Element t9 = x1.duplicate().mul(t7);
//x3=t6^2-(t8+2t9)
Element x3 = t6.duplicate().square().sub(t8.duplicate().add(t9.duplicate().twice()));
//y3=t6(t9-x3)-y1t8
Element y3 = t6.duplicate().mul(t9.duplicate().sub(x3)).sub((y1.duplicate().mul(t8)));
//z3=z1t5
Element z3 = z1.duplicate().mul(t5);
V.setX(x3);
V.setY(y3);
V.setZ(z3);
a.set(t6);
b.set(z3);
c.set(t6).mul(x).sub(z3.duplicate().mul(y));
//(z3 Q.y)i -(z3 y - t6 (Q.x + x))
// u.getX().set(Q.getX().duplicate().add(x).mul(t6).sub(z3.duplicate().mul(y)));
// u.getY().set(z3.duplicate().mul(Q.getY()));
}
public int getPairingPreProcessingTableLength() {
getPairingPreProcessingLengthInBytes();
return pairingPreProcessingTableLength;
}
public class TypeA1TateNafProjectiveMillerPairingPreProcessing extends AbstractMillerPairingPreProcessing {
public TypeA1TateNafProjectiveMillerPairingPreProcessing(byte[] source, int offset) {
super(pairing, source, offset);
}
public TypeA1TateNafProjectiveMillerPairingPreProcessing(Point in1) {
super(in1, getPairingPreProcessingTableLength());
JacobPoint V = new JacobPoint(in1.getX(), in1.getY(), in1.getX().getField().newOneElement());
Point nP = (Point) in1.duplicate().negate();
Element a = pairing.Fp.newElement();
Element b = pairing.Fp.newElement();
Element c = pairing.Fp.newElement();
for (int i = r.length - 2; i >= 0; i--) {
twice(V, a, b, c);
processingInfo.addRow(a, b, c);
switch (r[i]) {
case 1:
add(V, in1, a, b, c);
processingInfo.addRow(a, b, c);
break;
case -1:
add(V, nP, a, b, c);
processingInfo.addRow(a, b, c);
break;
}
}
}
public Element pairing(Element in2) {
Point Q = (Point) in2;
Point f = pairing.Fq2.newOneElement();
Point u = pairing.Fq2.newElement();
for (int i = r.length - 2, coeffIndex = 0; i >= 0; i--) {
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.square().mul(u);
coeffIndex++;
switch (r[i]) {
case 1:
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.mul(u);
coeffIndex++;
break;
case -1:
millerStep(u, processingInfo.table[coeffIndex][0], processingInfo.table[coeffIndex][1], processingInfo.table[coeffIndex][2], Q.getX(), Q.getY());
f.mul(u);
coeffIndex++;
break;
}
}
Point out = pairing.Fq2.newElement();
tatePow(out, f);
return new GTFiniteElement(TypeA1TateNafProjectiveMillerPairingMap.this, (GTFiniteField) pairing.getGT(), out);
}
}
}
| 9,512 | 32.734043 | 169 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/AbstractPairingAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor.AbstractAccumulator;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor.Accumulator;
import java.util.concurrent.Callable;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public abstract class AbstractPairingAccumulator extends AbstractAccumulator<Element> implements PairingAccumulator {
protected Pairing pairing;
public AbstractPairingAccumulator(Pairing pairing) {
this(pairing, pairing.getGT().newOneElement());
}
public AbstractPairingAccumulator(Pairing pairing, Element value) {
this.pairing = pairing;
this.result = value;
}
public Accumulator<Element> accumulate(Callable<Element> callable) {
throw new IllegalStateException("Invalid call method!");
}
public PairingAccumulator addPairing(final Element e1, final Element e2) {
super.accumulate(new Callable<Element>() {
public Element call() throws Exception {
return pairing.pairing(e1, e2);
}
});
return this;
}
public PairingAccumulator addPairingInverse(final Element e1, final Element e2) {
super.accumulate(new Callable<Element>() {
public Element call() throws Exception {
return pairing.pairing(e1, e2).invert();
}
});
return this;
}
public PairingAccumulator addPairing(final PairingPreProcessing pairingPreProcessing, final Element e2) {
super.accumulate(new Callable<Element>() {
public Element call() throws Exception {
return pairingPreProcessing.pairing(e2);
}
});
return this;
}
}
| 1,924 | 28.615385 | 117 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/MultiThreadedMulPairingAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class MultiThreadedMulPairingAccumulator extends AbstractPairingAccumulator {
public MultiThreadedMulPairingAccumulator(Pairing pairing) {
super(pairing);
}
public MultiThreadedMulPairingAccumulator(Pairing pairing, Element value) {
super(pairing, value);
}
protected void reduce(Element value) {
this.result.mul(value);
}
}
| 589 | 21.692308 | 84 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/PairingAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor.Accumulator;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public interface PairingAccumulator extends Accumulator<Element> {
public PairingAccumulator addPairing(Element e1, Element e2);
public PairingAccumulator addPairingInverse(Element e1, Element e2);
public PairingAccumulator addPairing(PairingPreProcessing pairingPreProcessing, Element e2);
}
| 600 | 29.05 | 96 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/PairingAccumulatorFactory.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class PairingAccumulatorFactory {
private static final PairingAccumulatorFactory INSTANCE = new PairingAccumulatorFactory();
public static PairingAccumulatorFactory getInstance() {
return INSTANCE;
}
private boolean multiThreadingEnabled;
private PairingAccumulatorFactory() {
this.multiThreadingEnabled = false; // Runtime.getRuntime().availableProcessors() > 1;
}
public PairingAccumulator getPairingMultiplier(Pairing pairing) {
return isMultiThreadingEnabled() ? new MultiThreadedMulPairingAccumulator(pairing)
: new SequentialMulPairingAccumulator(pairing);
}
public PairingAccumulator getPairingMultiplier(Pairing pairing, Element element) {
return isMultiThreadingEnabled() ? new MultiThreadedMulPairingAccumulator(pairing, element)
: new SequentialMulPairingAccumulator(pairing, element);
}
public boolean isMultiThreadingEnabled() {
return multiThreadingEnabled;
}
public void setMultiThreadingEnabled(boolean multiThreadingEnabled) {
this.multiThreadingEnabled = multiThreadingEnabled;
}
}
| 1,358 | 29.2 | 99 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/ProductPairingAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.Pool;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor.Accumulator;
import java.util.concurrent.Callable;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ProductPairingAccumulator implements PairingAccumulator {
private Pairing pairing;
private int cursor;
private Element[] in1, in2;
private Element result;
public ProductPairingAccumulator(Pairing pairing, int n) {
this.pairing = pairing;
this.in1 = new Element[n];
this.in2 = new Element[n];
this.cursor = 0;
}
public Accumulator<Element> accumulate(Callable<Element> callable) {
throw new IllegalStateException("Not supported!!!");
}
public Accumulator<Element> awaitTermination() {
awaitResult();
return this;
}
public Element getResult() {
return result;
}
public Pool<Element> submit(Callable<Element> callable) {
throw new IllegalStateException("Not supported!!!");
}
public Pool<Element> submit(Runnable runnable) {
throw new IllegalStateException("Not supported!!!");
}
public PairingAccumulator addPairing(Element e1, Element e2) {
in1[cursor] = e1;
in2[cursor++] = e2;
return this;
}
public PairingAccumulator addPairing(PairingPreProcessing pairingPreProcessing, Element e2) {
throw new IllegalStateException("Not supported!!!");
}
public PairingAccumulator addPairingInverse(Element e1, Element e2) {
throw new IllegalStateException("Not supported!!!");
}
public Element awaitResult(){
return (result = pairing.pairing(in1, in2));
}
}
| 1,928 | 24.381579 | 97 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/accumulator/SequentialMulPairingAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.accumulator;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.Pool;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor.Accumulator;
import java.util.concurrent.Callable;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class SequentialMulPairingAccumulator implements PairingAccumulator {
private Pairing pairing;
private Element value;
public SequentialMulPairingAccumulator(Pairing pairing) {
this.pairing = pairing;
this.value = pairing.getGT().newOneElement();
}
public SequentialMulPairingAccumulator(Pairing pairing, Element value) {
this.pairing = pairing;
this.value = value;
}
public Accumulator<Element> accumulate(Callable<Element> callable) {
throw new IllegalStateException("Not supported!!!");
}
public Accumulator<Element> awaitTermination() {
return this;
}
public Element getResult() {
return value;
}
public Pool submit(Callable<Element> callable) {
throw new IllegalStateException("Not supported!!!");
}
public Pool submit(Runnable runnable) {
throw new IllegalStateException("Not supported!!!");
}
public PairingAccumulator addPairing(Element e1, Element e2) {
value.mul(pairing.pairing(e1, e2));
return this;
}
public PairingAccumulator addPairing(PairingPreProcessing pairingPreProcessing, Element e2) {
value.mul(pairingPreProcessing.pairing(e2));
return this;
}
public PairingAccumulator addPairingInverse(Element e1, Element e2) {
value.mul(pairing.pairing(e1, e2).invert());
return this;
}
public Element awaitResult(){
return value;
}
}
| 1,917 | 24.918919 | 97 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/d/TypeDPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.d;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.QuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeDPairing extends AbstractPairing {
protected PairingParameters curveParams;
protected int k;
protected BigInteger q, n, r, h;
protected BigInteger a, b;
protected PolyModElement xPowq, xPowq2;
protected Element nqrInverse, nqrInverseSquare;
protected BigInteger tateExp, phikOnr;
protected Field Fq;
protected Field<? extends Point<Polynomial>> Fqk;
protected PolyModField Fqd;
protected CurveField Eq, Etwist;
public TypeDPairing(SecureRandom random, PairingParameters curveParams) {
super(random);
this.curveParams = curveParams;
initParams();
initMap();
initFields();
}
public TypeDPairing(PairingParameters curveParams) {
this(new SecureRandom(), curveParams);
}
public boolean isSymmetric() {
return false;
}
public PropertiesParameters saveTwist() {
PropertiesParameters params = (PropertiesParameters) curveParams;
params.putBytes("twist.a", Etwist.getA().toBytes());
params.putBytes("twist.b", Etwist.getB().toBytes());
params.putBytes("twist.gen", Etwist.getGen().toBytes());
return params;
}
protected void initParams() {
// validate the type
String type = curveParams.getString("type");
if (type == null || !"d".equalsIgnoreCase(type))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'd'.");
// load params
k = curveParams.getInt("k");
if (k % 2 != 0)
throw new IllegalArgumentException("odd k not implemented anymore");
r = curveParams.getBigInteger("r");
q = curveParams.getBigInteger("q");
h = curveParams.getBigInteger("h");
n = curveParams.getBigInteger("n");
a = curveParams.getBigInteger("a");
b = curveParams.getBigInteger("b");
}
protected void initFields() {
// Init Zr
Zr = initFp(r);
// Init Fq
Fq = initFp(q);
// Init Eq
Eq = initEq();
// Init Fqx
PolyField polyField = initPoly();
// Init the irreducible polynomial
int d = k / 2;
PolyElement<Element> irreduciblePoly = polyField.newElement();
List<Element> irreduciblePolyCoeff = irreduciblePoly.getCoefficients();
for (int i = 0; i < d; i++) {
irreduciblePolyCoeff.add(polyField.getTargetField().newElement().set(curveParams.getBigIntegerAt("coeff", i)));
}
irreduciblePolyCoeff.add(polyField.getTargetField().newElement().setToOne());
// init Fqd
Fqd = initPolyMod(irreduciblePoly);
// init Fqk
Fqk = initQuadratic();
// Compute constants involved in the final powering.
if (k == 6) {
phikOnr = q.multiply(q).subtract(q).add(BigInteger.ONE).divide(r);
PolyModElement polyModElement = Fqd.newElement();
polyModElement.getCoefficient(1).setToOne();
polyModElement.pow(q);
xPowq = polyModElement;
xPowq2 = polyModElement.duplicate().square();
} else {
tateExp = Fqk.getOrder().subtract(BigInteger.ONE).divide(r);
}
// init etwist
if (curveParams.containsKey("twist.a")) {
// load the twist
Element twistA = Fqd.newElementFromBytes(curveParams.getBytes("twist.a"));
Element twistB = Fqd.newElementFromBytes(curveParams.getBytes("twist.b"));
Etwist = new CurveField(random, twistA, twistB, r, curveParams.getBytes("twist.gen"));
} else {
Etwist = initEqMap().twist();
}
// ndonr temporarily holds the trace.
BigInteger ndonr = q.subtract(n).add(BigInteger.ONE) ;
// Negate it because we want the trace of the twist.
ndonr = ndonr.negate();
ndonr = BigIntegerUtils.pbc_mpz_curve_order_extn(q, ndonr, d);
ndonr = ndonr.divide(r);
Etwist.setQuotientCmp(ndonr);
nqrInverse = Fqd.getNqr().duplicate().invert();
nqrInverseSquare = nqrInverse.duplicate().square();
// Init G1, G2, GT
G1 = Eq;
G2 = Etwist;
GT = initGT();
}
protected Field initFp(BigInteger order) {
return new ZrField(random, order);
}
protected CurveField initEq() {
return new CurveField(random, Fq.newElement().set(a),Fq.newElement().set(b), r, h);
}
protected CurveField initEqMap() {
return new CurveField(random, Fqd.newElement().map(Eq.getA()), Fqd.newElement().map(Eq.getB()), r);
}
protected PolyField initPoly() {
return new PolyField(random, Fq);
}
protected PolyModField initPolyMod(PolyElement irred) {
return new PolyModField(random, irred, curveParams.getBigInteger("nqr"));
}
protected QuadraticField initQuadratic() {
return new QuadraticField(random, Fqd);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fqk);
}
protected void initMap() {
pairingMap = new TypeDTateAffineNoDenomMillerPairingMap(this);
}
} | 6,081 | 29.873096 | 123 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/d/TypeDTateAffineNoDenomMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.d;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModElement;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingPreProcessing;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeDTateAffineNoDenomMillerPairingMap extends AbstractMillerPairingMap<Polynomial> {
protected TypeDPairing pairing;
protected int pairingPreProcessingTableLength = -1;
protected int pairingPreProcessingLengthInBytes = -1;
public TypeDTateAffineNoDenomMillerPairingMap(TypeDPairing pairing) {
super(pairing);
this.pairing = pairing;
}
public Element pairing(Point in1, Point in2) {
// map from twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic non-residue used to construct the twist
Polynomial Qx = (Polynomial) in2.getX().duplicate().mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Polynomial Qy = (Polynomial) in2.getY().duplicate().mul(pairing.nqrInverseSquare);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), tatePow(pairing(in1, Qx, Qy)));
}
public boolean isProductPairingSupported() {
return true;
}
public Element pairing(Element[] in1, Element[] in2) {
int n = in1.length;
CurveElement[] Qs = new CurveElement[n];
for (int i = 0; i < n; i++) {
Point Q = (Point) in2[i];
Qs[i] = (CurveElement) Q.getField().newElement();
// map from twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic non-residue used to construct the twist
Qs[i].getX().set(Q.getX()).mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Qs[i].getY().set(Q.getY()).mul(pairing.nqrInverseSquare);
}
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), tatePow(pairingInternal(in1, Qs)));
}
public void finalPow(Element element) {
element.set(tatePow(element));
}
public int getPairingPreProcessingLengthInBytes() {
if (pairingPreProcessingLengthInBytes == -1){
pairingPreProcessingTableLength = pairing.r.bitLength() + BigIntegerUtils.hammingWeight(pairing.r) - 1;
pairingPreProcessingLengthInBytes = 4 + (pairingPreProcessingTableLength * 3 * pairing.Fq.getLengthInBytes());
}
return pairingPreProcessingLengthInBytes;
}
public PairingPreProcessing pairing(Point in1) {
return new TypeDMillerNoDenomAffinePairingPreProcessing(in1);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new TypeDMillerNoDenomAffinePairingPreProcessing(source, offset);
}
public boolean isAlmostCoddh(Element a, Element b, Element c, Element d) {
// Twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic nonresidue used to construct the twist.
Element cx = ((Point) c).getX().duplicate().mul(pairing.nqrInverse);
Element dx = ((Point) d).getX().duplicate().mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Element cy = ((Point) c).getY().duplicate().mul(pairing.nqrInverseSquare);
Element dy = ((Point) d).getY().duplicate().mul(pairing.nqrInverseSquare);
Element t0 = pairing((Point) a, (Polynomial) dx, (Polynomial) dy);
Element t1 = pairing((Point) b, (Polynomial) cx, (Polynomial) cy);
t0 = tatePow(t0);
t1 = tatePow(t1);
Element t2 = t0.duplicate().mul(t1);
if (t2.isOne())
return true; // We were given g, g^x, h, h^-x.
else {
// Cheaply check the other case.
t2.set(t0).mul(t1.invert());
if (t2.isOne())
return true; // We were given g, g^x, h, h^x.
}
return false;
}
public Element tatePow(Element element) {
if (pairing.k == 6) {
Point<Polynomial> e0, e3;
PolyModElement e2;
e0 = pairing.Fqk.newElement();
e2 = pairing.Fqd.newElement();
e3 = pairing.Fqk.newElement();
Polynomial e0re = e0.getX();
Polynomial e0im = e0.getY();
Element e0re0 = e0re.getCoefficient(0);
Element e0im0 = e0im.getCoefficient(0);
Point<Polynomial> in = (Point<Polynomial>) element;
List<Element> inre = in.getX().getCoefficients();
List<Element> inmi = in.getY().getCoefficients();
qPower(1, e2, e0re, e0im, e0re0, e0im0, inre, inmi);
e3.set(e0);
e0re.set(in.getX());
e0im.set(in.getY()).negate();
e3.mul(e0);
qPower(-1, e2, e0re, e0im, e0re0, e0im0, inre, inmi);
e0.mul(in);
e0.invert();
in.set(e3).mul(e0);
e0.set(in);
return lucasEven(e0, pairing.phikOnr);
} else {
return element.duplicate().pow(pairing.tateExp);
}
}
final void qPower(int sign, PolyModElement e2,
Element e0re, Element e0im, Element e0re0, Element e0im0,
List<Element> inre, List<Element> inim) {
e2.set(pairing.xPowq).polymodConstMul(inre.get(1));
e0re.set(e2);
e2.set(pairing.xPowq2).polymodConstMul(inre.get(2));
e0re.add(e2);
e0re0.add(inre.get(0));
if (sign > 0) {
e2.set(pairing.xPowq).polymodConstMul(inim.get(1));
e0im.set(e2);
e2.set(pairing.xPowq2).polymodConstMul(inim.get(2));
e0im.add(e2);
e0im0.add(inim.get(0));
} else {
e2.set(pairing.xPowq).polymodConstMul(inim.get(1));
e0im.set(e2).negate();
e2.set(pairing.xPowq2).polymodConstMul(inim.get(2));
e0im.sub(e2);
e0im0.sub(inim.get(0));
}
}
protected Element pairing(Point P, Polynomial Qx, Polynomial Qy) {
Element Px = P.getX();
Element Py = P.getY();
Point Z = (Point) P.duplicate();
Element Zx = Z.getX();
Element Zy = Z.getY();
Element a = Px.getField().newElement();
Element b = a.duplicate();
Element c = a.duplicate();
Element cca = ((CurveField) P.getField()).getA();
Element temp = a.duplicate();
Point<Polynomial> f0 = pairing.Fqk.newElement();
Element f = pairing.Fqk.newOneElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
tangentStep(f0, a, b, c, Zx, Zy, cca, temp, Qx, Qy, f);
Z.twice();
if (pairing.r.testBit(m)) {
lineStep(f0, a, b, c, Zx, Zy, Px, Py, temp, Qx, Qy, f);
Z.add(P);
}
f.square();
}
tangentStep(f0, a, b, c, Zx, Zy, cca, temp, Qx, Qy, f);
return f;
}
protected Element pairingInternal(Element[] Ps, Element[] Qs) {
Field refField = Ps[0].getField();
Element[] Zs = new Element[Ps.length];
for (int i = 0; i < Zs.length; i++) {
Zs[i] = Ps[i].duplicate();
}
Element a = ((Point) Ps[0]).getX().getField().newElement();
Element b = a.duplicate();
Element c = a.duplicate();
Element cca = ((CurveField) Ps[0].getField()).getA();
Element temp = a.duplicate();
Point<Polynomial> f0 = pairing.Fqk.newElement();
Element f = pairing.Fqk.newOneElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
tangentStep(f0, a, b, c, Zs, cca, temp, Qs, f);
refField.twice(Zs);
if (pairing.r.testBit(m)) {
lineStep(f0, a, b, c, Zs, Ps, temp, Qs, f);
refField.add(Zs, Ps);
}
f.square();
}
tangentStep(f0, a, b, c, Zs, cca, temp, Qs, f);
return f;
}
protected void millerStep(Point<Polynomial> out, Element a, Element b, Element c, Polynomial Qx, Polynomial Qy) {
// a, b, c are in Fq
// point Q is (Qx, Qy * sqrt(nqr)) where nqr is used to construct
// the quadratic field extension Fqk of Fqd
Polynomial rePart = out.getX();
Polynomial imPart = out.getY();
for (int i = 0, d = rePart.getDegree(); i < d; i++) {
rePart.getCoefficient(i).set(Qx.getCoefficient(i)).mul(a);
imPart.getCoefficient(i).set(Qy.getCoefficient(i)).mul(b);
}
rePart.getCoefficient(0).add(c);
}
public int getPairingPreProcessingTableLength() {
getPairingPreProcessingLengthInBytes();
return pairingPreProcessingTableLength;
}
public class TypeDMillerNoDenomAffinePairingPreProcessing extends AbstractMillerPairingPreProcessing {
public TypeDMillerNoDenomAffinePairingPreProcessing(byte[] source, int offset) {
super(pairing, source, offset);
}
public TypeDMillerNoDenomAffinePairingPreProcessing(Point in1) {
super(in1, getPairingPreProcessingTableLength());
Element Px = in1.getX();
Element Py = in1.getY();
Point Z = (Point) in1.duplicate();
Element Zx = Z.getX();
Element Zy = Z.getY();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element curveA = ((CurveField) in1.getField()).getA();
Element temp = pairing.Fq.newElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
computeTangent(processingInfo, a, b, c, Zx, Zy, curveA, temp);
Z.twice();
if (pairing.r.testBit(m)) {
computeLine(processingInfo, a, b, c, Zx, Zy, Px, Py, temp);
Z.add(in1);
}
}
computeTangent(processingInfo, a, b, c, Zx, Zy, curveA, temp);
}
public Element pairing(Element in2) {
Point pointIn2 = (Point) in2;
// map from twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic non-residue used to construct the twist
Polynomial Qx = (Polynomial) pointIn2.getX().duplicate().mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Polynomial Qy = (Polynomial) pointIn2.getY().duplicate().mul(pairing.nqrInverseSquare);
Point<Polynomial> f0 = pairing.Fqk.newElement();
Element out = pairing.Fqk.newOneElement();
int row = 0;
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
millerStep(f0, processingInfo.table[row][0], processingInfo.table[row][1], processingInfo.table[row][2], Qx, Qy);
out.mul(f0);
row++;
if (pairing.r.testBit(m)) {
millerStep(f0, processingInfo.table[row][0], processingInfo.table[row][1], processingInfo.table[row][2], Qx, Qy);
out.mul(f0);
row++;
}
out.square();
}
millerStep(f0, processingInfo.table[row][0], processingInfo.table[row][1], processingInfo.table[row][2], Qx, Qy);
out.mul(f0);
return new GTFiniteElement(
TypeDTateAffineNoDenomMillerPairingMap.this,
(GTFiniteField) pairing.getGT(),
tatePow(out)
);
}
}
}
| 11,963 | 34.713433 | 133 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/e/TypeECurveGenerator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.e;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeECurveGenerator implements PairingParametersGenerator {
protected SecureRandom random;
protected int rBits, qBits;
public TypeECurveGenerator(SecureRandom random, int rBits, int qBits) {
this.random = random;
this.rBits = rBits;
this.qBits = qBits;
}
public TypeECurveGenerator(int rBits, int qBits) {
this(new SecureRandom(), rBits, qBits);
}
public PairingParameters generate() {
// 3 takes 2 bits to represent
BigInteger q;
BigInteger r;
BigInteger h = null;
BigInteger n = null;
// won't find any curves is hBits is too low
int hBits = (qBits - 2) / 2 - rBits;
if (hBits < 3)
hBits = 3;
int exp2;
int exp1;
int sign0, sign1;
boolean found = false;
do {
r = BigInteger.ZERO;
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
exp2 = rBits - 1;
sign1 = 1;
} else {
exp2 = rBits;
sign1 = -1;
}
r = r.setBit(exp2);
exp1 = (random.nextInt(Integer.MAX_VALUE) % (exp2 - 1)) + 1;
//use q as a temp variable
q = BigInteger.ZERO.setBit(exp1);
if (sign1 > 0) {
r = r.add(q);
} else {
r = r.subtract(q);
}
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
sign0 = 1;
r = r.add(BigInteger.ONE);
} else {
sign0 = -1;
r = r.subtract(BigInteger.ONE);
}
if (!r.isProbablePrime(10))
continue;
for (int i = 0; i < 10; i++) {
//use q as a temp variable
q = BigInteger.ZERO.setBit(hBits + 1);
h = BigIntegerUtils.getRandom(q, random);
h = h.multiply(h).multiply(BigIntegerUtils.THREE);
//finally q takes the value it should
n = r.multiply(r).multiply(h);
q = n.add(BigInteger.ONE);
if (q.isProbablePrime(10)) {
found = true;
break;
}
}
} while (!found);
Field Fq = new ZrField(random, q);
CurveField curveField = new CurveField(random, Fq.newZeroElement(), Fq.newOneElement(), n);
// We may need to twist it.
// Pick a random point P and twist the curve if P has the wrong order.
if (!curveField.newRandomElement().mul(n).isZero())
curveField.twist();
PropertiesParameters params = new PropertiesParameters();
params.put("type", "e");
params.put("q", q.toString());
params.put("r", r.toString());
params.put("h", h.toString());
params.put("exp1", String.valueOf(exp1));
params.put("exp2", String.valueOf(exp2));
params.put("sign0", String.valueOf(sign0));
params.put("sign1", String.valueOf(sign1));
params.put("a", curveField.getA().toBigInteger().toString());
params.put("b", curveField.getB().toBigInteger().toString());
return params;
}
public static void main(String[] args) {
if (args.length < 2)
throw new IllegalArgumentException("Too few arguments. Usage <rbits> <qbits>");
if (args.length > 2)
throw new IllegalArgumentException("Too many arguments. Usage <rbits> <qbits>");
Integer rBits = Integer.parseInt(args[0]);
Integer qBits = Integer.parseInt(args[1]);
PairingParametersGenerator generator = new TypeECurveGenerator(rBits, qBits);
PairingParameters curveParams = generator.generate();
System.out.println(curveParams.toString(" "));
}
} | 4,423 | 30.827338 | 99 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/e/TypeEPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.e;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeEPairing extends AbstractPairing {
protected int exp2;
protected int exp1;
protected int sign1;
protected int sign0;
protected BigInteger r;
protected BigInteger q;
protected BigInteger h;
protected BigInteger a;
protected BigInteger b;
protected BigInteger phikonr;
protected Point R;
protected Field Fq;
public TypeEPairing(PairingParameters properties) {
this(new SecureRandom(), properties);
}
public TypeEPairing(SecureRandom random, PairingParameters properties) {
super(random);
initParams(properties);
initMap();
initFields();
}
protected void initParams(PairingParameters curveParams) {
// validate the type
String type = curveParams.getString("type");
if (type == null || !"e".equalsIgnoreCase(type))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'e'.");
// load params
exp2 = curveParams.getInt("exp2");
exp1 = curveParams.getInt("exp1");
sign1 = curveParams.getInt("sign1");
sign0 = curveParams.getInt("sign0");
r = curveParams.getBigInteger("r");
q = curveParams.getBigInteger("q");
h = curveParams.getBigInteger("h");
a = curveParams.getBigInteger("a");
b = curveParams.getBigInteger("b");
}
protected void initFields() {
// Init Zr
Zr = initFp(r);
// Init Fq
Fq = initFp(q);
// Init Eq
CurveField<Field> Eq = initEq();
// k=1, hence phikOnr = (q-1)/r
phikonr = Fq.getOrder().subtract(BigInteger.ONE).divide(r);
// Init G1, G2, GT
G1 = Eq;
G2 = G1;
GT = initGT();
R = (Point) Eq.getGenNoCofac().duplicate();
}
protected Field initFp(BigInteger order) {
return new ZrField(random, order);
}
protected CurveField<Field> initEq() {
return new CurveField<Field>(random,
Fq.newElement().set(a), Fq.newElement().set(b),
r, h);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fq);
}
protected void initMap() {
pairingMap = new TypeETateProjectiveMillerPairingMap(this);
}
} | 2,878 | 25.657407 | 102 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/e/TypeETateProjectiveMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.e;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractPairingMap;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeETateProjectiveMillerPairingMap extends AbstractPairingMap {
protected TypeEPairing pairing;
public TypeETateProjectiveMillerPairingMap(TypeEPairing pairing) {
super(pairing);
this.pairing = pairing;
}
public Element pairing(Point in1, Point in2) {
Element out = pairing.Fq.newElement();
Point QR = (Point) in2.duplicate().add(pairing.R);
e_miller_proj(out, in1, QR, pairing.R);
out.pow(pairing.phikonr);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), out);
}
public void finalPow(Element element) {
element.pow(pairing.phikonr);
}
void e_miller_proj(Element res, Point P, Point QR, Point R) {
//collate divisions
int n;
Element cca = ((CurveField) P.getField()).getA();
int i;
Element Zx, Zy;
Element Px = P.getX();
Element numx = QR.getX();
Element numy = QR.getY();
Element denomx = R.getX();
Element denomy = R.getY();
Element a = pairing.Fq.newElement();
Element b = pairing.Fq.newElement();
Element c = pairing.Fq.newElement();
Element e0 = pairing.Fq.newElement();
Element e1 = pairing.Fq.newElement();
Element z = pairing.Fq.newOneElement();
Element z2 = pairing.Fq.newOneElement();
Element v = pairing.Fq.newOneElement();
Element vd = pairing.Fq.newOneElement();
Element v1 = pairing.Fq.newOneElement();
Element vd1 = pairing.Fq.newOneElement();
Element e2 = a, e3 = b;
Point Z = (Point) P.duplicate();
Zx = Z.getX();
Zy = Z.getY();
Point Z1 = (Point) P.getField().newElement();
n = pairing.exp1;
for (i = 0; i < n; i++) {
v.square();
vd.square();
do_tangent(v, vd, a, b, c, e0, e1, z, z2, Zx, Zy, cca, numx, numy, denomx, denomy);
proj_double(Zx, Zy, e0, e1, e2, e3, z, z2, cca);
do_vertical(vd, v, Zx, e0, z2, numx, denomx);
}
pointToAffine(Zx, Zy, z, z2, e0);
if (pairing.sign1 < 0) {
v1.set(vd);
vd1.set(v);
do_vertical(vd1, v1, Zx, e0, z2, numx, denomx);
Z1.set(Z).negate();
} else {
v1.set(v);
vd1.set(vd);
Z1.set(Z);
}
n = pairing.exp2;
for (; i < n; i++) {
v.square();
vd.square();
do_tangent(v, vd, a, b, c, e0, e1, z, z2, Zx, Zy, cca, numx, numy, denomx, denomy);
proj_double(Zx, Zy, e0, e1, e2, e3, z, z2, cca);
do_vertical(vd, v, Zx, e0, z2, numx, denomx);
}
pointToAffine(Zx, Zy, z, z2, e0);
v.mul(v1);
vd.mul(vd1);
do_line(v, vd, Z, Z1, a, b, c, e0, e1, numx, numy, denomx, denomy);
Z.add(Z1);
do_vertical(vd, v, Zx, e0, z2, numx, denomx);
if (pairing.sign0 > 0) {
do_vertical(v, vd, Px, e0, z2, numx, denomx);
}
vd.invert();
res.set(v).mul(vd);
}
void proj_double(Element Zx, Element Zy, Element e0, Element e1, Element e2, Element e3, Element z, Element z2, Element cca) {
Element x = Zx;
Element y = Zy;
e0.set(x).square();
e1.set(e0).twice();
e0.add(e1);
e1.set(z2).square();
e1.mul(cca);
e0.add(e1);
z.mul(y);
z.twice();
z2.set(z).square();
e2.set(y).square();
e1.set(x).mul(e2);
e1.twice().twice();
e3.set(e1).twice();
x.set(e0).square();
x.sub(e3);
e2.square();
e2.twice().twice().twice();
e1.sub(x);
e0.mul(e1);
y.set(e0).sub(e2);
/*
//e0 = 3x^2 + (cc->a) z^4
element_square(e0, x);
//element_mul_si(e0, e0, 3);
element_double(e1, e0);
element_add(e0, e0, e1);
element_square(e1, z2);
element_mul(e1, e1, cca);
element_add(e0, e0, e1);
//z_out = 2 y z
element_mul(z, y, z);
//element_mul_si(z, z, 2);
element_double(z, z);
element_square(z2, z);
//e1 = 4 x y^2
element_square(e2, y);
element_mul(e1, x, e2);
//element_mul_si(e1, e1, 4);
element_double(e1, e1);
element_double(e1, e1);
//x_out = e0^2 - 2 e1
//element_mul_si(e3, e1, 2);
element_double(e3, e1);
element_square(x, e0);
element_sub(x, x, e3);
//e2 = 8y^4
element_square(e2, e2);
//element_mul_si(e2, e2, 8);
element_double(e2, e2);
element_double(e2, e2);
element_double(e2, e2);
//y_out = e0(e1 - x_out) - e2
element_sub(e1, e1, x);
element_mul(e0, e0, e1);
element_sub(y, e0, e2);
*/
}
void do_tangent(Element e, Element edenom, Element a, Element b, Element c, Element e0, Element e1, Element z, Element z2,
Element Zx, Element Zy, Element cca, Element numx, Element numy, Element denomx, Element denomy
) {
a.set(z2).square();
a.mul(cca);
b.set(Zx).square();
e0.set(b).twice();
b.add(e0);
a.add(b);
a.negate();
e0.set(Zy).twice();
b.set(e0).mul(z2);
b.mul(z);
c.set(Zx).mul(a);
a.mul(z2);
e0.mul(Zy);
c.add(e0).negate();
e0.set(a).mul(numx);
e1.set(b).mul(numy);
e0.add(e1).add(c);
e.mul(e0);
e0.set(a).mul(denomx);
e1.set(b).mul(denomy);
e0.add(e1).add(c);
edenom.mul(e0);
/*
//a = -(3x^2 + cca z^4)
//b = 2 y z^3
//c = -(2 y^2 + x a)
//a = z^2 a
element_square(a, z2);
element_mul(a, a, cca);
element_square(b, Zx);
//element_mul_si(b, b, 3);
element_double(e0, b);
element_add(b, b, e0);
element_add(a, a, b);
element_neg(a, a);
//element_mul_si(e0, Zy, 2);
element_double(e0, Zy);
element_mul(b, e0, z2);
element_mul(b, b, z);
element_mul(c, Zx, a);
element_mul(a, a, z2);
element_mul(e0, e0, Zy);
element_add(c, c, e0);
element_neg(c, c);
element_mul(e0, a, numx);
element_mul(e1, b, numy);
element_add(e0, e0, e1);
element_add(e0, e0, c);
element_mul(e, e, e0);
element_mul(e0, a, denomx);
element_mul(e1, b, denomy);
element_add(e0, e0, e1);
element_add(e0, e0, c);
element_mul(edenom, edenom, e0);
*/
}
void do_vertical(Element e, Element edenom, Element Ax, Element e0, Element z2, Element numx, Element denomx) {
e0.set(numx).mul(z2);
e0.sub(Ax);
e.mul(e0);
e0.set(denomx).mul(z2);
e0.sub(Ax);
edenom.mul(e0);
/*
element_mul(e0, numx, z2);
element_sub(e0, e0, Ax);
element_mul(e, e, e0);
element_mul(e0, denomx, z2);
element_sub(e0, e0, Ax);
element_mul(edenom, edenom, e0);
*/
}
void do_line(Element e, Element edenom, Point A, Point B, Element a, Element b, Element c, Element e0, Element e1,
Element numx, Element numy, Element denomx, Element denomy) {
Element Ax = A.getX();
Element Ay = A.getY();
Element Bx = B.getX();
Element By = B.getY();
b.set(Bx).sub(Ax);
a.set(Ay).sub(By);
c.set(Ax).mul(By);
e0.set(Ay).mul(Bx);
c.sub(e0);
e0.set(a).mul(numx);
e1.set(b).mul(numy);
e0.add(e1);
e0.add(c);
e.mul(e0);
e0.set(a).mul(denomx);
e1.set(b).mul(denomy);
e0.add(e1).add(c);
edenom.mul(e0);
/*
Element Ax = curve_x_coord(A);
Element Ay = curve_y_coord(A);
Element Bx = curve_x_coord(B);
Element By = curve_y_coord(B);
element_sub(b, Bx, Ax);
element_sub(a, Ay, By);
element_mul(c, Ax, By);
element_mul(e0, Ay, Bx);
element_sub(c, c, e0);
element_mul(e0, a, numx);
element_mul(e1, b, numy);
element_add(e0, e0, e1);
element_add(e0, e0, c);
element_mul(e, e, e0);
element_mul(e0, a, denomx);
element_mul(e1, b, denomy);
element_add(e0, e0, e1);
element_add(e0, e0, c);
element_mul(edenom, edenom, e0);
*/
}
}
| 9,031 | 25.17971 | 130 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/f/TypeFCurveGenerator.java | package it.unisa.dia.gas.plaf.jpbc.pairing.f;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.QuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* The curve is defined as E : y^2 = x^2 + b
* for some b \in F_q.
*/
public class TypeFCurveGenerator implements PairingParametersGenerator {
protected SecureRandom random;
protected int rBits; // The number of bits in r, the order of the subgroup G1
public TypeFCurveGenerator(SecureRandom random, int rBits) {
this.random = random;
this.rBits = rBits;
}
public TypeFCurveGenerator(int rBits) {
this(new SecureRandom(), rBits);
}
public PairingParameters generate() {
//36 is a 6-bit number
int xbit = (rBits - 6) / 4;
// Compute q and r primes
//TODO: use binary search to find smallest appropriate x
BigInteger q, r, b;
BigInteger x = BigInteger.ZERO.setBit(xbit);
BigInteger t;
for (; ;) {
// t = 6x^2 + 1
t = x.multiply(x).multiply(BigInteger.valueOf(6)).add(BigInteger.ONE);
// q = 36x^4 + 36x^3 + 24x^2 - 6x + 1
q = tryMinusX(x);
// r = 36x^4 + 36x^3 + 18x^2 - 6x + 1
r = q.subtract(t).add(BigInteger.ONE);
if (q.isProbablePrime(10) && r.isProbablePrime(10)) break;
// q = 36x^4 + 36x^3 + 24x^2 + 6x + 1
q = tryPlusX(x);
// r = 36x^4 + 36x^3 + 18x^2 + 6x + 1
r = q.subtract(t).add(BigInteger.ONE);
if (q.isProbablePrime(10) && r.isProbablePrime(10)) break;
x = x.add(BigInteger.ONE);
}
// Compute b
Field Fq = new ZrField(random, q);
Element e1 = Fq.newElement();
for (; ;) {
e1.setToRandom();
Field curveField = new CurveField(random, e1, r, null);
Element point = curveField.newRandomElement().mul(r);
if (point.isZero())
break;
}
b = e1.toBigInteger();
Field Fq2 = new QuadraticField(random, Fq);
BigInteger beta = Fq.getNqr().toBigInteger();
PolyField Fq2x = new PolyField(random, Fq2);
PolyElement<Point> f = Fq2x.newElement();
// Find an irreducible polynomial of the form f = x^6 + alpha.
// Call poly_set_coeff1() first so we can use element_item() for the other
// coefficients.
f.ensureSize(7);
f.getCoefficient(6).setToOne();
for (; ;) {
f.getCoefficient(0).setToRandom();
if (f.isIrriducible())
break;
}
//extend F_q^2 using f = x^6 + alpha
//see if sextic twist contains a subgroup of order r
//if not, it's the wrong twist: replace alpha with alpha^5
e1 = Fq2.newElement().set(b).mul(f.getCoefficient(0)).negate();
Field curveField = new CurveField(random, e1, r, null);
Element point = curveField.newRandomElement();
//I'm not sure what the #E'(F_q^2) is, but
//it definitely divides n_12 = #E(F_q^12). It contains a
//subgroup of order r if and only if
//(n_12 / r^2)P != O for some (in fact most) P in E'(F_q^6)
BigInteger z0 = q.pow(12).add(BigInteger.ONE);
BigInteger z1 = BigIntegerUtils.traceN(q, t, 12);
z1 = z0.subtract(z1);
z0 = r.multiply(r);
z1 = z1.divide(z0);
point.mul(z1);
if (point.isZero()) {
z0 = BigInteger.valueOf(5);
f.getCoefficient(0).pow(z0);
}
// Store parameters
PropertiesParameters params = new PropertiesParameters();
params.put("type", "f");
params.put("q", q.toString());
params.put("r", r.toString());
params.put("b", b.toString());
params.put("beta", beta.toString());
params.put("alpha0", f.getCoefficient(0).getX().toBigInteger().toString());
params.put("alpha1", f.getCoefficient(0).getY().toBigInteger().toString());
return params;
}
protected BigInteger tryMinusX(BigInteger x) {
// 36x^4 + 36x^3 + 24x^2 - 6x + 1 = ((36(x - 1)x + 24)x - 6)x + 1
return x.subtract(BigInteger.ONE)
.multiply(x)
.multiply(BigInteger.valueOf(36))
.add(BigInteger.valueOf(24))
.multiply(x)
.subtract(BigInteger.valueOf(6))
.multiply(x)
.add(BigInteger.ONE);
}
protected BigInteger tryPlusX(BigInteger x) {
// 36x^4 + 36x^3 + 24x^2 + 6x + 1 = ((36(x - 1)x + 24)x + 6)x + 1
return x.add(BigInteger.ONE)
.multiply(x)
.multiply(BigInteger.valueOf(36))
.add(BigInteger.valueOf(24))
.multiply(x)
.add(BigInteger.valueOf(6))
.multiply(x)
.add(BigInteger.ONE);
}
public static void main(String[] args) {
if (args.length < 1)
throw new IllegalArgumentException("Too few arguments. Usage <rbits>");
if (args.length > 1)
throw new IllegalArgumentException("Too many arguments. Usage <rbits>");
Integer rBits = Integer.parseInt(args[0]);
PairingParametersGenerator generator = new TypeFCurveGenerator(rBits);
PairingParameters curveParams = generator.generate();
System.out.println(curveParams.toString(" "));
}
} | 5,924 | 32.286517 | 84 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/f/TypeFPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.f;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.QuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeFPairing extends AbstractPairing {
protected PairingParameters curveParams;
protected BigInteger q;
protected BigInteger r;
protected BigInteger b;
protected BigInteger beta;
protected BigInteger alpha0;
protected BigInteger alpha1;
protected Element xPowq2, xPowq6, xPowq8;
protected Element negAlpha, negAlphaInv;
protected BigInteger tateExp;
protected Field Fq, Fq2x;
protected Field Fq2;
protected PolyModField Fq12;
protected CurveField Eq, etwist;
public TypeFPairing(PairingParameters curveParams) {
this(new SecureRandom(), curveParams);
}
public TypeFPairing(SecureRandom random, PairingParameters curveParams) {
super(random);
this.curveParams = curveParams;
initParams();
initMap();
initFields();
}
public boolean isSymmetric() {
return false;
}
protected void initParams() {
// validate the type
String type = curveParams.getString("type");
if (type == null || !type.equalsIgnoreCase("f"))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'f'.");
// load params
q = curveParams.getBigInteger("q");
r = curveParams.getBigInteger("r");
b = curveParams.getBigInteger("b");
beta = curveParams.getBigInteger("beta");
alpha0 = curveParams.getBigInteger("alpha0");
alpha1 = curveParams.getBigInteger("alpha1");
}
protected void initFields() {
// Init Zr
Zr = initFp(r, null);
// Init Fq
Fq = initFp(q, beta);
// Init Fq2
Fq2 = initQuadratic();
// Init Fq2x
Fq2x = initPoly();
Point tmp = (Point) Fq2.newElement();
tmp.getX().set(alpha0);
tmp.getY().set(alpha1);
negAlpha = tmp;
PolyElement irreduciblePoly = (PolyElement) Fq2x.newElement();
List<Element> irreduciblePolyCoeff = irreduciblePoly.getCoefficients();
irreduciblePolyCoeff.add(negAlpha.duplicate());
for (int i = 1; i < 6; i++)
irreduciblePolyCoeff.add(Fq2.newElement());
irreduciblePolyCoeff.add(Fq2.newOneElement());
// init Fq12
Fq12 = initPolyMod(irreduciblePoly);
negAlphaInv = negAlpha.negate().duplicate().invert();
// Initialize the curve Y^2 = X^3 + b.
Eq = initEq();
// Initialize the curve Y^2 = X^3 - alpha0 b - alpha1 sqrt(beta) b.
etwist = initEqMap();
// ndonr temporarily holds the trace.
BigInteger ndonr = q.subtract(r).add(BigInteger.ONE);
// TODO: We can use a smaller quotientCmp, but I have to figure out
// BN curves again.
ndonr = BigIntegerUtils.pbc_mpz_curve_order_extn(q, ndonr, 12);
ndonr = ndonr.divide(r);
ndonr = ndonr.divide(r);
etwist.setQuotientCmp(ndonr);
/*
For k = 12, the final exponent becomes
(q^12-1)/r = (p^6 - 1 )(p^2+1) ( (p^4-p^2+1)/r )
Lets compute the final factor (p^4-p^2+1)/r
*/
tateExp = q.multiply(q).subtract(BigInteger.ONE).multiply(q).multiply(q).add(BigInteger.ONE).divide(r);
PolyModElement polyModElement = Fq12.newElement();
polyModElement.getCoefficient(1).setToOne();
polyModElement.pow(q);
polyModElement.pow(q);
xPowq2 = polyModElement.getCoefficient(1).duplicate();
polyModElement.pow(q);
polyModElement.pow(q);
polyModElement.pow(q);
polyModElement.pow(q);
xPowq6 = polyModElement.getCoefficient(1).duplicate();
polyModElement.pow(q);
polyModElement.pow(q);
xPowq8 = polyModElement.getCoefficient(1).duplicate();
// Init G1, G2, GT
G1 = Eq;
G2 = etwist;
GT = initGT();
}
protected Field initFp(BigInteger order, BigInteger nqr) {
return new ZrField(random, order, nqr);
}
protected CurveField initEq() {
return new CurveField(random, Fq.newElement(), Fq.newElement().set(b), r);
}
protected CurveField initEqMap() {
Point tmp = (Point) Fq2.newElement();
tmp.getX().set(Fq.newElement().set(alpha0).negate().mul(b));
tmp.getY().set(Fq.newElement().set(alpha1).negate().mul(b));
return new CurveField(random, Fq2.newElement(), tmp, r);
}
protected PolyField initPoly() {
return new PolyField(random, Fq2);
}
protected PolyModField initPolyMod(PolyElement irred) {
return new PolyModField(random, irred);
}
protected QuadraticField initQuadratic() {
return new QuadraticField(random, Fq);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fq12);
}
protected void initMap() {
pairingMap = new TypeFTateNoDenomMillerPairingMap(this);
}
}
| 5,873 | 30.244681 | 111 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/f/TypeFTateNoDenomMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.f;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.jpbc.Polynomial;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
public class TypeFTateNoDenomMillerPairingMap extends AbstractMillerPairingMap {
protected TypeFPairing pairingData;
public TypeFTateNoDenomMillerPairingMap(TypeFPairing pairing) {
super(pairing);
this.pairingData = pairing;
}
public Element pairing(Point in1, Point in2) {
//map from twist: (x, y) --> (v^-2 x, v^-3 y)
//where v is the sixth root used to construct the twist
//i.e. v^6 = -alpha
//thus v^-2 = -alpha^-1 v^4
//and v^-3 = -alpha^-1 v^3
Point x = (Point) in2.getX().duplicate().mul(pairingData.negAlphaInv);
Point y = (Point) in2.getY().duplicate().mul(pairingData.negAlphaInv);
return new GTFiniteElement(
this,
(GTFiniteField) pairingData.getGT(),
tateExp((Polynomial) pairing(in1, x, y))
);
}
public void finalPow(Element element) {
element.set(tateExp((Polynomial) element));
}
public Element tateExp(Polynomial element) {
Polynomial x = pairingData.Fq12.newElement();
Polynomial y = pairingData.Fq12.newElement();
qPower(element, y, pairingData.xPowq8);
qPower(element, x, pairingData.xPowq6);
y.mul(x);
qPower(element, x, pairingData.xPowq2);
return y.mul(x.mul(element).invert()).pow(pairingData.tateExp);
}
private void qPower(Polynomial element, Polynomial e1, Element e) {
e1.getCoefficient(0).set(element.getCoefficient(0));
e1.getCoefficient(1).set(element.getCoefficient(1).duplicate().mul(e));
Element epow = e.duplicate().square();
e1.getCoefficient(2).set(element.getCoefficient(2).duplicate().mul(epow));
e1.getCoefficient(3).set(element.getCoefficient(3).duplicate().mul(epow.mul(e)));
e1.getCoefficient(4).set(element.getCoefficient(4).duplicate().mul(epow.mul(e)));
e1.getCoefficient(5).set(element.getCoefficient(5).duplicate().mul(epow.mul(e)));
}
protected Element pairing(Point P, Point Qx, Point Qy) {
Element Px = P.getX();
Element Py = P.getY();
Point Z = (Point) P.duplicate();
Element Zx = Z.getX();
Element Zy = Z.getY();
Element a = Px.getField().newElement();
Element b = a.duplicate();
Element c = a.duplicate();
Element t0 = a.duplicate();
Element cca = a.duplicate();
Polynomial e0 = pairingData.Fq12.newElement();
Polynomial v = (Polynomial) pairingData.Fq12.newOneElement();
for (int m = pairingData.r.bitLength() - 2; m > 0; m--) {
computeTangent(a, b, c, Zx, Zy, cca, t0);
millerStep(e0, v, a, b, c, Qx, Qy);
Z.twice();
if (pairingData.r.testBit(m)) {
computeLine(a, b, c, Zx, Zy, Px, Py, t0);
millerStep(e0, v, a, b, c, Qx, Qy);
Z.add(P);
}
v.square();
}
computeTangent(a, b, c, Zx, Zy, cca, t0);
millerStep(e0, v, a, b, c, Qx, Qy);
return v;
}
protected void millerStep(Point out_Renamed, Element a, Element b, Element c, Element Qx, Element Qy) {
}
protected void millerStep(Polynomial e0, Polynomial v, Element a, Element b, Element c, Element Qx, Element Qy) {
// a, b, c lie in Fq
// Qx, Qy lie in Fq^2
// Qx is coefficient of x^4
// Qy is coefficient of x^3
//
// computes v *= (a Qx x^4 + b Qy x^3 + c)
//
// recall x^6 = -alpha thus
// x^4 (u0 + u1 x^1 + ... + u5 x^5) =
// u0 x^4 + u1 x^5
// - alpha u2 - alpha u3 x - alpha u4 x^2 - alpha u5 x^3
// and
// x^4 (u0 + u1 x^1 + ... + u5 x^5) =
// u0 x^3 + u1 x^4 + u2 x^5
// - alpha u3 - alpha u4 x - alpha u5 x^2
millerStepTerm(0, 2, 3, 2, e0, v, a, b, c, Qx, Qy);
millerStepTerm(1, 3, 4, 2, e0, v, a, b, c, Qx, Qy);
millerStepTerm(2, 4, 5, 2, e0, v, a, b, c, Qx, Qy);
millerStepTerm(3, 5, 0, 1, e0, v, a, b, c, Qx, Qy);
millerStepTerm(4, 0, 1, 0, e0, v, a, b, c, Qx, Qy);
millerStepTerm(5, 1, 2, 0, e0, v, a, b, c, Qx, Qy);
v.set(e0);
}
protected void millerStepTerm(int i, int j, int k, int flag,
Polynomial e0, Polynomial v,
Element a, Element b, Element c,
Element Qx, Element Qy) {
Point e2 = (Point) e0.getCoefficient(i);
Point e1 = (Point) v.getCoefficient(j).duplicate().mul(Qx);
if (flag == 1)
e1.mul(pairingData.negAlpha);
e1.getX().mul(a);
e1.getY().mul(a);
e2.set(v.getCoefficient(k)).mul(Qy);
e2.getX().mul(b);
e2.getY().mul(b);
e2.add(e1);
if (flag == 2)
e2.mul(pairingData.negAlpha);
e1.set(v.getCoefficient(i));
e1.getX().mul(c);
e1.getY().mul(c);
e2.add(e1);
}
} | 5,373 | 34.355263 | 117 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/g/TypeGPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.g;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModElement;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModField;
import it.unisa.dia.gas.plaf.jpbc.field.quadratic.QuadraticField;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrField;
import it.unisa.dia.gas.plaf.jpbc.pairing.AbstractPairing;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.List;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeGPairing extends AbstractPairing {
protected PairingParameters curveParams;
protected BigInteger q, n, r, h;
protected BigInteger a, b;
protected BigInteger nqr;
protected PolyModElement xPowq, xPowq2, xPowq3, xPowq4;
protected Element nqrInverse, nqrInverseSquare;
protected BigInteger phikOnr;
protected Field Fq, Fqx;
protected Field<? extends Point<Polynomial>> Fqk;
protected PolyModField Fqd;
protected CurveField Eq, Etwist;
public TypeGPairing(PairingParameters curveParams) {
this(new SecureRandom(), curveParams);
}
public TypeGPairing(SecureRandom random, PairingParameters curveParams) {
super(random);
this.curveParams = curveParams;
initParams();
initMap();
initFields();
}
public boolean isSymmetric() {
return false;
}
protected void initParams() {
// validate the type
String type = curveParams.getString("type");
if (type == null || !type.equalsIgnoreCase("g"))
throw new IllegalArgumentException("Type not valid. Found '" + type + "'. Expected 'g'.");
// load params
q = curveParams.getBigInteger("q");
n = curveParams.getBigInteger("n");
h = curveParams.getBigInteger("h");
r = curveParams.getBigInteger("r");
a = curveParams.getBigInteger("a");
b = curveParams.getBigInteger("b");
// k = curveParams.getBigInteger("k");
// nk = curveParams.getBigInteger("nk");
// hk = curveParams.getBigInteger("hk");
nqr = curveParams.getBigInteger("nqr");
}
protected void initFields() {
// Init Zr
Zr = initFp(r);
// Init Fq
Fq = initFp(q);
// Init the curve
Eq = initEq();
// Init Fqx
Fqx = initPoly();
// Init polymod
// First set the coefficient of x^5 to 1 so we can call element_item()
// for the other coefficients.
PolyElement irreduciblePoly = (PolyElement) Fqx.newElement();
List<Element> irreduciblePolyCoeff = irreduciblePoly.getCoefficients();
for (int i = 0; i < 5; i++)
irreduciblePolyCoeff.add(Fq.newElement().set(curveParams.getBigIntegerAt("coeff", i)));
irreduciblePolyCoeff.add(Fq.newOneElement());
// init Fq12
Fqd = initPolyMod(irreduciblePoly);
Fqk = initQuadratic();
Etwist = initEqMap().twist();
nqrInverse = Fqd.getNqr().duplicate().invert();
nqrInverseSquare = nqrInverse.duplicate().square();
// ndonr temporarily holds the trace.
BigInteger ndonr = q.subtract(n).add(BigInteger.ONE);
// Negate because we want the order of the twist.
ndonr = ndonr.negate();
ndonr = BigIntegerUtils.pbc_mpz_curve_order_extn(q, ndonr, 5);
ndonr = ndonr.divide(r);
Etwist.setQuotientCmp(ndonr);
// Compute phi(k)/r = (q^4 - q^3 + ... + 1)/r.
phikOnr = BigInteger.ONE;
phikOnr = phikOnr.subtract(q);
BigInteger z0 = q.multiply(q);
phikOnr = phikOnr.add(z0);
z0 = z0.multiply(q);
phikOnr = phikOnr.subtract(z0);
z0 = z0.multiply(q);
phikOnr = phikOnr.add(z0);
phikOnr = phikOnr.divide(r);
// Compute xPowq's
xPowq = Fqd.newElement();
xPowq.getCoefficient(1).setToOne();
xPowq.pow(q);
xPowq2 = xPowq.duplicate().square();
xPowq4 = xPowq2.duplicate().square();
xPowq3 = xPowq2.duplicate().mul(xPowq);
// Init G1, G2, GT
G1 = Eq;
G2 = Etwist;
GT = initGT();
}
protected Field initFp(BigInteger order) {
return new ZrField(random, order);
}
protected CurveField initEq() {
return new CurveField(random, Fq.newElement().set(a), Fq.newElement().set(b), r, h);
}
protected CurveField initEqMap() {
return new CurveField(random, Fqd.newElement().map(Eq.getA()), Fqd.newElement().map(Eq.getB()), r);
}
protected PolyField initPoly() {
return new PolyField(random, Fq);
}
protected PolyModField initPolyMod(PolyElement irred) {
return new PolyModField(random, irred, nqr);
}
protected QuadraticField initQuadratic() {
return new QuadraticField(random, Fqd);
}
protected Field initGT() {
return new GTFiniteField(random, r, pairingMap, Fqk);
}
protected void initMap() {
pairingMap = new TypeGTateAffineNoDenomMillerPairingMap(this);
}
} | 5,395 | 29.834286 | 107 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/g/TypeGTateAffineNoDenomMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.g;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.jpbc.Polynomial;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveField;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteElement;
import it.unisa.dia.gas.plaf.jpbc.field.gt.GTFiniteField;
import it.unisa.dia.gas.plaf.jpbc.field.poly.PolyModElement;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.AbstractMillerPairingMap;
import java.util.List;
public class TypeGTateAffineNoDenomMillerPairingMap extends AbstractMillerPairingMap<Polynomial> {
protected TypeGPairing pairing;
public TypeGTateAffineNoDenomMillerPairingMap(TypeGPairing pairing) {
super(pairing);
this.pairing = pairing;
}
public Element pairing(Point in1, Point in2) {
// map from twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic non-residue used to construct the twist
Polynomial Qx = (Polynomial) in2.getX().duplicate().mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Polynomial Qy = (Polynomial) in2.getY().duplicate().mul(pairing.nqrInverseSquare);
return new GTFiniteElement(this, (GTFiniteField) pairing.getGT(), tatePow(pairing(in1, Qx, Qy)));
}
public void finalPow(Element element) {
element.set(tatePow(element));
}
public boolean isAlmostCoddh(Element a, Element b, Element c, Element d) {
// Twist: (x, y) --> (v^-1 x, v^-(3/2) y)
// where v is the quadratic nonresidue used to construct the twist.
Element cx = ((Point) c).getX().duplicate().mul(pairing.nqrInverse);
Element dx = ((Point) d).getX().duplicate().mul(pairing.nqrInverse);
// v^-3/2 = v^-2 * v^1/2
Element cy = ((Point) c).getY().duplicate().mul(pairing.nqrInverseSquare);
Element dy = ((Point) d).getY().duplicate().mul(pairing.nqrInverseSquare);
Element t0 = pairing((Point) a, (Polynomial) dx, (Polynomial) dy);
Element t1 = pairing((Point) b, (Polynomial) cx, (Polynomial) cy);
t0 = tatePow(t0);
t1 = tatePow(t1);
Element t2 = t0.duplicate().mul(t1);
if (t2.isOne())
return true; // We were given g, g^x, h, h^-x.
else {
// Cheaply check the other case.
t2.set(t0).mul(t1.invert());
if (t2.isOne())
return true; // We were given g, g^x, h, h^x.
}
return false;
}
public Element tatePow(Element element) {
Point<Polynomial> e0, e3;
PolyModElement e2;
e0 = pairing.Fqk.newElement();
e2 = pairing.Fqd.newElement();
e3 = pairing.Fqk.newElement();
Polynomial e0re = e0.getX();
Polynomial e0im = e0.getY();
Element e0re0 = e0re.getCoefficient(0);
Element e0im0 = e0im.getCoefficient(0);
Point<Polynomial> in = (Point<Polynomial>) element;
List<Element> inre = in.getX().getCoefficients();
List<Element> inmi = in.getY().getCoefficients();
qPower(1, e2, e0re, e0im, e0re0, e0im0, inre, inmi);
e3.set(e0);
e0re.set(in.getX());
e0im.set(in.getY()).negate();
e3.mul(e0);
qPower(-1, e2, e0re, e0im, e0re0, e0im0, inre, inmi);
e0.mul(in);
e0.invert();
in.set(e3).mul(e0);
e0.set(in);
return lucasEven(e0, pairing.phikOnr);
}
final void qPower(int sign, PolyModElement e2,
Element e0re, Element e0im, Element e0re0, Element e0im0,
List<Element> inre, List<Element> inim) {
e2.set(pairing.xPowq).polymodConstMul(inre.get(1));
e0re.set(e2);
e2.set(pairing.xPowq2).polymodConstMul(inre.get(2));
e0re.add(e2);
e2.set(pairing.xPowq3).polymodConstMul(inre.get(3));
e0re.add(e2);
e2.set(pairing.xPowq4).polymodConstMul(inre.get(4));
e0re.add(e2);
e0re0.add(inre.get(0));
if (sign > 0) {
e2.set(pairing.xPowq).polymodConstMul(inim.get(1));
e0im.set(e2);
e2.set(pairing.xPowq2).polymodConstMul(inim.get(2));
e0im.add(e2);
e2.set(pairing.xPowq3).polymodConstMul(inim.get(3));
e0im.add(e2);
e2.set(pairing.xPowq4).polymodConstMul(inim.get(4));
e0im.add(e2);
e0im0.add(inim.get(0));
} else {
e2.set(pairing.xPowq).polymodConstMul(inim.get(1));
e0im.set(e2).negate();
e2.set(pairing.xPowq2).polymodConstMul(inim.get(2));
e0im.sub(e2);
e2.set(pairing.xPowq3).polymodConstMul(inim.get(3));
e0im.sub(e2);
e2.set(pairing.xPowq4).polymodConstMul(inim.get(4));
e0im.sub(e2);
e0im0.sub(inim.get(0));
}
}
protected Element pairing(Point P, Polynomial Qx, Polynomial Qy) {
Element Px = P.getX();
Element Py = P.getY();
Point Z = (Point) P.duplicate();
Element Zx = Z.getX();
Element Zy = Z.getY();
Element a = Px.getField().newElement();
Element b = a.duplicate();
Element c = a.duplicate();
Element cca = ((CurveField) P.getField()).getA();
Element temp = a.duplicate();
Point<Polynomial> f0 = pairing.Fqk.newElement();
Element f = pairing.Fqk.newOneElement();
for (int m = pairing.r.bitLength() - 2; m > 0; m--) {
tangentStep(f0, a, b, c, Zx, Zy, cca, temp, Qx, Qy, f);
Z.twice();
if (pairing.r.testBit(m)) {
lineStep(f0, a, b, c, Zx, Zy, Px, Py, temp, Qx, Qy, f);
Z.add(P);
}
f.square();
}
tangentStep(f0, a, b, c, Zx, Zy, cca, temp, Qx, Qy, f);
return f;
}
protected void millerStep(Point<Polynomial> out, Element a, Element b, Element c, Polynomial Qx, Polynomial Qy) {
// a, b, c are in Fq
// point Q is (Qx, Qy * sqrt(nqr)) where nqr is used to construct
// the quadratic field extension Fqk of Fqd
Polynomial rePart = out.getX();
Polynomial imPart = out.getY();
int i;
//int d = rePart.getField().getN();
int d = rePart.getDegree();
for (i = 0; i < d; i++) {
rePart.getCoefficient(i).set(Qx.getCoefficient(i)).mul(a);
imPart.getCoefficient(i).set(Qy.getCoefficient(i)).mul(b);
}
rePart.getCoefficient(0).add(c);
}
} | 6,551 | 33.303665 | 117 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/immutable/ImmutableElementPowPreProcessing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.immutable;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;
import it.unisa.dia.gas.jpbc.Field;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ImmutableElementPowPreProcessing implements ElementPowPreProcessing {
private ElementPowPreProcessing elementPowPreProcessing;
private Field immutableField;
public ImmutableElementPowPreProcessing(ImmutableField immutableField, ElementPowPreProcessing elementPowPreProcessing){
this.immutableField = immutableField;
this.elementPowPreProcessing = elementPowPreProcessing;
}
public Field getField() {
return immutableField;
}
public Element pow(BigInteger n) {
return elementPowPreProcessing.pow(n).getImmutable();
}
public Element powZn(Element n) {
return elementPowPreProcessing.powZn(n).getImmutable();
}
public byte[] toBytes() {
return elementPowPreProcessing.toBytes();
}
}
| 1,079 | 26.692308 | 124 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/immutable/ImmutableField.java | package it.unisa.dia.gas.plaf.jpbc.pairing.immutable;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ImmutableField implements Field {
protected Field field;
public ImmutableField(Field field) {
this.field = field;
}
public Element newElement() {
return field.newElement().getImmutable();
}
public Element newElement(int value) {
return field.newElement(value).getImmutable();
}
public Element newElement(BigInteger value) {
return field.newElement(value).getImmutable();
}
public Element newElement(Element element) {
return field.newElement(element).getImmutable();
}
public Element newZeroElement() {
return field.newZeroElement().getImmutable();
}
public Element newOneElement() {
return field.newOneElement().getImmutable();
}
public Element newElementFromHash(byte[] source, int offset, int length) {
return field.newElementFromHash(source, offset, length).getImmutable();
}
public Element newElementFromBytes(byte[] source) {
return field.newElementFromBytes(source).getImmutable();
}
public Element newElementFromBytes(byte[] source, int offset) {
return field.newElementFromBytes(source, offset).getImmutable();
}
public Element newRandomElement() {
return field.newRandomElement().getImmutable();
}
public BigInteger getOrder() {
return field.getOrder();
}
public boolean isOrderOdd() {
return field.isOrderOdd();
}
public Element getNqr() {
return field.getNqr();
}
public int getLengthInBytes() {
return field.getLengthInBytes();
}
public int getLengthInBytes(Element element) {
return field.getLengthInBytes(element);
}
public int getCanonicalRepresentationLengthInBytes() {
return field.getCanonicalRepresentationLengthInBytes();
}
public Element[] twice(Element[] elements) {
Element[] temp = ElementUtils.duplicate(elements);
return ElementUtils.cloneImmutable(field.twice(temp));
}
public Element[] add(Element[] a, Element[] b) {
Element[] temp = ElementUtils.duplicate(a);
return ElementUtils.cloneImmutable(field.add(temp, b));
}
public ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source) {
return new ImmutableElementPowPreProcessing(this, field.getElementPowPreProcessingFromBytes(source));
}
public ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source, int offset) {
return new ImmutableElementPowPreProcessing(this, field.getElementPowPreProcessingFromBytes(source, offset));
}
@Override
public String toString() {
return "ImmutableField{" +
"field=" + field +
'}';
}
}
| 3,120 | 26.619469 | 117 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/immutable/ImmutablePairingPreProcessing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.immutable;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ImmutablePairingPreProcessing implements PairingPreProcessing {
private PairingPreProcessing pairingPreProcessing;
public ImmutablePairingPreProcessing(PairingPreProcessing pairingPreProcessing) {
this.pairingPreProcessing = pairingPreProcessing;
}
public Element pairing(Element in2) {
return pairingPreProcessing.pairing(in2).getImmutable();
}
public byte[] toBytes() {
return pairingPreProcessing.toBytes();
}
}
| 699 | 25.923077 | 85 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/immutable/ImmutableParing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.immutable;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import java.util.HashMap;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ImmutableParing implements Pairing {
private Pairing pairing;
private Map<Integer, Field> fieldMap;
public ImmutableParing(Pairing pairing) {
this.pairing = pairing;
this.fieldMap = new HashMap<Integer, Field>();
}
public boolean isSymmetric() {
return pairing.isSymmetric();
}
public int getDegree() {
return pairing.getDegree();
}
public Field getG1() {
return getFieldAt(1);
}
public Field getG2() {
return getFieldAt(2);
}
public Field getGT() {
return getFieldAt(3);
}
public Field getZr() {
return getFieldAt(0);
}
public Field getFieldAt(int index) {
Field field = fieldMap.get(index);
if (field == null) {
fieldMap.put(index, (field = new ImmutableField(pairing.getFieldAt(index))));
}
return field;
}
public int getFieldIndex(Field field) {
if (field instanceof ImmutableField)
return pairing.getFieldIndex(((ImmutableField)field).field);
return pairing.getFieldIndex(field);
}
public Element pairing(Element in1, Element in2) {
return pairing.pairing(in1, in2).getImmutable();
}
public boolean isProductPairingSupported() {
return pairing.isProductPairingSupported();
}
public Element pairing(Element[] in1, Element[] in2) {
return pairing.pairing(in1, in2).getImmutable();
}
public int getPairingPreProcessingLengthInBytes() {
return pairing.getPairingPreProcessingLengthInBytes();
}
public PairingPreProcessing getPairingPreProcessingFromElement(Element in1) {
return new ImmutablePairingPreProcessing(pairing.getPairingPreProcessingFromElement(in1));
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source) {
return new ImmutablePairingPreProcessing(pairing.getPairingPreProcessingFromBytes(source));
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source, int offset) {
return new ImmutablePairingPreProcessing(pairing.getPairingPreProcessingFromBytes(source, offset));
}
@Override
public String toString() {
return "ImmutableParing{" +
"pairing=" + pairing +
'}';
}
}
| 2,679 | 25.534653 | 107 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/map/AbstractMillerPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.map;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.util.io.PairingStreamReader;
import it.unisa.dia.gas.plaf.jpbc.util.io.PairingStreamWriter;
import java.io.IOException;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public abstract class AbstractMillerPairingMap<E extends Element> extends AbstractPairingMap {
protected AbstractMillerPairingMap(final Pairing pairing) {
super(pairing);
}
protected final void lineStep(final Point<E> f0,
final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element V1x, final Element V1y,
final Element e0,
final E Qx, final E Qy,
final Element f) {
// computeLine(a, b, c, Vx, Vy, V1x, V1y, e0);
// a = -(V1y - Vy) / (V1x - Vx);
// b = 1;
// c = -(Vy + a * Vx);
//
// but we will multiply by V1x - Vx to avoid division, so
//
// a = -(V1y - Vy)
// b = V1x - Vx
// c = -(Vy b + a Vx);
a.set(Vy).sub(V1y);
b.set(V1x).sub(Vx);
c.set(Vx).mul(V1y).sub(e0.set(Vy).mul(V1x));
millerStep(f0, a, b, c, Qx, Qy);
f.mul(f0);
}
protected final void lineStep(final Point<E> f0,
final Element a, final Element b, final Element c,
final Element[] Vs,
final Element[] V1s,
final Element e0,
final Element[] Qs,
final Element f) {
// computeLine(a, b, c, Vx, Vy, V1x, V1y, e0);
// a = -(V1y - Vy) / (V1x - Vx);
// b = 1;
// c = -(Vy + a * Vx);
//
// but we will multiply by V1x - Vx to avoid division, so
//
// a = -(V1y - Vy)
// b = V1x - Vx
// c = -(Vy b + a Vx);
for (int i = 0; i < Vs.length; i++) {
Point V = (Point) Vs[i];
Point V1 = (Point) V1s[i];
Point Q = (Point) Qs[i];
a.set(V.getY()).sub(V1.getY());
b.set(V1.getX()).sub(V.getX());
c.set(V.getX()).mul(V1.getY()).sub(e0.set(V.getY()).mul(V1.getX()));
millerStep(f0, a, b, c, (E) Q.getX(), (E) Q.getY());
f.mul(f0);
}
}
protected final void tangentStep(final Point<E> f0,
final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element curveA,
final Element e0,
final E Qx, final E Qy,
final Element f) {
//computeTangent(a, b, c, Vx, Vy, curveA, e0);
//a = -slope_tangent(V.x, V.y);
//b = 1;
//c = -(V.y + aV.x);
//but we multiply by -2*V.y to avoid division so:
//a = -(3 Vx^2 + cc->a)
//b = 2 * Vy
//c = -(2 Vy^2 + a Vx);
a.set(Vx).square().mul(3).add(curveA).negate();
b.set(Vy).twice();
c.set(a).mul(Vx).add(e0.set(b).mul(Vy)).negate();
millerStep(f0, a, b, c, Qx, Qy);
f.mul(f0);
}
protected final void tangentStep(final Point<E> f0,
final Element a, final Element b, final Element c,
final Element[] Vs,
final Element curveA,
final Element e0,
final Element[] Qs,
final Element f) {
//computeTangent(a, b, c, Vx, Vy, curveA, e0);
//a = -slope_tangent(V.x, V.y);
//b = 1;
//c = -(V.y + aV.x);
//but we multiply by -2*V.y to avoid division so:
//a = -(3 Vx^2 + cc->a)
//b = 2 * Vy
//c = -(2 Vy^2 + a Vx);
for (int i = 0; i < Vs.length; i++) {
Point V = (Point) Vs[i];
Point Q = (Point) Qs[i];
a.set(V.getX()).square().mul(3).add(curveA).negate();
b.set(V.getY()).twice();
c.set(a).mul(V.getX()).add(e0.set(b).mul(V.getY())).negate();
millerStep(f0, a, b, c, (E) Q.getX(), (E) Q.getY());
f.mul(f0);
}
}
protected final void tangentStepProjective(final Point<E> f0,
final Element a, final Element b,final Element c,
final Element Vx, final Element Vy, final Element z,
final Element z2,
final Element e0,
final E Qx, final E Qy,
final Element f) {
// Compute the tangent line T (aX + bY + c) at point V = (Vx, Vy, z)
a.set(z2).square();
b.set(Vx).square();
a.add(b.add(e0.set(b).twice())).negate();
// Now:
// a = -(3x^2 + cca z^4) with cca = 1
b.set(e0.set(Vy).twice()).mul(z2).mul(z);
// Now:
// b = 2 y z^3
c.set(Vx).mul(a);
a.mul(z2);
c.add(e0.mul(Vy)).negate();
// Now:
// a = -3x^2 z^2 - z^6
// c = 3x^3 + z^4 x - 2x^2 y
millerStep(f0, a, b, c, Qx, Qy);
f.mul(f0);
}
protected abstract void millerStep(Point<E> out,
Element a, Element b, Element c,
E Qx, E Qy);
protected final void computeTangent(final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element curveA,
final Element temp) {
//a = -slope_tangent(V.x, V.y);
//b = 1;
//c = -(V.y + aV.x);
//but we multiply by -2*V.y to avoid division so:
//a = -(3 Vx^2 + cc->a)
//b = 2 * Vy
//c = -(2 Vy^2 + a Vx);
a.set(Vx).square().mul(3).add(curveA).negate();
b.set(Vy).twice();
c.set(a).mul(Vx).add(temp.set(b).mul(Vy)).negate();
}
protected final void computeTangent(final MillerPreProcessingInfo info,
final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element curveA,
final Element temp) {
//a = -slope_tangent(Z.x, Z.y);
//b = 1;
//c = -(Z.y + a * Z.x);
//but we multiply by 2*Z.y to avoid division
//a = -Vx * (3 Vx + twicea_2) - a_4;
//Common curves: a2 = 0 (and cc->a is a_4), so
//a = -(3 Vx^2 + cc->a)
//b = 2 * Vy
//c = -(2 Vy^2 + a Vx);
a.set(Vx).square();
// a.add(a).add(a);
a.mul(3);
a.add(curveA);
a.negate();
b.set(Vy).twice();
temp.set(b).mul(Vy);
c.set(a).mul(Vx);
c.add(temp).negate();
info.addRow(a, b, c);
}
/**
* Compute the tangent line L (aX + bY + c) through the points V = (Vx, Vy) e V1 = (V1x, V1y).
*
* @param a the coefficient of X of tangent line T.
* @param b the coefficient of Y of tangent line T.
* @param c the constant term f tangent line T.
* @param Vx V's x.
* @param Vy V's y.
* @param V1x V1's x.
* @param V1y V1's y.
* @param temp temp element.
*/
protected final void computeLine(final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element V1x, final Element V1y,
final Element temp) {
// a = -(V1y - Vy) / (V1x - Vx);
// b = 1;
// c = -(Vy + a * Vx);
//
// but we will multiply by V1x - Vx to avoid division, so
//
// a = -(V1y - Vy)
// b = V1x - Vx
// c = -(Vy b + a Vx);
a.set(Vy).sub(V1y);
b.set(V1x).sub(Vx);
c.set(Vx).mul(V1y).sub(temp.set(Vy).mul(V1x));
}
protected final void computeLine(final MillerPreProcessingInfo info,
final Element a, final Element b, final Element c,
final Element Vx, final Element Vy,
final Element V1x, final Element V1y,
final Element temp) {
// a = -(V1y - Vy) / (V1x - Vx);
// b = 1;
// c = -(Vy + a * Vx);
//
// but we will multiply by V1x - Vx to avoid division, so
//
// a = -(V1y - Vy)
// b = V1x - Vx
// c = -(Vy b + a Vx);
a.set(Vy).sub(V1y);
b.set(V1x).sub(Vx);
c.set(Vx).mul(V1y).sub(temp.set(Vy).mul(V1x));
info.addRow(a, b, c);
}
protected final Element lucasEven(final Point in, final BigInteger cofactor) {
//assumes cofactor is even
//mangles in
//in cannot be out
if (in.isOne()) {
return in.duplicate();
}
Point out = (Point) in.getField().newElement();
Point temp = (Point) in.getField().newElement();
Element in0 = in.getX();
Element in1 = in.getY();
Element v0 = out.getX();
Element v1 = out.getY();
Element t0 = temp.getX();
Element t1 = temp.getY();
t0.set(2);
t1.set(in0).twice();
v0.set(t0);
v1.set(t1);
int j = cofactor.bitLength() - 1;
while (true) {
if (j == 0) {
v1.mul(v0).sub(t1);
v0.square().sub(t0);
break;
}
if (cofactor.testBit(j)) {
v0.mul(v1).sub(t1);
v1.square().sub(t0);
} else {
v1.mul(v0).sub(t1);
v0.square().sub(t0);
}
j--;
}
v0.twice();
in0.set(t1).mul(v1).sub(v0);
t1.square().sub(t0).sub(t0);
v0.set(v1).halve();
v1.set(in0).div(t1);
v1.mul(in1);
return out;
}
protected final void lucasOdd(final Point out, final Point in, final Point temp, final BigInteger cofactor) {
//assumes cofactor is odd
//overwrites in and temp, out must not be in
//luckily this touchy routine is only used internally
//TODO: rewrite to allow (out == in)? would simplify a_finalpow()
Element in0 = in.getX();
Element in1 = in.getY();
Element v0 = out.getX();
Element v1 = out.getY();
Element t0 = temp.getX();
Element t1 = temp.getY();
t0.set(2);
t1.set(in0).twice();
v0.set(t0);
v1.set(t1);
int j = cofactor.bitLength() - 1;
for (; ; ) {
if (j == 0) {
v1.mul(v0).sub(t1);
v0.square().sub(t0);
break;
}
if (cofactor.testBit(j)) {
v0.mul(v1).sub(t1);
v1.square().sub(t0);
} else {
v1.mul(v0).sub(t1);
v0.square().sub(t0);
}
j--;
}
v1.twice().sub(in0.set(v0).mul(t1));
t1.square().sub(t0).sub(t0);
v1.div(t1);
v0.halve();
v1.mul(in1);
}
public static class MillerPreProcessingInfo {
public int numRow = 0;
public final Element[][] table;
public MillerPreProcessingInfo(int size) {
this.table = new Element[size][3];
}
public MillerPreProcessingInfo(Pairing pairing, byte[] source, int offset) {
PairingStreamReader in = new PairingStreamReader(pairing, source, offset);
this.numRow = in.readInt();
this.table = new Element[numRow][3];
Field field = ((FieldOver) pairing.getG1()).getTargetField();
for (int i = 0; i < numRow; i++) {
table[i][0] = in.readFieldElement(field);
table[i][1] = in.readFieldElement(field);
table[i][2] = in.readFieldElement(field);
}
}
public void addRow(Element a, Element b, Element c) {
table[numRow][0] = a.duplicate();
table[numRow][1] = b.duplicate();
table[numRow][2] = c.duplicate();
numRow++;
}
public byte[] toBytes() {
try {
PairingStreamWriter out = new PairingStreamWriter(table[0][0].getField().getLengthInBytes() * numRow * 3 + 4);
out.writeInt(numRow);
for (int i = 0; i < numRow; i++) {
for (Element element : table[i])
out.write(element);
}
return out.toBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static class JacobPoint {
private Element x;
private Element y;
private Element z;
public JacobPoint(Element x, Element y, Element z) {
this.x = x;
this.y = y;
this.z = z;
}
public Element getX() {
return this.x;
}
public Element getY() {
return this.y;
}
public Element getZ() {
return this.z;
}
public boolean isInfinity() {
//return this.equals(JacobPoint.INFINITY);
return this.z.isZero();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
result = prime * result + ((z == null) ? 0 : z.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JacobPoint other = (JacobPoint) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
if (z == null) {
if (other.z != null)
return false;
} else if (!z.equals(other.z))
return false;
return true;
}
@Override
public String toString() {
return "[" + x + "," + y + "," + z + "]";
}
public void setX(Element newX) {
this.x = newX;
}
public void setY(Element newY) {
this.y = newY;
}
public void setZ(Element newZ) {
this.z = newZ;
}
}
}
| 15,794 | 29.970588 | 126 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/map/AbstractMillerPairingPreProcessing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.map;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public abstract class AbstractMillerPairingPreProcessing implements PairingPreProcessing {
protected AbstractMillerPairingMap.MillerPreProcessingInfo processingInfo;
protected AbstractMillerPairingPreProcessing() {
}
protected AbstractMillerPairingPreProcessing(Point in1, int processingInfoSize) {
this.processingInfo = new AbstractMillerPairingMap.MillerPreProcessingInfo(processingInfoSize);
}
protected AbstractMillerPairingPreProcessing(Pairing pairing, byte[] source, int offset) {
this.processingInfo = new AbstractMillerPairingMap.MillerPreProcessingInfo(pairing, source, offset);
}
public byte[] toBytes() {
if (processingInfo != null)
return processingInfo.toBytes();
else
return new byte[0];
}
}
| 1,034 | 30.363636 | 108 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/map/AbstractPairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.map;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
import it.unisa.dia.gas.plaf.jpbc.pairing.accumulator.PairingAccumulator;
import it.unisa.dia.gas.plaf.jpbc.pairing.accumulator.PairingAccumulatorFactory;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public abstract class AbstractPairingMap implements PairingMap {
protected final Pairing pairing;
protected AbstractPairingMap(Pairing pairing) {
this.pairing = pairing;
}
public boolean isProductPairingSupported() {
return false;
}
public Element pairing(Element[] in1, Element[] in2) {
PairingAccumulator combiner = PairingAccumulatorFactory.getInstance().getPairingMultiplier(pairing);
for(int i = 0; i < in1.length; i++)
combiner.addPairing(in1[i], in2[i]);
return combiner.awaitResult();
}
public int getPairingPreProcessingLengthInBytes() {
return pairing.getG1().getLengthInBytes();
}
public PairingPreProcessing pairing(final Point in1) {
return new DefaultPairingPreProcessing(pairing, in1);
}
public PairingPreProcessing pairing(byte[] source, int offset) {
return new DefaultPairingPreProcessing(pairing, pairing.getG1(), source, offset);
}
public boolean isAlmostCoddh(Element a, Element b, Element c, Element d) {
Element t0, t1;
t0 = pairing((Point) a, (Point) d);
t1 = pairing((Point) b, (Point) c);
if (t0.isEqual(t1)) {
return true;
} else {
t0.mul(t1);
return t0.isOne();
}
}
protected final void pointToAffine(Element Vx, Element Vy, Element z, Element z2, Element e0) {
// Vx = Vx * z^-2
Vx.mul(e0.set(z.invert()).square());
// Vy = Vy * z^-3
Vy.mul(e0.mul(z));
z.setToOne();
z2.setToOne();
}
}
| 2,028 | 27.577465 | 108 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/map/DefaultPairingPreProcessing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.map;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class DefaultPairingPreProcessing implements PairingPreProcessing {
protected Pairing pairing;
protected Element in1;
public DefaultPairingPreProcessing(Pairing pairing, Element in1) {
this.pairing = pairing;
this.in1 = in1;
}
public DefaultPairingPreProcessing(Pairing pairing, Field field, byte[] source, int offset) {
this.pairing = pairing;
this.in1 = field.newElementFromBytes(source, offset);
}
public Element pairing(Element in2) {
return pairing.pairing(in1, in2);
}
public byte[] toBytes() {
return in1.toBytes();
}
}
| 911 | 24.333333 | 97 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/map/PairingMap.java | package it.unisa.dia.gas.plaf.jpbc.pairing.map;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;
import it.unisa.dia.gas.jpbc.Point;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public interface PairingMap {
Element pairing(Point in1, Point in2);
boolean isProductPairingSupported();
Element pairing(Element[] in1, Element[] in2);
void finalPow(Element element);
boolean isAlmostCoddh(Element a, Element b, Element c, Element d);
int getPairingPreProcessingLengthInBytes();
PairingPreProcessing pairing(Point in1);
PairingPreProcessing pairing(byte[] source, int offset);
}
| 669 | 19.9375 | 70 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/parameters/MapParameters.java | package it.unisa.dia.gas.plaf.jpbc.pairing.parameters;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class MapParameters implements MutablePairingParameters {
protected Map<String, Object> values;
public MapParameters() {
this.values = new LinkedHashMap<String, Object>();
}
public MapParameters(Map<String, Object> values) {
this.values = values;
}
public String getType() {
return (String) values.get("type");
}
public boolean containsKey(String key) {
return values.containsKey(key);
}
public int getInt(String key) {
throw new IllegalStateException("Not Implemented yet!");
}
public int getInt(String key, int defaultValue) {
throw new IllegalStateException("Not Implemented yet!");
}
public long getLong(String key) {
throw new IllegalStateException("Not Implemented yet!");
}
public long getLong(String key, long defaultValue) {
throw new IllegalStateException("Not Implemented yet!");
}
public BigInteger getBigInteger(String key) {
return (BigInteger) values.get(key);
}
public BigInteger getBigIntegerAt(String key, int index) {
Object value = getObject(key);
if (value instanceof List) {
List list = (List) value;
return (BigInteger) list.get(index);
}
if (value instanceof BigInteger[]) {
return ((BigInteger[]) value)[index];
}
throw new IllegalArgumentException("Key not found or invalid");
}
public BigInteger getBigInteger(String key, BigInteger defaultValue) {
throw new IllegalStateException("Not Implemented yet!");
}
public String getString(String key) {
throw new IllegalStateException("Not Implemented yet!");
}
public String getString(String key, String defaultValue) {
throw new IllegalStateException("Not Implemented yet!");
}
public byte[] getBytes(String key) {
throw new IllegalStateException("Not Implemented yet!");
}
public byte[] getBytes(String key, byte[] defaultValue) {
throw new IllegalStateException("Not Implemented yet!");
}
public Object getObject(String key) {
return values.get(key);
}
public String toString(String separator) {
throw new IllegalStateException("Not Implemented yet!");
}
public void putObject(String key, Object value) {
values.put(key, value);
}
public void putBigIntegerAt(String key, int index, BigInteger value) {
Object obj = getObject(key);
if (obj instanceof Map) {
Map map = (Map) obj;
map.put(index, value);
} else {
Map map = new HashMap<Integer, BigInteger>();
map.put(index, value);
values.put(key, map);
}
}
public void putBigInteger(String key, BigInteger value) {
values.put(key, value);
}
public void putBoolean(String key, boolean value) {
values.put(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MapParameters that = (MapParameters) o;
if (values != null ? !values.equals(that.values) : that.values != null) return false;
return true;
}
@Override
public int hashCode() {
return values != null ? values.hashCode() : 0;
}
}
| 3,657 | 24.58042 | 93 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/parameters/MutableMapParameters.java | package it.unisa.dia.gas.plaf.jpbc.pairing.parameters;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class MutableMapParameters extends MapParameters implements MutablePairingParameters {
public MutableMapParameters() {
}
}
| 267 | 18.142857 | 93 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/parameters/MutablePairingParameters.java | package it.unisa.dia.gas.plaf.jpbc.pairing.parameters;
import it.unisa.dia.gas.jpbc.PairingParameters;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*
* @since 2.0.0
*/
public interface MutablePairingParameters extends PairingParameters {
void putObject(String key, Object value);
void putBigIntegerAt(String key, int index, BigInteger value);
void putBigInteger(String key, BigInteger value);
void putBoolean(String key, boolean value);
}
| 500 | 20.782609 | 69 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/parameters/PropertiesParameters.java | package it.unisa.dia.gas.plaf.jpbc.pairing.parameters;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.plaf.jpbc.util.io.Base64;
import java.io.*;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class PropertiesParameters implements PairingParameters, Externalizable {
protected final Map<String, String> parameters;
public PropertiesParameters() {
this.parameters = new LinkedHashMap<String, String>();
}
public String getType() {
return parameters.get("type");
}
public boolean containsKey(String key) {
return parameters.containsKey(key);
}
public int getInt(String key) {
String value = parameters.get(key);
if (value == null)
throw new IllegalArgumentException("Cannot find value for the following key : " + key);
return Integer.parseInt(value);
}
public int getInt(String key, int defaultValue) {
String value = parameters.get(key);
if (value == null)
return defaultValue;
return Integer.parseInt(value);
}
public long getLong(String key) {
String value = parameters.get(key);
if (value == null)
throw new IllegalArgumentException("Cannot find value for the following key : " + key);
return Long.parseLong(value);
}
public long getLong(String key, long defaultValue) {
String value = parameters.get(key);
if (value == null)
return defaultValue;
return Long.parseLong(value);
}
public BigInteger getBigInteger(String key) {
String value = parameters.get(key);
if (value == null)
throw new IllegalArgumentException("Cannot find value for the following key : " + key);
return new BigInteger(value);
}
public BigInteger getBigIntegerAt(String key, int index) {
return getBigInteger(key+index);
}
public BigInteger getBigInteger(String key, BigInteger defaultValue) {
String value = parameters.get(key);
if (value == null)
return defaultValue;
return new BigInteger(value);
}
public String getString(String key) {
String value = parameters.get(key);
if (value == null)
throw new IllegalArgumentException("Cannot find value for the following key : " + key);
return value;
}
public String getString(String key, String defaultValue) {
String value = parameters.get(key);
if (value == null)
return defaultValue;
return value;
}
public byte[] getBytes(String key) {
try {
return Base64.decode(getString(key));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public byte[] getBytes(String key, byte[] defaultValue) {
String value = parameters.get(key);
if (value == null)
return defaultValue;
try {
return Base64.decode(value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Object getObject(String key) {
return parameters.get(key);
}
public String toString(String separator) {
StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
buffer.append(entry.getKey()).append(separator).append(entry.getValue()).append("\n");
}
return buffer.toString();
}
public void put(String key, String value) {
parameters.put(key, value);
}
public void putBytes(String key, byte[] bytes) {
parameters.put(key, Base64.encodeBytes(bytes, 0, bytes.length));
}
public String remove(String key) {
return parameters.remove(key);
}
public PropertiesParameters load(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
while (true) {
String line = reader.readLine();
if (line == null)
break;
line = line.trim();
if (line.length() == 0)
continue;
if (line.startsWith("#"))
continue;
StringTokenizer tokenizer = new StringTokenizer(line, "= :", false);
String key = tokenizer.nextToken();
String value = tokenizer.nextToken();
parameters.put(key, value);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return this;
}
public PropertiesParameters load(String path) {
InputStream inputStream;
File file = new File(path);
if (file.exists()) {
try {
inputStream = file.toURI().toURL().openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
}
if (inputStream == null)
throw new IllegalArgumentException("No valid resource found!");
load(inputStream);
try {
inputStream.close();
} catch (IOException e) {
// Discard
}
return this;
}
public String toString() {
return toString(" ");
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(toString());
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
load(new ByteArrayInputStream(in.readUTF().getBytes()));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PropertiesParameters that = (PropertiesParameters) o;
if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false;
return true;
}
@Override
public int hashCode() {
return parameters != null ? parameters.hashCode() : 0;
}
}
| 6,363 | 26.196581 | 109 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/product/ProductPairing.java | package it.unisa.dia.gas.plaf.jpbc.pairing.product;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.field.vector.VectorField;
import it.unisa.dia.gas.plaf.jpbc.pairing.accumulator.PairingAccumulator;
import it.unisa.dia.gas.plaf.jpbc.pairing.accumulator.PairingAccumulatorFactory;
import it.unisa.dia.gas.plaf.jpbc.pairing.accumulator.ProductPairingAccumulator;
import it.unisa.dia.gas.plaf.jpbc.pairing.map.DefaultPairingPreProcessing;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ProductPairing implements Pairing {
protected Pairing basePairing;
protected Field G1, G2;
public ProductPairing(SecureRandom random, Pairing basePairing, int n) {
this.basePairing = basePairing;
this.G1 = new VectorField(random, basePairing.getG1(), n);
this.G2 = new VectorField(random, basePairing.getG2(), n);
}
public boolean isSymmetric() {
return basePairing.isSymmetric();
}
public Field getG1() {
return G1;
}
public Field getG2() {
return G2;
}
public Field getGT() {
return basePairing.getGT();
}
public Field getZr() {
return basePairing.getZr();
}
public int getDegree() {
return 2;
}
public Field getFieldAt(int index) {
switch (index) {
case 0:
return basePairing.getZr();
case 1:
return G1;
case 2:
return G2;
case 3:
return basePairing.getGT();
default:
throw new IllegalArgumentException("invalid index");
}
}
public Element pairing(Element in1, Element in2) {
Vector v1 = (Vector) in1;
Vector v2 = (Vector) in2;
PairingAccumulator combiner = (basePairing.isProductPairingSupported()) ?
new ProductPairingAccumulator(basePairing, v1.getSize()) :
PairingAccumulatorFactory.getInstance().getPairingMultiplier(basePairing);
for (int i = 0; i < v1.getSize(); i++) {
combiner.addPairing(v1.getAt(i), v2.getAt(i));
}
return combiner.awaitResult();
}
public boolean isProductPairingSupported() {
return false;
}
public Element pairing(Element[] in1, Element[] in2) {
PairingAccumulator combiner = PairingAccumulatorFactory.getInstance().getPairingMultiplier(basePairing);
for (int i = 0; i < in1.length; i++) {
combiner.addPairing(in1[i], in2[i]);
}
return combiner.awaitResult();
}
public PairingPreProcessing getPairingPreProcessingFromElement(final Element in1) {
return new DefaultPairingPreProcessing(this, in1);
}
public int getPairingPreProcessingLengthInBytes() {
throw new IllegalStateException("Not implemented yet!!!");
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source) {
throw new IllegalStateException("Not implemented yet!!!");
}
public PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source, int offset) {
throw new IllegalStateException("Not implemented yet!!!");
}
public int getFieldIndex(Field field) {
throw new IllegalStateException("Not Implemented yet!");
}
} | 3,362 | 29.297297 | 112 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/Arrays.java | package it.unisa.dia.gas.plaf.jpbc.util;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class Arrays {
public static byte[] copyOf(byte[] original, int newLength) {
int len = Math.min(original.length, newLength);
byte[] copy = new byte[len];
System.arraycopy(original, 0, copy, 0, len);
return copy;
}
public static byte[] copyOf(byte[] original, int offset, int newLength) {
int len = Math.min(original.length - offset, newLength);
byte[] copy = new byte[len];
System.arraycopy(original, offset, copy, 0, len);
return copy;
}
public static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
}
| 1,013 | 29.727273 | 77 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/ElementUtils.java | package it.unisa.dia.gas.plaf.jpbc.util;
import it.unisa.dia.gas.jpbc.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class ElementUtils {
public static Element[] duplicate(Element[] source) {
Element[] target = new Element[source.length];
for (int i = 0; i < target.length; i++)
target[i] = source[i].duplicate();
return target;
}
public static Element[] cloneImmutable(Element[] source) {
Element[] target = Arrays.copyOf(source, source.length);
for (int i = 0; i < target.length; i++) {
Element uElement = target[i];
if (uElement != null && !uElement.isImmutable())
target[i] = target[i].getImmutable();
}
return target;
}
public static <K> Map<K, Element[]> cloneImmutable(Map<K, Element[]> source) {
Map<K, Element[]> dest = new HashMap<K, Element[]>(source.size());
for (Map.Entry<K, Element[]> kEntry : source.entrySet())
dest.put(kEntry.getKey(), cloneImmutable(kEntry.getValue()));
return dest;
}
public static <K> Map<K, Element> cloneImmutable2(Map<K, Element> source) {
Map<K, Element> dest = new HashMap<K, Element>(source.size());
for (Map.Entry<K, Element> kEntry : source.entrySet())
dest.put(kEntry.getKey(), kEntry.getValue().getImmutable());
return dest;
}
public static ElementPow[] cloneToElementPow(Element[] source) {
ElementPow[] target = new ElementPow[source.length];
for (int i = 0; i < target.length; i++) {
target[i] = source[i].getElementPowPreProcessing();
}
return target;
}
public static Element randomIn(Pairing pairing, Element generator) {
return generator.duplicate().powZn(pairing.getZr().newRandomElement());
}
public static Element getGenerator(Pairing pairing, Element generator, PairingParameters parameters, int subgroupIndex, int numPrimes) {
BigInteger prod = BigInteger.ONE;
for (int j = 0; j < numPrimes; j++) {
if (j != subgroupIndex)
prod = prod.multiply(parameters.getBigIntegerAt("n", j));
}
return generator.pow(prod);
}
public static void print(Element[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(matrix[i][j] + ", ");
}
System.out.println();
}
System.out.println();
}
public static Element[][] transpose(Element[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
Element temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return matrix;
}
public static Element[][] multiply(Element[][] a, Element[][] b) {
int n = a.length;
Field field = a[0][0].getField();
Element[][] res = new Element[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = field.newZeroElement();
for (int k = 0; k < n; k++)
res[i][j].add(a[i][k].duplicate().mul(b[k][j]));
}
}
return res;
}
public static void copyArray(Element[][] target, Element[][] source, int sizeY, int sizeX, int y, int x) {
for (int i = y; i < sizeY; i++) {
for (int j = x; j < sizeX; j++) {
target[i - y][j - x] = source[i][j].duplicate();
}
}
}
}
| 3,848 | 27.93985 | 140 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/collection/FlagMap.java | package it.unisa.dia.gas.plaf.jpbc.util.collection;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class FlagMap<K> {
protected LatchHashMap<K, Boolean> flags;
public FlagMap() {
this.flags = new LatchHashMap<K, Boolean>();
}
public void get(K key) {
flags.get(key);
}
public void set(K key) {
flags.put(key, true);
}
}
| 408 | 16.041667 | 52 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/collection/LatchHashMap.java | package it.unisa.dia.gas.plaf.jpbc.util.collection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class LatchHashMap<K, V> implements Map<K, V> {
private Map<K, ValueLatch> internalMap;
public LatchHashMap() {
this.internalMap = new HashMap<K, ValueLatch>();
}
public int size() {
return internalMap.size();
}
public boolean isEmpty() {
return internalMap.isEmpty();
}
public boolean containsKey(Object key) {
return internalMap.containsKey(key);
}
public boolean containsValue(Object value) {
throw new IllegalStateException("Not implemented yet!");
}
public V get(Object key) {
return getLatch(key).get();
}
public V put(K key, V value) {
return getLatch(key).set(value);
}
public V remove(Object key) {
throw new IllegalStateException("Not implemented yet!");
}
public void putAll(Map<? extends K, ? extends V> m) {
throw new IllegalStateException("Not implemented yet!");
}
public void clear() {
throw new IllegalStateException("Not implemented yet!");
}
public Set<K> keySet() {
throw new IllegalStateException("Not implemented yet!");
}
public Collection<V> values() {
throw new IllegalStateException("Not implemented yet!");
}
public Set<Entry<K,V>> entrySet() {
throw new IllegalStateException("Not implemented yet!");
}
@Override
public boolean equals(Object o) {
return internalMap.equals(o);
}
@Override
public int hashCode() {
return internalMap.hashCode();
}
protected ValueLatch<V> getLatch(Object key) {
ValueLatch<V> latch;
synchronized (this) {
if (containsKey(key))
latch = internalMap.get(key);
else {
latch = new ValueLatch();
internalMap.put((K) key, latch);
}
}
return latch;
}
class ValueLatch<V> extends CountDownLatch {
V value;
ValueLatch() {
super(1);
}
V set(V value) {
V old = this.value;
this.value = value;
countDown();
return old;
}
V get() {
try {
await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return value;
}
}
}
| 2,662 | 20.650407 | 64 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/ExecutorServiceUtils.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ExecutorServiceUtils {
private static ExecutorService fixedThreadPool;
private static ExecutorService cachedThreadPool;
static {
fixedThreadPool = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() * 4
);
cachedThreadPool = Executors.newCachedThreadPool();
}
private ExecutorServiceUtils() {
}
public static ExecutorService getFixedThreadPool() {
return fixedThreadPool;
}
public static ExecutorService getCachedThreadPool() {
return cachedThreadPool;
}
public static void shutdown() {
fixedThreadPool.shutdown();
cachedThreadPool.shutdown();
}
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public abstract static class IndexCallable<T> implements Callable<T> {
protected int i, j;
public IndexCallable(int i) {
this.i = i;
}
public IndexCallable(int i, int j) {
this.i = i;
this.j = j;
}
}
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 1.2.2
*/
public abstract static class IndexRunnable implements Runnable {
protected int i, j;
public IndexRunnable(int i) {
this.i = i;
}
public IndexRunnable(int i, int j) {
this.i = i;
this.j = j;
}
}
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public abstract static class IntervalCallable<T> implements Callable<T> {
protected int from, to;
protected IntervalCallable(int from, int to) {
this.from = from;
this.to = to;
}
}
}
| 2,023 | 21.488889 | 77 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/Pool.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent;
import java.util.concurrent.Callable;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public interface Pool<T> {
Pool<T> submit(Callable<T> callable);
Pool<T> submit(Runnable runnable);
Pool<T> awaitTermination();
}
| 308 | 16.166667 | 51 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/PoolExecutor.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class PoolExecutor<T> implements Pool<T> {
protected CompletionService<T> pool;
protected int counter;
public PoolExecutor() {
this(ExecutorServiceUtils.getFixedThreadPool());
}
public PoolExecutor(Executor executor) {
this.pool = new ExecutorCompletionService<T>(executor);
this.counter = 0;
}
public Pool<T> submit(Callable<T> callable) {
counter++;
pool.submit(callable);
return this;
}
public Pool<T> submit(Runnable runnable) {
counter++;
pool.submit(runnable, null);
return this;
}
public Pool<T> awaitTermination() {
try {
for (int i = 0; i < counter; i++)
pool.take().get();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
counter = 0;
}
return this;
}
}
| 1,215 | 20.714286 | 63 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/accumultor/AbstractAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.ExecutorServiceUtils;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.Pool;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.PoolExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public abstract class AbstractAccumulator<T> extends PoolExecutor<T> implements Accumulator<T> {
protected T result;
public AbstractAccumulator() {
this(ExecutorServiceUtils.getFixedThreadPool());
}
public AbstractAccumulator(Executor executor) {
super(executor);
}
public Accumulator<T> accumulate(Callable<T> callable) {
submit(callable);
return this;
}
public Pool<T> submit(Runnable runnable) {
throw new IllegalStateException("Invalid call method!");
}
public Accumulator<T> awaitTermination() {
try {
for (int i = 0; i < counter; i++)
reduce(pool.take().get());
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
counter = 0;
}
return this;
}
public T getResult() {
return result;
}
public T awaitResult() {
return awaitTermination().getResult();
}
protected abstract void reduce(T value);
}
| 1,445 | 21.952381 | 96 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/accumultor/Accumulator.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.Pool;
import java.util.concurrent.Callable;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public interface Accumulator<T> extends Pool<T> {
Accumulator<T> accumulate(Callable<T> callable);
Accumulator<T> awaitTermination();
T awaitResult();
T getResult();
}
| 419 | 18.090909 | 62 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/accumultor/BigIntegerAddAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class BigIntegerAddAccumulator extends AbstractAccumulator<BigInteger> {
public BigIntegerAddAccumulator() {
this.result = BigInteger.ZERO;
}
protected void reduce(BigInteger value) {
result = result.add(value);
}
}
| 424 | 18.318182 | 79 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/accumultor/BigIntegerAddModAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class BigIntegerAddModAccumulator extends AbstractAccumulator<BigInteger> {
private BigInteger modulo;
public BigIntegerAddModAccumulator(BigInteger modulo) {
this.result = BigInteger.ZERO;
this.modulo = modulo;
}
protected void reduce(BigInteger value) {
result = result.add(value).mod(modulo);
}
}
| 520 | 20.708333 | 82 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/accumultor/BigIntegerMulAccumulator.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.accumultor;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class BigIntegerMulAccumulator extends AbstractAccumulator<BigInteger> {
public BigIntegerMulAccumulator() {
this.result = BigInteger.ONE;
}
protected void reduce(BigInteger value) {
result = result.multiply(value);
}
}
| 427 | 19.380952 | 79 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/context/ContextExecutor.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.context;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.MutablePairingParameters;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.ExecutorServiceUtils;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.Pool;
import it.unisa.dia.gas.plaf.jpbc.util.concurrent.PoolExecutor;
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ContextExecutor extends PoolExecutor implements MutablePairingParameters {
private MutablePairingParameters parameters;
public ContextExecutor(MutablePairingParameters parameters) {
super(ExecutorServiceUtils.getCachedThreadPool());
this.parameters = parameters;
}
public ContextExecutor(Executor executor, MutablePairingParameters parameters) {
super(executor);
this.parameters = parameters;
}
public Pool submit(Callable callable) {
throw new IllegalStateException("Invalid method invocation!");
}
public ContextExecutor submit(ContextRunnable runnable) {
runnable.setExecutor(this);
super.submit(runnable);
return this;
}
public void putBigIntegerAt(String key, int index, BigInteger value) {
parameters.putBigIntegerAt(key, index, value);
}
public void putBigInteger(String key, BigInteger value) {
parameters.putBigInteger(key, value);
}
public void putBoolean(String key, boolean value) {
parameters.putBoolean(key, value);
}
public void putObject(String key, Object value) {
parameters.putObject(key, value);
}
public boolean containsKey(String key) {
return parameters.containsKey(key);
}
public String getString(String key) {
return parameters.getString(key);
}
public String getString(String key, String defaultValue) {
return parameters.getString(key, defaultValue);
}
public int getInt(String key) {
return parameters.getInt(key);
}
public int getInt(String key, int defaultValue) {
return parameters.getInt(key, defaultValue);
}
public BigInteger getBigInteger(String key) {
return parameters.getBigInteger(key);
}
public BigInteger getBigIntegerAt(String key, int index) {
return parameters.getBigIntegerAt(key, index);
}
public BigInteger getBigInteger(String key, BigInteger defaultValue) {
return parameters.getBigInteger(key, defaultValue);
}
public long getLong(String key) {
return parameters.getLong(key);
}
public long getLong(String key, long defaultValue) {
return parameters.getLong(key, defaultValue);
}
public byte[] getBytes(String key) {
return parameters.getBytes(key);
}
public byte[] getBytes(String key, byte[] defaultValue) {
return parameters.getBytes(key, defaultValue);
}
public String toString(String separator) {
return parameters.toString(separator);
}
public Object getObject(String key) {
return parameters.getObject(key);
}
}
| 3,206 | 26.646552 | 87 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/context/ContextRunnable.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.context;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.MutablePairingParameters;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public abstract class ContextRunnable implements Runnable, MutablePairingParameters {
private String name;
private ContextExecutor executor;
public ContextRunnable() {
}
public ContextRunnable(String name) {
this.name = name;
}
public ContextExecutor getExecutor() {
return executor;
}
public void setExecutor(ContextExecutor executor) {
this.executor = executor;
}
public void putBigInteger(String key, BigInteger value) {
executor.putBigInteger(key, value);
}
public void putBigIntegerAt(String key, int index, BigInteger value) {
executor.putBigIntegerAt(key, index, value);
}
public void putBoolean(String key, boolean value) {
executor.putBoolean(key, value);
}
public void putObject(String key, Object value) {
executor.putObject(key, value);
}
public boolean containsKey(String key) {
return executor.containsKey(key);
}
public String getString(String key) {
return executor.getString(key);
}
public String getString(String key, String defaultValue) {
return executor.getString(key, defaultValue);
}
public int getInt(String key) {
return executor.getInt(key);
}
public int getInt(String key, int defaultValue) {
return executor.getInt(key, defaultValue);
}
public BigInteger getBigInteger(String key) {
return executor.getBigInteger(key);
}
public BigInteger getBigIntegerAt(String key, int index) {
return executor.getBigIntegerAt(key, index);
}
public BigInteger getBigInteger(String key, BigInteger defaultValue) {
return executor.getBigInteger(key, defaultValue);
}
public long getLong(String key) {
return executor.getLong(key);
}
public long getLong(String key, long defaultValue) {
return executor.getLong(key, defaultValue);
}
public byte[] getBytes(String key) {
return executor.getBytes(key);
}
public byte[] getBytes(String key, byte[] defaultValue) {
return executor.getBytes(key, defaultValue);
}
public String toString(String separator) {
return executor.toString(separator);
}
public Object getObject(String key) {
return executor.getObject(key);
}
}
| 2,592 | 23.695238 | 85 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/recursive/RecursiveBigIntegerMultiplier.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.recursive;
import java.math.BigInteger;
import java.util.concurrent.RecursiveTask;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class RecursiveBigIntegerMultiplier extends RecursiveTask<BigInteger> {
static final int SEQUENTIAL_THRESHOLD = 2;
BigInteger[] values;
int low;
int high;
public RecursiveBigIntegerMultiplier(BigInteger[] values, int lo, int hi) {
this.values = values;
this.low = lo;
this.high = hi;
}
protected BigInteger compute() {
if (high == low) {
return values[low];
}
if (high - low < SEQUENTIAL_THRESHOLD) {
return values[low].multiply(values[high]);
} else {
int mid = low + (high - low) / 2;
RecursiveBigIntegerMultiplier left = new RecursiveBigIntegerMultiplier(values, low, mid);
RecursiveBigIntegerMultiplier right = new RecursiveBigIntegerMultiplier(values, mid + 1, high);
left.fork();
BigInteger rightAns = right.compute();
BigInteger leftAns = left.join();
return rightAns.multiply(leftAns);
}
}
}
| 1,225 | 26.244444 | 107 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/concurrent/recursive/RecursiveMultiplier.java | package it.unisa.dia.gas.plaf.jpbc.util.concurrent.recursive;
import it.unisa.dia.gas.jpbc.Element;
import java.util.concurrent.RecursiveTask;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class RecursiveMultiplier extends RecursiveTask<Element> {
static final int SEQUENTIAL_THRESHOLD = 2;
Element[] elements;
int low;
int high;
public RecursiveMultiplier(Element[] elements, int lo, int hi) {
this.elements = elements;
this.low = lo;
this.high = hi;
}
protected Element compute() {
if (high == low) {
return elements[low];
}
if (high - low < SEQUENTIAL_THRESHOLD) {
return elements[low].mul(elements[high]);
} else {
int mid = low + (high - low) / 2;
RecursiveMultiplier left = new RecursiveMultiplier(elements, low, mid);
RecursiveMultiplier right = new RecursiveMultiplier(elements, mid + 1, high);
left.fork();
Element rightAns = right.compute();
Element leftAns = left.join();
return rightAns.mul(leftAns);
}
}
}
| 1,165 | 24.347826 | 89 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/Base64.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
* Section 2.1, implementations should not add line feeds unless explicitly told
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline characters.</p>
* <p>Also...</p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
* value 01111111, which is an invalid base 64 character but should not
* throw an ArrayIndexOutOfBoundsException either. Led to discovery of
* mishandling (or potential for better handling) of other bad input
* characters. You should now get an IOException if you try decoding
* something that has bad characters in it.</li>
* <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
* string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li>
* <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
* was wrong for files of size 31, 34, and 37 bytes.</li>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
* the Base64.OutputStream closed the Base64 encoding (by padding with equals
* signs) too soon. Also added an option to suppress the automatic decoding
* of gzipped streams. Also added experimental support for specifying a
* class loader when using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
* method.</li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
* footprint with its CharEncoders and so forth. Fixed some javadocs that were
* inconsistent. Removed imports and specified things like java.io.IOException
* explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output
* arrays: an oversized initial one and then a final, exact-sized one. Big win
* when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
* using the gzip options which uses a different mechanism with streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
* similar helper methods to be more efficient with memory by not returning a
* String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
* Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance with
* <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some operations
* (especially those that may permit the GZIP option) use IO streams, there
* is a possiblity of an java.io.IOException being thrown. After some discussion and
* thought, I've changed the behavior of the methods to throw java.io.IOExceptions
* rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry,
* it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
* such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
* This was especially annoying before for people who were thorough in their
* own projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.3.7
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/** Defeats instantiation. */
private Base64(){}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> ByteBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> CharBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
for( int i = 0; i < 4; i++ ){
encoded.put( (char)(enc4[i] & 0xFF) );
}
} // end input remaining
}
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException if there is an error
* @throws NullPointerException if serializedObject is null
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
throws java.io.IOException {
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
if( (options & GZIP) != 0 ){
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream( gzos );
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream( b64os );
}
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue){
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes( byte[] source ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes( source, off, len, NO_OPTIONS );
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes( source, off, len, options );
// Return value according to relevant encoding.
try {
return new String( encoded, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source ) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
// Compress?
if( (options & GZIP) != 0 ) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e <= outBuff.length - 1 ){
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode( byte[] source )
throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
// } catch( java.io.IOException ex ) {
// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
// }
return decoded;
}
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiDecode = DECODABET[ source[i]&0xFF ];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = source[i]; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( source[i] == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee ) {
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 ) {
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e ) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
* If <tt>loader</tt> is not null, it will be the class loader
* used when deserializing.
*
* @param encodedObject The Base64 data to decode
* @param options Various parameters related to decoding
* @param loader Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 2.3.4
*/
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile( byte[] dataToEncode, String filename )
throws java.io.IOException {
if( dataToEncode == null ){
throw new NullPointerException( "Data to encode was null." );
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static void decodeToFile( String dataToDecode, String filename )
throws java.io.IOException {
Base64.OutputStream bos = null;
try{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
throws java.io.IOException {
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength ) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read( byte[] dest, int off, int len )
throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
if( b >= 0 ) {
dest[off + i] = (byte) b;
}
else if( i == 0 ) {
return -1;
}
else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out ) {
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options ) {
super( out );
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(int theByte)
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
this.out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to output.
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
* @throws java.io.IOException if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @throws java.io.IOException if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| 86,857 | 41.041626 | 170 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/ByteBufferDataInput.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ByteBufferDataInput implements DataInput {
private ByteBuffer byteBuffer;
public ByteBufferDataInput(ByteBuffer byteBuffer) {
this.byteBuffer = byteBuffer;
}
public void readFully(byte[] b) throws IOException {
byteBuffer.get(b);
}
public void readFully(byte[] b, int off, int len) throws IOException {
throw new IllegalStateException();
}
public int skipBytes(int n) throws IOException {
throw new IllegalStateException();
}
public boolean readBoolean() throws IOException {
throw new IllegalStateException();
}
public byte readByte() throws IOException {
return byteBuffer.get();
}
public int readUnsignedByte() throws IOException {
throw new IllegalStateException();
}
public short readShort() throws IOException {
throw new IllegalStateException();
}
public int readUnsignedShort() throws IOException {
throw new IllegalStateException();
}
public char readChar() throws IOException {
throw new IllegalStateException();
}
public int readInt() throws IOException {
return byteBuffer.getInt();
}
public long readLong() throws IOException {
return byteBuffer.getLong();
}
public float readFloat() throws IOException {
throw new IllegalStateException();
}
public double readDouble() throws IOException {
throw new IllegalStateException();
}
public String readLine() throws IOException {
throw new IllegalStateException();
}
public String readUTF() throws IOException {
throw new IllegalStateException();
}
}
| 1,896 | 22.7125 | 74 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/ByteBufferDataOutput.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ByteBufferDataOutput implements DataOutput {
private ByteBuffer buffer;
public ByteBufferDataOutput(ByteBuffer buffer) {
this.buffer = buffer;
}
public void write(int b) throws IOException {
throw new IllegalStateException();
}
public void write(byte[] b) throws IOException {
buffer.put(b);
}
public void write(byte[] b, int off, int len) throws IOException {
throw new IllegalStateException();
}
public void writeBoolean(boolean v) throws IOException {
throw new IllegalStateException();
}
public void writeByte(int v) throws IOException {
throw new IllegalStateException();
}
public void writeShort(int v) throws IOException {
throw new IllegalStateException();
}
public void writeChar(int v) throws IOException {
throw new IllegalStateException();
}
public void writeInt(int v) throws IOException {
buffer.putInt(v);
}
public void writeLong(long v) throws IOException {
throw new IllegalStateException();
}
public void writeFloat(float v) throws IOException {
throw new IllegalStateException();
}
public void writeDouble(double v) throws IOException {
throw new IllegalStateException();
}
public void writeBytes(String s) throws IOException {
throw new IllegalStateException();
}
public void writeChars(String s) throws IOException {
throw new IllegalStateException();
}
public void writeUTF(String s) throws IOException {
throw new IllegalStateException();
}
}
| 1,839 | 23.210526 | 70 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/ExByteArrayInputStream.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import java.io.ByteArrayInputStream;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 1.0.0
*/
public class ExByteArrayInputStream extends ByteArrayInputStream {
public ExByteArrayInputStream(byte[] buf) {
super(buf);
}
public ExByteArrayInputStream(byte[] buf, int offset, int length) {
super(buf, offset, length);
}
public int getPos() {
return pos;
}
}
| 467 | 17.72 | 71 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/FieldStreamReader.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import java.io.DataInputStream;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class FieldStreamReader {
private Field field;
private byte[] buffer;
private int offset;
private int cursor;
private DataInputStream dis;
private ExByteArrayInputStream bais;
public FieldStreamReader(Field field, byte[] buffer, int offset) {
this.field = field;
this.buffer = buffer;
this.offset = offset;
this.cursor = offset;
this.bais = new ExByteArrayInputStream(buffer, offset, buffer.length - offset);
this.dis = new DataInputStream(bais);
}
public void reset() {
this.cursor = this.offset;
}
public Element readElement() {
Element element = field.newElementFromBytes(buffer, cursor);
jump(field.getLengthInBytes(element));
return element;
}
public String readString() {
try {
return dis.readUTF();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
cursor = bais.getPos();
}
}
public int readInt() {
try {
return dis.readInt();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
cursor = bais.getPos();
}
}
private void jump(int length) {
cursor += length;
bais.skip(length);
}
}
| 1,569 | 20.506849 | 87 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/PairingDataInput.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import it.unisa.dia.gas.jpbc.*;
import java.io.DataInput;
import java.io.IOException;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class PairingDataInput implements DataInput {
private DataInput dataInput;
private Pairing pairing;
public PairingDataInput(DataInput dataInput) {
this.dataInput = dataInput;
}
public PairingDataInput(DataInput dataInput, Pairing pairing) {
this.dataInput = dataInput;
this.pairing = pairing;
}
public void readFully(byte[] b) throws IOException {
dataInput.readFully(b);
}
public void readFully(byte[] b, int off, int len) throws IOException {
dataInput.readFully(b, off, len);
}
public int skipBytes(int n) throws IOException {
return dataInput.skipBytes(n);
}
public boolean readBoolean() throws IOException {
return dataInput.readBoolean();
}
public byte readByte() throws IOException {
return dataInput.readByte();
}
public int readUnsignedByte() throws IOException {
return dataInput.readUnsignedByte();
}
public short readShort() throws IOException {
return dataInput.readShort();
}
public int readUnsignedShort() throws IOException {
return dataInput.readUnsignedShort();
}
public char readChar() throws IOException {
return dataInput.readChar();
}
public int readInt() throws IOException {
return dataInput.readInt();
}
public long readLong() throws IOException {
return dataInput.readLong();
}
public float readFloat() throws IOException {
return dataInput.readFloat();
}
public double readDouble() throws IOException {
return dataInput.readDouble();
}
public String readLine() throws IOException {
return dataInput.readLine();
}
public String readUTF() throws IOException {
return dataInput.readUTF();
}
public Pairing getPairing() {
return pairing;
}
public Field readField() throws IOException {
int identifier = readInt();
return pairing.getFieldAt(identifier);
}
public Element readElement(int fieldIdentifier) throws IOException {
byte[] buffer = new byte[readInt()];
readFully(buffer);
return pairing.getFieldAt(fieldIdentifier).newElementFromBytes(buffer);
}
public Element[] readElements(int identifier) throws IOException{
int num = readInt();
Element[] elements = new Element[num];
for (int i = 0; i < num; i++) {
elements[i] = readElement(identifier);
}
return elements;
}
public PairingPreProcessing readPairingPreProcessing() throws IOException {
int size = readInt();
byte[] buffer = new byte[size];
readFully(buffer);
return getPairing().getPairingPreProcessingFromBytes(buffer, 0);
}
public ElementPowPreProcessing readElementPowPreProcessing() throws IOException {
// Read field identifier
Field field = readField();
// read the preprocessing information
int size = readInt();
byte[] buffer = new byte[size];
readFully(buffer);
return field.getElementPowPreProcessingFromBytes(buffer, 0);
}
public int[] readInts() throws IOException {
int num = readInt();
int[] elements = new int[num];
for (int i = 0; i < num; i++) {
elements[i] = readInt();
}
return elements;
}
public byte[] readBytes() throws IOException {
int length = readInt();
byte[] buffer = new byte[length];
readFully(buffer);
return buffer;
}
public BigInteger readBigInteger() throws IOException {
return new BigInteger(readBytes());
}
public BigInteger[] readBigIntegers() throws IOException {
int num = readInt();
BigInteger[] bigIntegers = new BigInteger[num];
for (int i = 0; i < bigIntegers.length; i++) {
bigIntegers[i] = readBigInteger();
}
return bigIntegers;
}
} | 4,227 | 24.317365 | 85 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/PairingDataOutput.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import it.unisa.dia.gas.jpbc.*;
import it.unisa.dia.gas.plaf.jpbc.util.Arrays;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class PairingDataOutput implements DataOutput {
private DataOutput dataOutput;
private Pairing pairing;
public PairingDataOutput(DataOutput dataOutput) {
this(null, dataOutput);
}
public PairingDataOutput(Pairing pairing, DataOutput dataOutput) {
this.pairing = pairing;
this.dataOutput = dataOutput;
}
public void write(int b) throws IOException {
dataOutput.write(b);
}
public void write(byte[] b) throws IOException {
dataOutput.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
dataOutput.write(b, off, len);
}
public void writeBoolean(boolean v) throws IOException {
dataOutput.writeBoolean(v);
}
public void writeByte(int v) throws IOException {
dataOutput.writeByte(v);
}
public void writeShort(int v) throws IOException {
dataOutput.writeShort(v);
}
public void writeChar(int v) throws IOException {
dataOutput.writeChar(v);
}
public void writeInt(int v) throws IOException {
dataOutput.writeInt(v);
}
public void writeLong(long v) throws IOException {
dataOutput.writeLong(v);
}
public void writeFloat(float v) throws IOException {
dataOutput.writeFloat(v);
}
public void writeDouble(double v) throws IOException {
dataOutput.writeDouble(v);
}
public void writeBytes(String s) throws IOException {
dataOutput.writeBytes(s);
}
public void writeChars(String s) throws IOException {
dataOutput.writeChars(s);
}
public void writeUTF(String s) throws IOException {
dataOutput.writeUTF(s);
}
public void writeElement(Element element) throws IOException {
if (element == null)
writeInt(0);
else {
byte[] bytes = element.toBytes();
writeInt(bytes.length);
write(bytes);
}
}
public void writeElements(Element[] elements) throws IOException {
if (elements == null)
writeInt(0);
else {
writeInt(elements.length);
for (Element e : elements)
writeElement(e);
}
}
public void writePreProcessing(PreProcessing processing) throws IOException {
byte[] buffer = processing.toBytes();
if (processing instanceof ElementPowPreProcessing) {
// write additional information on the field
ElementPowPreProcessing powPreProcessing = (ElementPowPreProcessing) processing;
writePairingFieldIndex(powPreProcessing.getField());
}
writeInt(buffer.length);
writeBytes(buffer);
}
public void writeInts(int[] ints) throws IOException {
if (ints == null) {
writeInt(0);
} else {
writeInt(ints.length);
for (int anInt : ints) writeInt(anInt);
}
}
public void writeBytes(byte[] buffer) throws IOException{
writeInt(buffer.length);
write(buffer);
}
public Pairing getPairing() {
return pairing;
}
public void writeBigInteger(BigInteger bigInteger) throws IOException {
writeBytes(bigInteger.toByteArray());
}
public void writeBigInteger(BigInteger bigInteger, int ensureLength) throws IOException {
byte[] bytes = bigInteger.toByteArray();
if (bytes.length > ensureLength) {
// strip the zero prefix
if (bytes[0] == 0 && bytes.length == ensureLength + 1) {
// Remove it
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
} else
throw new IllegalStateException("result has more than allowed bytes.");
} else if (bytes.length < ensureLength) {
byte[] result = new byte[ensureLength];
System.arraycopy(bytes, 0, result, ensureLength - bytes.length, bytes.length);
bytes = result;
}
writeBytes(bytes);
}
public void writeBigIntegers(BigInteger[] bigIntegers) throws IOException {
writeInt(bigIntegers.length);
for (BigInteger bigInteger : bigIntegers) {
writeBigInteger(bigInteger);
}
}
public void writeBigIntegers(BigInteger[] bigIntegers, int ensureLength) throws IOException {
writeInt(bigIntegers.length);
for (BigInteger bigInteger : bigIntegers) {
writeBigInteger(bigInteger, ensureLength);
}
}
protected void writePairingFieldIndex(Field field) throws IOException {
int index = getPairing().getFieldIndex(field);
if (index == -1)
throw new IllegalArgumentException("The field does not belong to the current pairing instance.");
writeInt(index);
}
} | 5,108 | 26.616216 | 109 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/PairingStreamReader.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Pairing;
import java.io.DataInputStream;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class PairingStreamReader {
private Pairing pairing;
private byte[] buffer;
private int offset;
private int cursor;
private DataInputStream dis;
private ExByteArrayInputStream bais;
public PairingStreamReader(Pairing pairing, byte[] buffer, int offset) {
this.pairing = pairing;
this.buffer = buffer;
this.offset = offset;
this.cursor = offset;
this.bais = new ExByteArrayInputStream(buffer, offset, buffer.length - offset);
this.dis = new DataInputStream(bais);
}
public void reset() {
this.cursor = this.offset;
}
public Element[] readElements(int... ids) {
Element[] elements = new Element[ids.length];
for (int i = 0; i < ids.length; i++) {
Field field = pairing.getFieldAt(ids[i]);
elements[i] = field.newElementFromBytes(buffer, cursor);
jump(field.getLengthInBytes(elements[i]));
}
return elements;
}
public Element[] readElements(int id, int count) {
Element[] elements = new Element[count];
Field field = pairing.getFieldAt(id);
for (int i = 0; i < count; i++) {
elements[i] = field.newElementFromBytes(buffer, cursor);
jump(field.getLengthInBytes(elements[i]));
}
return elements;
}
public Element[] readG1Elements(int count) {
return readElements(1, count);
}
public Element readG1Element() {
Element element = pairing.getG1().newElementFromBytes(buffer, cursor);
jump(pairing.getG1().getLengthInBytes(element));
return element;
}
public Element readGTElement() {
Element element = pairing.getGT().newElementFromBytes(buffer, cursor);
jump(pairing.getGT().getLengthInBytes(element));
return element;
}
public Element readFieldElement(Field field) {
Element element = field.newElementFromBytes(buffer, cursor);
jump(field.getLengthInBytes(element));
return element;
}
public String readString() {
try {
return dis.readUTF();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
cursor = bais.getPos();
}
}
public int readInt() {
try {
return dis.readInt();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
cursor = bais.getPos();
}
}
private void jump(int length) {
cursor += length;
bais.skip(length);
}
}
| 2,875 | 23.793103 | 87 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/PairingStreamWriter.java | package it.unisa.dia.gas.plaf.jpbc.util.io;
import it.unisa.dia.gas.jpbc.Element;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class PairingStreamWriter {
private ByteArrayOutputStream baos;
private DataOutputStream dos;
public PairingStreamWriter(int size) {
this.baos = new ByteArrayOutputStream(size);
this.dos = new DataOutputStream(baos);
}
public void write(String s) throws IOException {
dos.writeUTF(s);
}
public void write(Element element) throws IOException {
dos.write(element.toBytes());
}
public void writeInt(int value) throws IOException {
dos.writeInt(value);
}
public void write(byte[] bytes) throws IOException {
dos.write(bytes);
}
public byte[] toBytes() {
return baos.toByteArray();
}
}
| 964 | 19.978261 | 59 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/ArraySector.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public interface ArraySector<T> extends Sector {
int getSize();
T getAt(int index);
void setAt(int index, T value);
T getAt(String label);
void setAt(String label, T value);
}
| 323 | 14.428571 | 48 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/ByteBufferBigIntegerArraySector.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
import it.unisa.dia.gas.plaf.jpbc.util.io.ByteBufferDataInput;
import it.unisa.dia.gas.plaf.jpbc.util.io.ByteBufferDataOutput;
import it.unisa.dia.gas.plaf.jpbc.util.io.PairingDataInput;
import it.unisa.dia.gas.plaf.jpbc.util.io.PairingDataOutput;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ByteBufferBigIntegerArraySector implements ArraySector<BigInteger> {
protected ByteBuffer buffer;
protected int offset, recordSize, recordLength, numRecords;
protected int lengthInBytes;
protected PairingDataInput in;
protected PairingDataOutput out;
protected Map<String, Integer> labelsMap;
public ByteBufferBigIntegerArraySector(int recordSize, int numRecords) throws IOException {
this.lengthInBytes = 4 + ((recordSize + 4) * numRecords);
this.offset = 4;
this.recordSize = recordSize;
this.recordLength = recordSize + 4;
this.numRecords = numRecords;
}
public ByteBufferBigIntegerArraySector(int recordSize, int numRecords, String... labels) throws IOException {
this(recordSize, numRecords);
labelsMap = new HashMap<String, Integer>(labels.length);
for (int i = 0; i < labels.length; i++) {
labelsMap.put(labels[i], i);
}
}
public int getLengthInBytes() {
return lengthInBytes;
}
public int getSize() {
return numRecords;
}
public synchronized ArraySector<BigInteger> mapTo(Mode mode, ByteBuffer buffer) {
this.buffer = buffer;
this.in = new PairingDataInput(new ByteBufferDataInput(buffer));
this.out = new PairingDataOutput(new ByteBufferDataOutput(buffer));
switch (mode) {
case INIT:
try {
out.writeInt(numRecords);
} catch (Exception e) {
throw new RuntimeException(e);
}
break;
case READ:
break;
default:
throw new IllegalStateException("Invalid mode!");
}
return this;
}
public synchronized BigInteger getAt(int index) {
try {
buffer.position(offset + (index * recordLength));
return in.readBigInteger();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public synchronized void setAt(int index, BigInteger value) {
try {
buffer.position(offset + (index * recordLength));
out.writeBigInteger(value, recordSize);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public BigInteger getAt(String label) {
if (labelsMap == null)
throw new IllegalStateException();
return getAt(labelsMap.get(label));
}
public void setAt(String label, BigInteger value) {
if (labelsMap == null)
throw new IllegalStateException();
setAt(labelsMap.get(label), value);
}
}
| 3,209 | 27.660714 | 113 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/ByteBufferLatchSoftRefBigIntegerArraySector.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
import it.unisa.dia.gas.plaf.jpbc.util.collection.FlagMap;
import java.io.IOException;
import java.math.BigInteger;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ByteBufferLatchSoftRefBigIntegerArraySector extends ByteBufferSoftRefBigIntegerArraySector {
protected FlagMap<Integer> flags;
public ByteBufferLatchSoftRefBigIntegerArraySector(int recordSize, int numRecords) throws IOException {
super(recordSize, numRecords);
this.flags = new FlagMap<Integer>();
}
public ByteBufferLatchSoftRefBigIntegerArraySector(int recordSize, int numRecords, String... labels) throws IOException {
super(recordSize, numRecords, labels);
this.flags = new FlagMap<Integer>();
}
public BigInteger getAt(int index) {
flags.get(index);
return super.getAt(index);
}
public void setAt(int index, BigInteger value) {
super.setAt(index, value);
flags.set(index);
}
}
| 1,046 | 23.348837 | 125 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/ByteBufferSoftRefBigIntegerArraySector.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public class ByteBufferSoftRefBigIntegerArraySector extends ByteBufferBigIntegerArraySector {
protected Map<Integer, SoftReference<BigInteger>> cache;
public ByteBufferSoftRefBigIntegerArraySector(int recordSize, int numRecords) throws IOException {
super(recordSize, numRecords);
this.cache = new ConcurrentHashMap<Integer, SoftReference<BigInteger>>();
}
public ByteBufferSoftRefBigIntegerArraySector(int recordSize, int numRecords, String... labels) throws IOException {
super(recordSize, numRecords, labels);
this.cache = new ConcurrentHashMap<Integer, SoftReference<BigInteger>>();
}
public synchronized BigInteger getAt(int index) {
BigInteger result = null;
SoftReference<BigInteger> sr = cache.get(index);
if (sr != null)
result = sr.get();
if (result == null) {
result = super.getAt(index);
cache.put(index, new SoftReference<BigInteger>(result));
}
return result;
}
public synchronized void setAt(int index, BigInteger value) {
cache.put(index, new SoftReference<BigInteger>(value));
super.setAt(index, value);
}
}
| 1,490 | 27.132075 | 120 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/Disk.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 1.0.0
*/
public interface Disk<S extends Sector> {
S getSectorAt(int index);
S getSector(String key);
void flush();
}
| 244 | 15.333333 | 48 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/FileChannelDisk.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 1.0.0
*/
public class FileChannelDisk<S extends Sector> implements Disk<S> {
protected List<Sector> sectors;
protected Map<String, Sector> sectorsMap;
protected FileChannel channel;
public FileChannelDisk() {
this.sectors = new ArrayList<Sector>();
this.sectorsMap = new HashMap<String, Sector>();
}
public S getSectorAt(int index) {
return (S) sectors.get(index);
}
public S getSector(String key) {
return (S) sectorsMap.get(key);
}
public void flush() {
if (channel != null)
try {
channel.force(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public FileChannelDisk<S> mapTo(FileChannel channel) {
try {
this.channel = channel;
int channelCursor = 0;
for (Sector sector : sectors) {
channelCursor += sector.mapTo(
Sector.Mode.READ,
channel.map(FileChannel.MapMode.READ_ONLY, channelCursor, sector.getLengthInBytes())
).getLengthInBytes();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public FileChannelDisk<S> mapTo(String filePath) {
int size = 0;
for (Sector sector : sectors) {
size += sector.getLengthInBytes();
}
try {
RandomAccessFile f = new RandomAccessFile(filePath, "rw");
f.setLength(size);
channel = f.getChannel();
int channelCursor = 0;
for (Sector sector : sectors) {
channelCursor += sector.mapTo(
Sector.Mode.INIT,
channel.map(FileChannel.MapMode.READ_WRITE, channelCursor, sector.getLengthInBytes())
).getLengthInBytes();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public FileChannelDisk<S> addSector(String name, S sector) {
sectors.add(sector);
if (name != null)
sectorsMap.put(name, sector);
return this;
}
}
| 2,525 | 25.3125 | 109 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/io/disk/Sector.java | package it.unisa.dia.gas.plaf.jpbc.util.io.disk;
import java.nio.ByteBuffer;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
* @since 2.0.0
*/
public interface Sector {
enum Mode {INIT, READ}
int getLengthInBytes();
Sector mapTo(Mode mode, ByteBuffer buffer);
}
| 285 | 14.052632 | 48 | java |
CP-ABE | CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/util/math/BigIntegerUtils.java | package it.unisa.dia.gas.plaf.jpbc.util.math;
import java.math.BigInteger;
import java.security.SecureRandom;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class BigIntegerUtils {
public static final BigInteger TWO = BigInteger.valueOf(2);
public static final BigInteger THREE = BigInteger.valueOf(3);
public static final BigInteger FOUR = BigInteger.valueOf(4);
public static final BigInteger FIVE = BigInteger.valueOf(5);
public static final BigInteger SIX = BigInteger.valueOf(6);
public static final BigInteger SEVEN = BigInteger.valueOf(7);
public static final BigInteger EIGHT = BigInteger.valueOf(8);
public static final BigInteger TWELVE = BigInteger.valueOf(12);
public static final BigInteger MAXINT = BigInteger.valueOf(Integer.MAX_VALUE);
public static final BigInteger ITERBETTER = ONE.shiftLeft(1024);
public static boolean isOdd(BigInteger bigInteger) {
return bigInteger.testBit(0);
}
//windowed naf form of BigInteger n, k is the window size
public static byte[] naf(BigInteger n, byte k) {
// The window NAF is at most 1 element longer than the binary
// representation of the integer n. byte can be used instead of short or
// int unless the window width is larger than 8. For larger width use
// short or int. However, a width of more than 8 is not efficient for
// m = log2(q) smaller than 2305 Bits. Note: Values for m larger than
// 1000 Bits are currently not used in practice.
byte[] wnaf = new byte[n.bitLength() + 1];
// 2^width as short and BigInteger
short pow2wB = (short) (1 << k);
BigInteger pow2wBI = BigInteger.valueOf(pow2wB);
int i = 0;
// The actual length of the WNAF
int length = 0;
// while n >= 1
while (n.signum() > 0) {
// if n is odd
if (n.testBit(0)) {
// n mod 2^width
BigInteger remainder = n.mod(pow2wBI);
// if remainder > 2^(width - 1) - 1
if (remainder.testBit(k - 1)) {
wnaf[i] = (byte) (remainder.intValue() - pow2wB);
} else {
wnaf[i] = (byte) remainder.intValue();
}
// wnaf[i] is now in [-2^(width-1), 2^(width-1)-1]
n = n.subtract(BigInteger.valueOf(wnaf[i]));
length = i;
} else {
wnaf[i] = 0;
}
// n = n/2
n = n.shiftRight(1);
i++;
}
length++;
// Reduce the WNAF array to its actual length
byte[] wnafShort = new byte[length];
System.arraycopy(wnaf, 0, wnafShort, 0, length);
return wnafShort;
}
public static int hammingWeight(byte[] bytes, int length) {
int weight = 0;
for (int i = 0; i <= length; i++) {
if (bytes[i] != 0)
weight++;
}
return weight;
}
public static BigInteger generateSolinasPrime(int bits, SecureRandom random) {
// r is picked to be a Solinas prime, that is,
// r has the form 2a +- 2b +- 1 for some integers 0 < b < a.
BigInteger r, q;
int exp2, sign1;
while (true) {
r = BigInteger.ZERO;
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
exp2 = bits - 1;
sign1 = 1;
} else {
exp2 = bits;
sign1 = -1;
}
r = r.setBit(exp2);
q = BigInteger.ZERO.setBit((random.nextInt(Integer.MAX_VALUE) % (exp2 - 1)) + 1);
if (sign1 > 0) {
r = r.add(q);
} else {
r = r.subtract(q);
}
if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
r = r.add(BigInteger.ONE);
} else {
r = r.subtract(BigInteger.ONE);
}
if (r.isProbablePrime(10))
return r;
}
}
public static BigInteger factorial(int n) {
return factorial(BigInteger.valueOf(n));
}
public static BigInteger factorial(BigInteger n) {
if (n.equals(ZERO))
return ONE;
BigInteger i = n.subtract(ONE);
while (i.compareTo(ZERO) > 0) {
n = n.multiply(i);
i = i.subtract(ONE);
}
return n;
}
/**
* Compute trace of Frobenius at q^n given trace at q
* see p.105 of Blake, Seroussi and Smart
*
* @param q
* @param trace
* @param n
* @return
*/
public static BigInteger computeTrace(BigInteger q, BigInteger trace, int n) {
int i;
BigInteger c0, c1, c2;
BigInteger t0;
c2 = TWO;
c1 = trace;
for (i = 2; i <= n; i++) {
c0 = trace.multiply(c1);
t0 = q.multiply(c2);
c0 = c0.subtract(t0);
c2 = c1;
c1 = c0;
}
return c1;
}
// Given q, t such that #E(F_q) = q - t + 1, compute #E(F_q^k).
public static BigInteger pbc_mpz_curve_order_extn(BigInteger q, BigInteger t, int k) {
BigInteger z = q.pow(k).add(BigInteger.ONE);
BigInteger tk = computeTrace(q, t, k);
z = z.subtract(tk);
return z;
}
public static boolean isDivisible(BigInteger a, BigInteger b) {
return a.remainder(b).compareTo(ZERO) == 0;
}
public static boolean isPerfectSquare(BigInteger n) {
return fullSqrt(n)[1].signum() == 0;
}
public static BigInteger sqrt(BigInteger n) {
return fullSqrt(n)[0];
}
/* Compute the integer square root of n
Precondition: n >= 0
Postcondition: Result sr has the property sr[0]^2 <= n < (sr[0] + 1)^2 and (sr[0]^2 + sr[1] = n)
*/
public static BigInteger[] fullSqrt(BigInteger n) {
if (n.compareTo(MAXINT) < 1) {
long ln = n.longValue();
long s = (long) java.lang.Math.sqrt(ln);
return new BigInteger[]{
BigInteger.valueOf(s),
BigInteger.valueOf(ln - s * s)
};
}
BigInteger[] sr = isqrtInternal(n, n.bitLength() - 1);
if (sr[1].signum() < 0) {
return new BigInteger[]{
sr[0].subtract(ONE),
sr[1].add(sr[0].shiftLeft(1)).subtract(ONE)};
}
return sr;
}
/**
* Calculate the Legendre symbol (a/p). This is defined only for p an odd positive prime,
* and for such p it's identical to the Jacobi symbol.
*
* @param a
* @param n
* @return
*/
public static int legendre(BigInteger a, BigInteger n) {
return jacobi(a, n);
}
public static int jacobi(BigInteger a, BigInteger n) {
/* Precondition: a, n >= 0; n is odd */
/* int ans = 0;
if (ZERO.equals(a))
ans = (ONE.equals(n)) ? 1 : 0;
else if (TWO.equals(a)) {
BigInteger mod = n.mod(EIGHT);
if (ONE.equals(mod) || SEVEN.equals(mod))
ans = 1;
else if (THREE.equals(mod) || FIVE.equals(mod))
ans = -1;
} else if (a.compareTo(n) >= 0)
ans = jacobi(a.mod(n), n);
else if (ZERO.equals(a.mod(TWO)))
ans = jacobi(TWO, n) * jacobi(a.divide(TWO), n);
else
ans = (THREE.equals(a.mod(FOUR)) && THREE.equals(n.mod(FOUR))) ? -jacobi(n, a) : jacobi(n, a);
return ans;*/
if (ZERO.equals(a))
return 0; // (0/n) = 0
int ans = 1;
BigInteger temp;
if (a.compareTo(ZERO) == -1) {
a = a.negate(); // (a/n) = (-a/n)*(-1/n)
if (n.mod(FOUR).equals(THREE))
ans = -ans; // (-1/n) = -1 if n = 3 ( mod 4 )
}
if (a.equals(ONE))
return ans; // (1/n) = 1
while (!ZERO.equals(a)) {
if (a.compareTo(ZERO) == -1) {
a = a.negate(); // (a/n) = (-a/n)*(-1/n)
if (n.mod(FOUR).equals(THREE))
ans = -ans; // (-1/n) = -1 if n = 3 ( mod 4 )
}
while (a.mod(TWO).equals(ZERO)) {
a = a.divide(TWO); // Property (iii)
BigInteger mod = n.mod(EIGHT);
if (mod.equals(THREE) || mod.equals(FIVE))
ans = -ans;
}
// Property (iv)
temp = a;
a = n;
n = temp;
if (a.mod(FOUR).equals(THREE) && n.mod(FOUR).equals(THREE))
ans = -ans; // Property (iv)
a = a.mod(n); // because (a/p) = (a%p / p ) and a%pi = (a%n)%pi if n % pi = 0
if (a.compareTo(n.divide(TWO)) == 1)
a = a.subtract(n);
}
if (n.equals(ONE))
return ans;
return 0;
}
public static int scanOne(BigInteger a, int startIndex) {
for (int i = startIndex, size = a.bitLength(); i < size; i++) {
if (a.testBit(i))
return i;
}
return -1;
}
public static BigInteger getRandom(BigInteger limit) {
return getRandom(limit, new SecureRandom());
}
public static BigInteger getRandom(BigInteger limit, SecureRandom random) {
BigInteger result;
do {
result = new BigInteger(limit.bitLength(), random);
} while (limit.compareTo(result) <= 0);
return result;
}
public static BigInteger getRandom(int nbBits, SecureRandom random) {
if (nbBits <= 1)
return random.nextBoolean() ? BigInteger.ZERO : BigInteger.ONE;
else
return new BigInteger(nbBits, random).subtract(BigInteger.ONE.shiftLeft(nbBits - 1));
}
/**
* Compute trace of Frobenius at q^n given trace at q.
* See p.105 of Blake, Seroussi and Smart.
*
* @param q
* @param trace
* @param n
* @return
*/
public static BigInteger traceN(BigInteger q, BigInteger trace, int n) {
BigInteger c2 = TWO;
BigInteger c1 = trace;
for (int i = 2; i <= n; i++) {
BigInteger c0 = trace.multiply(c1);
BigInteger t0 = q.multiply(c2);
c0 = c0.subtract(t0);
c2 = c1;
c1 = c0;
}
return c1;
}
/* Compute the integer square root of n or a number which is too large by one
Precondition: n >= 0 and 2^log2n <= n < 2^(log2n + 1), i.e. log2n = floor(log2(n))
Postcondition: Result sr has the property (sr[0]^2 - 1) <= n < (sr[0] + 1)^2 and (sr[0]^2 + sr[1] = n)
*/
private static BigInteger[] isqrtInternal(BigInteger n, int log2n) {
if (n.compareTo(MAXINT) < 1) {
int ln = n.intValue(), s = (int) java.lang.Math.sqrt(ln);
return new BigInteger[]{BigInteger.valueOf(s), BigInteger.valueOf(ln - s * s)};
}
if (n.compareTo(ITERBETTER) < 1) {
int d = 7 * (log2n / 14 - 1), q = 7;
BigInteger s = BigInteger.valueOf((long) java.lang.Math.sqrt(n.shiftRight(d << 1).intValue()));
while (d > 0) {
if (q > d) q = d;
s = s.shiftLeft(q);
d -= q;
q <<= 1;
s = s.add(n.shiftRight(d << 1).divide(s)).shiftRight(1);
}
return new BigInteger[]{s, n.subtract(s.multiply(s))};
}
int log2b = log2n >> 2;
BigInteger mask = ONE.shiftLeft(log2b).subtract(ONE);
BigInteger[] sr = isqrtInternal(n.shiftRight(log2b << 1), log2n - (log2b << 1));
BigInteger s = sr[0];
BigInteger[] qu = sr[1].shiftLeft(log2b).add(n.shiftRight(log2b).and(mask)).divideAndRemainder(s.shiftLeft(1));
BigInteger q = qu[0];
return new BigInteger[]{s.shiftLeft(log2b).add(q), qu[1].shiftLeft(log2b).add(n.and(mask)).subtract(q.multiply(q))};
}
public static int hammingWeight(BigInteger value) {
int weight = 0;
for (int i = 0; i <= value.bitLength(); i++) {
if (value.testBit(i))
weight++;
}
return weight;
}
public static BigInteger modNear(BigInteger a, BigInteger b) {
BigInteger res = a.mod(b);
if (res.compareTo(b.shiftRight(1)) == 1)
res = res.subtract(b);
return res;
}
public static BigInteger mod(BigInteger a, BigInteger b) {
BigInteger res = a.mod(b);
return res;
}
/**
* Divides `n` with primes up to `limit`. For each factor found,
* call `fun`. If the callback returns nonzero, then aborts and returns 1.
* Otherwise returns 0.
*/
public static abstract class TrialDivide {
protected BigInteger limit;
public TrialDivide(BigInteger limit) {
this.limit = limit;
}
public int trialDivide(BigInteger n) {
BigInteger m = n;
BigInteger p = TWO;
while (m.compareTo(BigInteger.ONE) != 0) {
if (m.isProbablePrime(10))
p = m;
if (limit != null && !limit.equals(BigInteger.ZERO) && p.compareTo(limit) > 0)
p = m;
if (isDivisible(m, p)) {
int mul = 0;
do {
m = m.divide(p);
mul++;
} while (isDivisible(m, p));
if (fun(p, mul) != 0)
return 1;
}
p = p.nextProbablePrime();
}
return 0;
}
protected abstract int fun(BigInteger factor, int multiplicity);
}
}
| 13,942 | 29.779249 | 124 | java |
CP-ABE | CP-ABE-master/src/setup/Setup.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package setup;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import java.io.ByteArrayInputStream;
import static java.lang.System.currentTimeMillis;
import java.util.ArrayList;
import java.util.Scanner;
class makesetup {
String pairingDesc;
Pairing p;
Element g;
Element h;
Element f;
Element gp;
Element g_hat_alpha;
Element beta;
Element g_alpha;
String curveParams = "type a\n"
+ "q 87807107996633125224377819847540498158068831994142082"
+ "1102865339926647563088022295707862517942266222142315585"
+ "8769582317459277713367317481324925129998224791\n"
+ "h 12016012264891146079388821366740534204802954401251311"
+ "822919615131047207289359704531102844802183906537786776\n"
+ "r 730750818665451621361119245571504901405976559617\n"
+ "exp2 159\n" + "exp1 107\n" + "sign1 1\n" + "sign0 1\n";
void setup() {
Element alpha, beta_inv;
PropertiesParameters params = new PropertiesParameters()
.load(new ByteArrayInputStream(curveParams.getBytes()));
pairingDesc = curveParams;
p= PairingFactory.getPairing(params);
Pairing pairing = p;
g = pairing.getG1().newElement();
f = pairing.getG1().newElement();
h = pairing.getG1().newElement();
gp = pairing.getG2().newElement();
g_hat_alpha = pairing.getGT().newElement();
alpha = pairing.getZr().newElement();
beta = pairing.getZr().newElement();
g_alpha = pairing.getG2().newElement();
alpha.setToRandom();
beta.setToRandom();
g.setToRandom();
System.out.println("**************Setup Function:*****************");
System.out.println("Element of group G1:");
System.out.println("The value of g is :");
System.out.println(g);
gp.setToRandom();
g_alpha = gp.duplicate();
g_alpha.powZn(alpha);
System.out.println("g to the power alpha");
System.out.println(g_alpha);
beta_inv = beta.duplicate();
beta_inv.invert();
f = g.duplicate();
f.powZn(beta_inv);
System.out.println("g to the power beta inverse");
System.out.println(f);
h = g.duplicate();
h.powZn(beta);
System.out.println("g to the power beta");
System.out.println(h);
g_hat_alpha = pairing.pairing(g,g_alpha);
System.out.println("billenear map of g and g alpha");
System.out.println("Element of group GT:");
System.out.println(g_hat_alpha);
}
}
class user
{
String attr;
Element a;
Element b;
}
class keygen
{
Element d;
ArrayList<user>comps=new ArrayList<user>();
void secretkey(makesetup ms)
{
Pairing pair;
pair=ms.p;
d=pair.getG2().newElement();
d=ms.g_alpha.duplicate();
Element r;
r=pair.getZr().newElement();
r.setToRandom();
Element gr;
gr=pair.getG2().newElement();
gr=ms.gp.duplicate();
gr.powZn(r);
d.mul(gr);
Element bi;
bi=pair.getZr().newElement();
bi=ms.beta.duplicate();
bi.invert();
d.powZn(bi);
System.out.println("**************************Key Generation Function***********************");
System.out.println("The value of d that is g to the power (alpha + r)/ beta is");
System.out.println(d);
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of attributes of user");
int n=sc.nextInt();
sc.nextLine();
String[] attributes=new String[n];
int i;
System.out.println("enter the attributes");
for(i=0;i<n;i++)
{
attributes[i]=sc.nextLine();
}
System.out.println("the attributes are :");
for(i=0;i<n;i++)
{
System.out.println(attributes[i]);
}
System.out.println("FOR EVERY ATTRIBUTE ");
for(i=0;i<n;i++)
{
user u=new user();
u.attr=attributes[i];
Element rp;
rp=pair.getZr().newElement();
rp.setToRandom();
u.a=pair.getG2().newElement();
u.b=pair.getG1().newElement();
u.a=gr.duplicate();
Element h;
h=pair.getG2().newElement();
h.powZn(rp);
u.a.mul(h);
u.b=ms.g.duplicate();
u.b.powZn(rp);
comps.add(u);
System.out.println(u.a);
System.out.println(u.b);
}
}
}
class polynomial
{
int degree;
Element[]coef;
}
class policy
{
String attr;
int k;
policy[]child;
Element c1 ;
Element c2;
polynomial q;
boolean satisfy=false;
}
class cyphertext
{
Element c;
Element cs;
policy p;
Element[]ctext;
Integer []ct;
Element generate_ct(makesetup o)
{
Element s;
Pairing pa=o.p;
s=pa.getZr().newElement();
c=pa.getG1().newElement();
cs=pa.getGT().newElement();
s.setToRandom();
c=o.h.duplicate();
c.powZn(s);
System.out.println("**************************ENCRYPTION******************************");
System.out.println("value of s is");
System.out.println(s);
System.out.println("value of c to the power s is");
System.out.println(c);
String message="abcdef";
Scanner sc=new Scanner(System.in);
int l=message.length();
ct=new Integer[l];
int i;
for(i=0;i<l;i++)
{
ct[i]=(int)message.charAt(i);
}
cs=o.g_hat_alpha.duplicate();
cs.powZn(s);
System.out.println("value of cs to the power s is");
System.out.println(cs);
ctext=new Element[l];
for(i=0;i<l;i++)
{
ctext[i]=cs.mul(ct[i]);
}
System.out.println("elements of element array");
for(i=0;i<l;i++)
{
System.out.println(ctext[i]);
}
return s;
}
policy access_structure(String cypher_policy)
{
String[] toks;
String tok;
ArrayList<policy>stack=new ArrayList<>();
toks=cypher_policy.split(" ");
int index;
index = toks.length;
int i;
for(i=0;i<index;i++)
{
int k,n;
tok=toks[i];
if(!tok.contains("of"))
{
policy node=new policy();
node.attr=tok;
node.k=1;
stack.add(node);
}
else
{
String[]again=tok.split("of");
k=Integer.parseInt(again[0]);
n=Integer.parseInt(again[1]);
policy node2=new policy();
node2.attr=null;
node2.k=k;
node2.child=new policy[n];
int it;
for(it=n-1;it>=0;it--)
{
node2.child[it]=new policy();
node2.child[it]=stack.remove(stack.size()-1);
}
stack.add(node2);
}
}
p=stack.get(0);
return p;
}
void fillPolicy(policy p,makesetup m,Element e)
{
int i;
Element r, t, h;
Pairing pairing = m.p;
r = pairing.getZr().newElement();
t = pairing.getZr().newElement();
h = pairing.getG2().newElement();
h=m.h.duplicate();
p.q = randPoly(p.k - 1, e);
if (p.child == null || p.child.length == 0) {
p.c1 = pairing.getG1().newElement();
p.c2 = pairing.getG2().newElement();
p.c1 = m.g.duplicate();;
p.c1.powZn(p.q.coef[0]);
p.c2 = h.duplicate();
p.c2.powZn(p.q.coef[0]);
} else {
for (i = 0; i < p.child.length; i++) {
r.set(i + 1);
evalPoly(t, p.q, r);
fillPolicy(p.child[i], m, t);
}
}
}
void evalPoly(Element r, polynomial q, Element x) {
int i;
Element s, t;
s = r.duplicate();
t = r.duplicate();
r.setToZero();
t.setToOne();
for (i = 0; i < q.degree + 1; i++) {
s = q.coef[i].duplicate();
s.mul(t);
r.add(s);
t.mul(x);
}
}
polynomial randPoly(int deg, Element zeroVal) {
int i;
polynomial q = new polynomial();
q.degree = deg;
q.coef = new Element[deg + 1];
for (i = 0; i < deg + 1; i++)
q.coef[i] = zeroVal.duplicate();
q.coef[0].set(zeroVal);
for (i = 1; i < deg + 1; i++)
q.coef[i].setToRandom();
return q;
}
}
class dec
{
void decrypt(keygen sk,policy p)
{
if(p.attr!=null)
{
int i=0;
String at;
at=p.attr;
for(i=0;i<sk.comps.size();i++)
{
if(at.compareTo(sk.comps.get(i).attr)==0)
{
p.satisfy=true;
return;
}
}
}
else
{
int i;
for(i=0;i<p.child.length;i++)
{
decrypt(sk,p.child[i]);
}
}
}
boolean check(policy p)
{
int count=0;
int i;
for(i=0;i<p.child.length;i++)
{
if(p.child[i].satisfy==true)
{
count++;
}
}
System.out.println(count);
if(count>=p.k)
{
System.out.println("ACCESS GRANTED");
return true;
}
else
{
System.out.println("ACCESS DENIED");
return false;
}
}
void getvalue(cyphertext t,keygen k,makesetup pub)
{
System.out.println("Working on fetching the decrypted value");
System.out.println("The value of g to the power (alpha + r)/ beta is");
System.out.println(k.d);
System.out.println("The billenear map of h to the power s and g to the power (alpha + r)/ beta");
Pairing pair;
pair=pub.p;
Element r1=pair.getG1().newElement();
r1=k.d.duplicate();
Element r2=pair.getG1().newElement();
r2=t.c.duplicate();
Element r3=pair.getGT().newElement();
r3=pair.pairing(r1, r2);
System.out.println(r3);
System.out.println("divide the above obtained value with cs of cyphertext");
r3.div(t.cs);
System.out.println(r3);
System.out.println("Hospital Recoards");
}
}
/**
*
* @author rajat
*/
public class Setup {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
makesetup ob=new makesetup();
long time1;
time1=System.currentTimeMillis();
ob.setup();
long time2=System.currentTimeMillis();
System.out.println("time for setup in milli seconds");
System.out.println(time2-time1);
policy root;
keygen key=new keygen();
long keygentime1;
keygentime1 =System.currentTimeMillis();
key.secretkey(ob);
long keygentime2;
keygentime2 =System.currentTimeMillis();
System.out.println("time for key generation in milli seconds");
System.out.println(keygentime2-keygentime1);
cyphertext text=new cyphertext();
long enc1=System.currentTimeMillis();
Element s_p=text.generate_ct(ob);
long enc12=System.currentTimeMillis();
System.out.println(s_p);
Scanner sc=new Scanner(System.in);
System.out.println("enter the cypher policy");
String s=sc.nextLine();
long enc2=System.currentTimeMillis();
text.p=text.access_structure(s);
System.out.println(text.p.k);
long enc22=System.currentTimeMillis();
long enc3=System.currentTimeMillis();
text.fillPolicy(text.p, ob, s_p);
long enc32=System.currentTimeMillis();
int i;
System.out.println("time for encryption");
System.out.println((enc12-enc1)+(enc22-enc2)+(enc32-enc3));
dec d1=new dec();
long dect=System.currentTimeMillis();
d1.decrypt(key,text.p);
boolean x;
x=d1.check(text.p);
if(x)
{
d1.getvalue(text,key,ob);
}
long fdect=System.currentTimeMillis();
System.out.println("time for decryption");
System.out.println(fdect-dect);
}
}
| 13,657 | 23.389286 | 106 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/cpabeDataGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class cpabeDataGUI {
private JFrame jframe;
private JButton btnEncrypt, btnDecrypt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
cpabeDataGUI window = new cpabeDataGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public cpabeDataGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI for Data Protection");
jframe.setBounds(100, 100, 450, 280);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
btnEncrypt = new JButton("ENCRYPT");
btnEncrypt.setBounds(40, 100, 165, 100);
jframe.getContentPane().add(btnEncrypt);
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
encGUI encrypt = new encGUI();
encrypt.show();
}
});
btnDecrypt = new JButton("DECRYPT");
btnDecrypt.setBounds(245, 100, 165, 100);
jframe.getContentPane().add(btnDecrypt);
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
decGUI decrypt = new decGUI();
decrypt.show();
}
});
}
}
| 2,133 | 25.675 | 94 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/cpabeGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class cpabeGUI {
private JFrame jframe;
private JButton btnSetup, btnKeygen, btnEncrypt, btnDecrypt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
cpabeGUI window = new cpabeGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public cpabeGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() { //private
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI (FULL FUNCTION)");
jframe.setBounds(100, 100, 450, 300);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
btnSetup = new JButton("SETUP");
btnSetup.setBounds(40, 100, 180, 65);
jframe.getContentPane().add(btnSetup);
btnSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setupGUI setup = new setupGUI();
setup.show();
}
});
btnKeygen = new JButton("KEYGEN");
btnKeygen.setBounds(230, 100, 180, 65);
jframe.getContentPane().add(btnKeygen);
btnKeygen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
keygenGUI keygen = new keygenGUI();
keygen.show();
}
});
btnEncrypt = new JButton("ENCRYPT");
btnEncrypt.setBounds(40, 175, 180, 65);
jframe.getContentPane().add(btnEncrypt);
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
encGUI encrypt = new encGUI();
encrypt.show();
}
});
btnDecrypt = new JButton("DECRYPT");
btnDecrypt.setBounds(230, 175, 180, 65);
jframe.getContentPane().add(btnDecrypt);
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
decGUI decrypt = new decGUI();
decrypt.show();
}
});
}
}
| 2,742 | 26.707071 | 94 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/cpabeJNI.java | package tw.edu.au.csie.ucan.beebit;
public class cpabeJNI {
public native int setup(String pk_path, String mk_path);
public native int keygen(String pk_path, String mk_path, String sk_path, int attr_no, String... params);
public native int vkeygen(String pk_path, String mk_path, String sk_path, int attr_no, String[] params);
public native byte[] enc(String pk_path, byte[] pt, String pllicy_str);
public native byte[] dec(String pk_path, String sk_path, byte[] ct);
public native int fenc(String pk_path, String pt_path, String policy_str, String ct_path);
public native int fdec(String pk_path, String sk_path, String ct_path);
static { System.loadLibrary("beebit-cpabe"); };
}
| 692 | 48.5 | 105 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/cpabeKeyGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class cpabeKeyGUI {
private JFrame jframe;
private JButton btnSetup, btnKeygen;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
cpabeKeyGUI window = new cpabeKeyGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public cpabeKeyGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI for Key Management");
jframe.setBounds(100, 100, 450, 280);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
btnSetup = new JButton("SETUP");
btnSetup.setBounds(40, 100, 165, 100);
jframe.getContentPane().add(btnSetup);
btnSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setupGUI setup = new setupGUI();
setup.show();
}
});
btnKeygen = new JButton("KEYGEN");
btnKeygen.setBounds(245, 100, 165, 100);
jframe.getContentPane().add(btnKeygen);
btnKeygen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
keygenGUI keygen = new keygenGUI();
keygen.show();
}
});
}
}
| 2,014 | 24.506329 | 80 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/decGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class decGUI {
private JFrame jframe;
private JLabel labPKey, labFile, labSKey;
private JTextField txtPKey, txtFile, txtSKey;
private JButton btnDecrypt, btnExit, btnSelectPKey, btnSelectFile, btnSelectSKey;
private JFileChooser fChooser;
/**
* Launch the application.
*/
public static void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
decGUI window = new decGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public decGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI (DECRYPTION)");
jframe.getContentPane().setForeground(Color.PINK);
jframe.setBounds(100, 100, 450, 470);
jframe.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
// Public Key Area
labPKey = new JLabel("Public Key:");
labPKey.setBounds(40, 100, 150, 20);
jframe.getContentPane().add(labPKey);
txtPKey = new JTextField("Select Public Key ...");
txtPKey.setBounds(150, 100, 260, 20);
jframe.getContentPane().add(txtPKey);
btnSelectPKey = new JButton("Select ...");
btnSelectPKey.setBounds(40, 120, 100, 20);
jframe.getContentPane().add(btnSelectPKey);
btnSelectPKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtPKey.setText(selectedPath.getAbsolutePath());
}
}
});
// Secrect Key Area
labSKey = new JLabel("Secrect Key:");
labSKey.setBounds(40, 150, 150, 20);
jframe.getContentPane().add(labSKey);
txtSKey = new JTextField("Select Secrect Key ...");
txtSKey.setBounds(150, 150, 260, 20);
jframe.getContentPane().add(txtSKey);
btnSelectSKey = new JButton("Select ...");
btnSelectSKey.setBounds(40, 170, 100, 20);
jframe.getContentPane().add(btnSelectSKey);
btnSelectSKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtSKey.setText(selectedPath.getAbsolutePath());
}
}
});
// File Area
labFile = new JLabel("Target File:");
labFile.setBounds(40, 200, 150, 20);
jframe.getContentPane().add(labFile);
txtFile = new JTextField("Select Target File ...");
txtFile.setBounds(150, 200, 260, 20);
jframe.getContentPane().add(txtFile);
btnSelectFile = new JButton("Select ...");
btnSelectFile.setBounds(40, 220, 100, 20);
jframe.getContentPane().add(btnSelectFile);
btnSelectFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtFile.setText(selectedPath.getAbsolutePath());
}
}
});
btnDecrypt = new JButton("DECRYPT");
btnDecrypt.setBounds(40, 300, 180, 90);
jframe.getContentPane().add(btnDecrypt);
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cpabeJNI beebit = new cpabeJNI();
String pkey = txtPKey.getText();
String skey = txtSKey.getText();
String file = txtFile.getText();
int len = beebit.fdec(pkey, skey, file);
if(len == -1)
{
JOptionPane.showMessageDialog(null,"DEC FAILED(JNI) \n");
} else {
JOptionPane.showMessageDialog(null,"DEC SUCCESS(JNI) \n");
}
}});
btnExit = new JButton("EXIT");
btnExit.setBounds(230, 300, 180, 90);
jframe.getContentPane().add(btnExit);
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe.dispose();
}
});
}
}
| 6,010 | 36.56875 | 94 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/encGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class encGUI {
private JFrame jframe;
private JLabel labKey, labFile, labPolicy;
private JTextField txtKey, txtFile, txtPolicy;
private JButton btnEncrypt, btnExit, btnSelectKey, btnSelectFile, btnEditPolicy;
private JFileChooser fChooser;
/**
* Launch the application.
*/
public static void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
encGUI window = new encGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public encGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI (ENCRYPTION)");
jframe.getContentPane().setForeground(Color.PINK);
jframe.setBounds(100, 100, 450, 470);
jframe.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
// Public Key Area
labKey = new JLabel("Public Key:");
labKey.setBounds(40, 100, 150, 20);
jframe.getContentPane().add(labKey);
txtKey = new JTextField("Select Public Key ...");
txtKey.setBounds(150, 100, 260, 20);
jframe.getContentPane().add(txtKey);
btnSelectKey = new JButton("Select ...");
btnSelectKey.setBounds(40, 120, 100, 20);
jframe.getContentPane().add(btnSelectKey);
btnSelectKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtKey.setText(selectedPath.getAbsolutePath());
}
}
});
// Plaintext File Area
labFile = new JLabel("Target File:");
labFile.setBounds(40, 150, 150, 20);
jframe.getContentPane().add(labFile);
txtFile = new JTextField("Select Target File ...");
txtFile.setBounds(150, 150, 260, 20);
jframe.getContentPane().add(txtFile);
btnSelectFile = new JButton("Select ...");
btnSelectFile.setBounds(40, 170, 100, 20);
jframe.getContentPane().add(btnSelectFile);
btnSelectFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtFile.setText(selectedPath.getAbsolutePath());
}
}
});
// Policy Area
labPolicy = new JLabel("Policy:");
labPolicy.setBounds(40, 200, 150, 20);
jframe.getContentPane().add(labPolicy);
txtPolicy = new JTextField("Edit Policy ...");
txtPolicy.setBounds(150, 200, 260, 20);
jframe.getContentPane().add(txtPolicy);
btnEncrypt = new JButton("ENCRYPT");
btnEncrypt.setBounds(40, 300, 180, 90);
jframe.getContentPane().add(btnEncrypt);
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cpabeJNI beebit = new cpabeJNI();
String key = txtKey.getText();
String file = txtFile.getText();
String policy = txtPolicy.getText();
int len = beebit.fenc(key, file, policy, "default");
if(len == -1)
{
JOptionPane.showMessageDialog(null,"ENC FAILED(JNI) \n");
} else {
JOptionPane.showMessageDialog(null,"ENC SUCCESS(JNI) \n");
}
}});
// EXIT
btnExit = new JButton("EXIT");
btnExit.setBounds(230, 300, 180, 90);
jframe.getContentPane().add(btnExit);
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe.dispose();
}
});
}
}
| 5,219 | 34.27027 | 94 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/keygenGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class keygenGUI {
private JFrame jframe;
private JLabel labPKey, labMKey, labSKeyPath, labCSV;
private JTextField txtPKey, txtMKey, txtSKeyPath, txtCSV;
private JButton btnSelectPKey, btnSelectMKey, btnSelectSKeyPath, btnSelectCSV;
private JButton btnEditCSV, btnKeygen, btnExit;
private JFileChooser fChooser;
/**
* Launch the application.
*/
public static void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
keygenGUI window = new keygenGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public keygenGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI (KEYGEN)");
jframe.getContentPane().setForeground(Color.PINK);
jframe.setBounds(100, 100, 450, 470);
jframe.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
// Public Key Area
labPKey = new JLabel("Public Key:");
labPKey.setBounds(40, 100, 150, 20);
jframe.getContentPane().add(labPKey);
txtPKey = new JTextField("Select Public Key ...");
txtPKey.setBounds(150, 100, 260, 20);
jframe.getContentPane().add(txtPKey);
btnSelectPKey = new JButton("Select ...");
btnSelectPKey.setBounds(40, 120, 100, 20);
jframe.getContentPane().add(btnSelectPKey);
btnSelectPKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtPKey.setText(selectedPath.getAbsolutePath());
}
}
});
// Master Key Area
labMKey = new JLabel("Master Key:");
labMKey.setBounds(40, 150, 150, 20);
jframe.getContentPane().add(labMKey);
txtMKey = new JTextField("Select Master Key ...");
txtMKey.setBounds(150, 150, 260, 20);
jframe.getContentPane().add(txtMKey);
btnSelectMKey = new JButton("Select ...");
btnSelectMKey.setBounds(40, 170, 100, 20);
jframe.getContentPane().add(btnSelectMKey);
btnSelectMKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtMKey.setText(selectedPath.getAbsolutePath());
}
}
});
// Secrect Key Area
labSKeyPath = new JLabel("Secrect Key:");
labSKeyPath.setBounds(40, 200, 150, 20);
jframe.getContentPane().add(labSKeyPath);
txtSKeyPath = new JTextField("Select Secrect Key Path ...");
txtSKeyPath.setBounds(150, 200, 260, 20);
jframe.getContentPane().add(txtSKeyPath);
btnSelectSKeyPath = new JButton("Select ...");
btnSelectSKeyPath.setBounds(40, 220, 100, 20);
jframe.getContentPane().add(btnSelectSKeyPath);
btnSelectSKeyPath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
fChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtSKeyPath.setText(selectedPath.getAbsolutePath());
}
}
});
// CSV Area
labCSV = new JLabel("CSV File:");
labCSV.setBounds(40, 250, 150, 20);
jframe.getContentPane().add(labCSV);
txtCSV = new JTextField("Select CSV File ...");
txtCSV.setBounds(150, 250, 260, 20);
jframe.getContentPane().add(txtCSV);
btnSelectCSV = new JButton("Select ...");
btnSelectCSV.setBounds(40, 270, 100, 20);
jframe.getContentPane().add(btnSelectCSV);
btnSelectCSV.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fChooser = new JFileChooser();
int returnValue = fChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fChooser.getSelectedFile();
txtCSV.setText(selectedPath.getAbsolutePath());
}
}
});
// TODO: Number of attributes is limited to 6 now.
btnKeygen = new JButton("KEYGEN");
btnKeygen.setBounds(165, 300, 120, 90);
jframe.getContentPane().add(btnKeygen);
btnKeygen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileReader fr =null;
BufferedReader br =null;
String tempString="";
String[] tempArray;
String[][] score;
String[] name=new String[10];
try{
int i;
fr= new FileReader(txtCSV.getText());
br = new BufferedReader(fr);
String data;
while ((data = br.readLine()) != null){
tempString = data;
tempArray = tempString.split(",");
for(i = 0 ; i < tempArray.length ; i++){
name[i] = tempArray[i];
}
System.out.print("\n");
score=new String[][]{{name[0]}};
for(String [] y: score){
String pk = txtPKey.getText();
String mk = txtMKey.getText();
String skp = txtSKeyPath.getText();
cpabeJNI beebit = new cpabeJNI();
if(beebit.keygen(pk, mk, String.format("%s/secKey_%s",skp, name[0]),3,name[0],name[1],name[2],name[3],name[4],name[5],name[6]) == -1)
{
JOptionPane.showMessageDialog(null,name[0]+" "+"KEYGEN FAILED(JNI)\n");
} else {
JOptionPane.showMessageDialog(null,name[0]+" "+"KEYGEN SUCCESS(JNI)\n");
}
}
}
System.out.println();
}catch(IOException h){
}
finally{
try{
br.close();
fr.close();
} catch(IOException g){
}
}
}});
btnEditCSV = new JButton("EDIT CSV");
btnEditCSV.setBounds(40, 300, 120, 90);
jframe.getContentPane().add(btnEditCSV);
btnEditCSV.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Desktop.getDesktop().open(new java.io.File(txtCSV.getText()));
}
catch(Exception ioe){
ioe.printStackTrace();
}
}
});
btnExit = new JButton("EXIT");
btnExit.setBounds(290, 300, 120, 90);
jframe.getContentPane().add(btnExit);
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe.dispose();
}
});
}
}
| 8,653 | 35.514768 | 141 | java |
beebit-cpabe-gui | beebit-cpabe-gui-master/tw/edu/au/csie/ucan/beebit/setupGUI.java | package tw.edu.au.csie.ucan.beebit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class setupGUI {
private JFrame jframe;
private JLabel labProject, labPath;
private JTextField txtProject, txtPath;
private JFileChooser fpChooser;
private JButton btnSelect, btnSetup, btnExit;
/**
* Launch the application.
*/
/*public static void main(String[] args) { */
public static void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
setupGUI window = new setupGUI();
window.jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public setupGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
jframe = new JFrame();
jframe.setResizable(false);
jframe.setTitle("Beebit CPABE GUI (SETUP)");
jframe.getContentPane().setForeground(Color.PINK);
jframe.setBounds(100, 100, 450, 300); // (x, y, width, height)
jframe.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jframe.getContentPane().setLayout(null);
// TITLE (TEMP) Will be replaced by image
JLabel labTitle = new JLabel("Beebit CPABE", SwingConstants.CENTER);
labTitle.setBounds(40, 10, 370, 40);
labTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labTitle);
JLabel labSubTitle = new JLabel("UCAN.CSIE.AU.EDU.TW", SwingConstants.CENTER);
labSubTitle.setBounds(40, 50, 370, 40);
labSubTitle.setFont(new Font("Serif", Font.BOLD, 20));
jframe.getContentPane().add(labSubTitle);
// Project Name Area
labProject = new JLabel("Project Name: ");
labProject.setBounds(40, 100, 150, 20);
jframe.getContentPane().add(labProject);
txtProject = new JTextField("demo");
txtProject.setBounds(150, 100, 260, 20);
jframe.getContentPane().add(txtProject);
// Key Path Area
labPath = new JLabel("Key Path: ");
labPath.setBounds(40, 130, 150, 20);
jframe.getContentPane().add(labPath);
txtPath = new JTextField(".");
txtPath.setBounds(150, 130, 260, 20);
jframe.getContentPane().add(txtPath);
btnSelect = new JButton("Select");
btnSelect.setBounds(40, 150, 100, 20);
jframe.getContentPane().add(btnSelect);
btnSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fpChooser = new JFileChooser();
fpChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnValue = fpChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION) {
File selectedPath = fpChooser.getSelectedFile();
txtPath.setText(selectedPath.getAbsolutePath());
}
}
});
// SETUP
btnSetup = new JButton("SETUP");
btnSetup.setBounds(40, 180, 175, 50);
jframe.getContentPane().add(btnSetup);
btnSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cpabeJNI beebit = new cpabeJNI();
String name = txtProject.getText();
String path = txtPath.getText();
if(beebit.setup(
String.format("%s/%s_pubKey",path,name),
String.format("%s/%s_mstKey",path,name)) == -1){
JOptionPane.showMessageDialog(null,"SETUP FAILED (JNI)\n");
} else {
JOptionPane.showMessageDialog(null,"SETUP SUCCESS(JNI)\n");
}
}});
// EXIT
btnExit = new JButton("EXIT");
btnExit.setBounds(235, 180, 175, 50);
jframe.getContentPane().add(btnExit);
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe.dispose();
}
});
}
}
| 3,790 | 28.850394 | 94 | java |
null | tesseract-main/java/com/google/scrollview/ScrollView.java | // Copyright 2007 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); You may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
// applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
package com.google.scrollview;
import com.google.scrollview.events.SVEvent;
import com.google.scrollview.ui.SVImageHandler;
import com.google.scrollview.ui.SVWindow;
import org.piccolo2d.nodes.PImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* The ScrollView class is the main class which gets started from the command
* line. It sets up LUA and handles the network processing.
* @author wanke@google.com
*/
public class ScrollView {
/** The port our server listens at. */
public static int SERVER_PORT = 8461;
/**
* All SVWindow objects share the same connection stream. The socket is needed
* to detect when the connection got closed, in/out are used to send and
* receive messages.
*/
private static Socket socket;
private static PrintStream out;
public static BufferedReader in;
public static float polylineXCoords[]; // The coords being received.
public static float polylineYCoords[]; // The coords being received.
public static int polylineSize; // The size of the coords arrays.
public static int polylineScanned; // The size read so far.
private static ArrayList<SVWindow> windows; // The id to SVWindow map.
private static Pattern intPattern; // For checking integer arguments.
private static Pattern floatPattern; // For checking float arguments.
/** Keeps track of the number of messages received. */
static int nrInputLines = 0;
/** Prints all received messages to the console if true. */
static boolean debugViewNetworkTraffic = false;
/** Add a new message to the outgoing queue */
public static void addMessage(SVEvent e) {
if (debugViewNetworkTraffic) {
System.out.println("(S->c) " + e.toString());
}
String str = e.toString();
// Send the whole thing as UTF8.
try {
byte [] utf8 = str.getBytes("UTF8");
out.write(utf8, 0, utf8.length);
} catch (java.io.UnsupportedEncodingException ex) {
System.out.println("Oops... can't encode to UTF8... Exiting");
System.exit(0);
}
out.println();
// Flush the output and check for errors.
boolean error = out.checkError();
if (error) {
System.out.println("Connection error. Quitting ScrollView Server...");
System.exit(0);
}
}
/** Read one message from client (assuming there are any). */
public static String receiveMessage() throws IOException {
return in.readLine();
}
/**
* The main program loop. Basically loops through receiving messages and
* processing them and then sending messages (if there are any).
*/
private static void IOLoop() {
String inputLine;
try {
while (!socket.isClosed() && !socket.isInputShutdown() &&
!socket.isOutputShutdown() &&
socket.isConnected() && socket.isBound()) {
inputLine = receiveMessage();
if (inputLine == null) {
// End of stream reached.
break;
}
nrInputLines++;
if (debugViewNetworkTraffic) {
System.out.println("(c->S," + nrInputLines + ")" + inputLine);
}
if (polylineSize > polylineScanned) {
// We are processing a polyline.
// Read pairs of coordinates separated by commas.
boolean first = true;
for (String coordStr : inputLine.split(",")) {
int coord = Integer.parseInt(coordStr);
if (first) {
polylineXCoords[polylineScanned] = coord;
} else {
polylineYCoords[polylineScanned++] = coord;
}
first = !first;
}
assert first;
} else {
// Process this normally.
processInput(inputLine);
}
}
}
// Some connection error
catch (IOException e) {
System.out.println("Connection error. Quitting ScrollView Server...");
}
System.exit(0);
}
// Parse a comma-separated list of arguments into ArrayLists of the
// possible types. Each type is stored in order, but the order
// distinction between types is lost.
// Note that the format is highly constrained to what the client used
// to send to LUA:
// Quoted string -> String.
// true or false -> Boolean.
// %f format number -> Float (no %e allowed)
// Sequence of digits -> Integer
// Nothing else allowed.
private static void parseArguments(String argList,
ArrayList<Integer> intList,
ArrayList<Float> floatList,
ArrayList<String> stringList,
ArrayList<Boolean> boolList) {
// str is only non-null if an argument starts with a single or double
// quote. str is set back to null on completion of the string with a
// matching quote. If the string contains a comma then str will stay
// non-null across multiple argStr values until a matching closing quote.
// Backslash escaped quotes do not count as terminating the string.
String str = null;
for (String argStr : argList.split(",")) {
if (str != null) {
// Last string was incomplete. Append argStr to it and restore comma.
// Execute str += "," + argStr in Java.
int length = str.length() + 1 + argStr.length();
StringBuilder appended = new StringBuilder(length);
appended.append(str);
appended.append(",");
appended.append(argStr);
str = appended.toString();
} else if (argStr.length() == 0) {
continue;
} else {
char quote = argStr.charAt(0);
// If it begins with a quote then it is a string, but may not
// end this time if it contained a comma.
if (quote == '\'' || quote == '"') {
str = argStr;
}
}
if (str != null) {
// It began with a quote. Check that it still does.
assert str.charAt(0) == '\'' || str.charAt(0) == '"';
int len = str.length();
if (len > 1 && str.charAt(len - 1) == str.charAt(0)) {
// We have an ending quote of the right type. Now check that
// it is not escaped. Must have an even number of slashes before.
int slash = len - 1;
while (slash > 0 && str.charAt(slash - 1) == '\\')
--slash;
if ((len - 1 - slash) % 2 == 0) {
// It is now complete. Chop off the quotes and save.
// TODO(rays) remove the first backslash of each pair.
stringList.add(str.substring(1, len - 1));
str = null;
}
}
// If str is not null here, then we have a string with a comma in it.
// Append , and the next argument at the next iteration, but check
// that str is null after the loop terminates in case it was an
// unterminated string.
} else if (floatPattern.matcher(argStr).matches()) {
// It is a float.
floatList.add(Float.parseFloat(argStr));
} else if (argStr.equals("true")) {
boolList.add(true);
} else if (argStr.equals("false")) {
boolList.add(false);
} else if (intPattern.matcher(argStr).matches()) {
// Only contains digits so must be an int.
intList.add(Integer.parseInt(argStr));
}
// else ignore all incompatible arguments for forward compatibility.
}
// All strings must have been terminated.
assert str == null;
}
/** Executes the LUA command parsed as parameter. */
private static void processInput(String inputLine) {
if (inputLine == null) {
return;
}
// Execute a function encoded as a LUA statement! Yuk!
if (inputLine.charAt(0) == 'w') {
// This is a method call on a window. Parse it.
String noWLine = inputLine.substring(1);
String[] idStrs = noWLine.split("[ :]", 2);
int windowID = Integer.parseInt(idStrs[0]);
// Find the parentheses.
int start = inputLine.indexOf('(');
int end = inputLine.lastIndexOf(')');
// Parse the args.
ArrayList<Integer> intList = new ArrayList<Integer>(4);
ArrayList<Float> floatList = new ArrayList<Float>(2);
ArrayList<String> stringList = new ArrayList<String>(4);
ArrayList<Boolean> boolList = new ArrayList<Boolean>(3);
parseArguments(inputLine.substring(start + 1, end),
intList, floatList, stringList, boolList);
int colon = inputLine.indexOf(':');
if (colon > 1 && colon < start) {
// This is a regular function call. Look for the name and call it.
String func = inputLine.substring(colon + 1, start);
if (func.equals("drawLine")) {
windows.get(windowID).drawLine(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else if (func.equals("createPolyline")) {
windows.get(windowID).createPolyline(intList.get(0));
} else if (func.equals("drawPolyline")) {
windows.get(windowID).drawPolyline();
} else if (func.equals("drawRectangle")) {
windows.get(windowID).drawRectangle(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else if (func.equals("setVisible")) {
windows.get(windowID).setVisible(boolList.get(0));
} else if (func.equals("setAlwaysOnTop")) {
windows.get(windowID).setAlwaysOnTop(boolList.get(0));
} else if (func.equals("addMessage")) {
windows.get(windowID).addMessage(stringList.get(0));
} else if (func.equals("addMessageBox")) {
windows.get(windowID).addMessageBox();
} else if (func.equals("clear")) {
windows.get(windowID).clear();
} else if (func.equals("setStrokeWidth")) {
windows.get(windowID).setStrokeWidth(floatList.get(0));
} else if (func.equals("drawEllipse")) {
windows.get(windowID).drawEllipse(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else if (func.equals("pen")) {
if (intList.size() == 4) {
windows.get(windowID).pen(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else {
windows.get(windowID).pen(intList.get(0), intList.get(1),
intList.get(2));
}
} else if (func.equals("brush")) {
if (intList.size() == 4) {
windows.get(windowID).brush(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else {
windows.get(windowID).brush(intList.get(0), intList.get(1),
intList.get(2));
}
} else if (func.equals("textAttributes")) {
windows.get(windowID).textAttributes(stringList.get(0),
intList.get(0),
boolList.get(0),
boolList.get(1),
boolList.get(2));
} else if (func.equals("drawText")) {
windows.get(windowID).drawText(intList.get(0), intList.get(1),
stringList.get(0));
} else if (func.equals("addMenuBarItem")) {
if (boolList.size() > 0) {
windows.get(windowID).addMenuBarItem(stringList.get(0),
stringList.get(1),
intList.get(0),
boolList.get(0));
} else if (intList.size() > 0) {
windows.get(windowID).addMenuBarItem(stringList.get(0),
stringList.get(1),
intList.get(0));
} else {
windows.get(windowID).addMenuBarItem(stringList.get(0),
stringList.get(1));
}
} else if (func.equals("addPopupMenuItem")) {
if (stringList.size() == 4) {
windows.get(windowID).addPopupMenuItem(stringList.get(0),
stringList.get(1),
intList.get(0),
stringList.get(2),
stringList.get(3));
} else {
windows.get(windowID).addPopupMenuItem(stringList.get(0),
stringList.get(1));
}
} else if (func.equals("update")) {
windows.get(windowID).update();
} else if (func.equals("showInputDialog")) {
windows.get(windowID).showInputDialog(stringList.get(0));
} else if (func.equals("showYesNoDialog")) {
windows.get(windowID).showYesNoDialog(stringList.get(0));
} else if (func.equals("zoomRectangle")) {
windows.get(windowID).zoomRectangle(intList.get(0), intList.get(1),
intList.get(2), intList.get(3));
} else if (func.equals("readImage")) {
PImage image = SVImageHandler.readImage(intList.get(2), in);
windows.get(windowID).drawImage(image, intList.get(0), intList.get(1));
} else if (func.equals("drawImage")) {
PImage image = new PImage(stringList.get(0));
windows.get(windowID).drawImage(image, intList.get(0), intList.get(1));
} else if (func.equals("destroy")) {
windows.get(windowID).destroy();
}
// else for forward compatibility purposes, silently ignore any
// unrecognized function call.
} else {
// No colon. Check for create window.
if (idStrs[1].startsWith("= luajava.newInstance")) {
while (windows.size() <= windowID) {
windows.add(null);
}
windows.set(windowID, new SVWindow(stringList.get(1),
intList.get(0), intList.get(1),
intList.get(2), intList.get(3),
intList.get(4), intList.get(5),
intList.get(6)));
}
// else for forward compatibility purposes, silently ignore any
// unrecognized function call.
}
} else if (inputLine.startsWith("svmain")) {
// Startup or end. Startup is a lua bind, which is now a no-op.
if (inputLine.startsWith("svmain:exit")) {
exit();
}
// else for forward compatibility purposes, silently ignore any
// unrecognized function call.
}
// else for forward compatibility purposes, silently ignore any
// unrecognized function call.
}
/** Called from the client to make the server exit. */
public static void exit() {
System.exit(0);
}
/**
* The main function. Sets up LUA and the server connection and then calls the
* IOLoop.
*/
public static void main(String[] args) {
if (args.length > 0) {
SERVER_PORT = Integer.parseInt(args[0]);
}
windows = new ArrayList<SVWindow>(100);
intPattern = Pattern.compile("[0-9-][0-9]*");
floatPattern = Pattern.compile("[0-9-][0-9]*\\.[0-9]*");
// Open a socket to listen on.
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) {
System.out.println("Socket started on port " + SERVER_PORT);
// Wait (blocking) for an incoming connection
socket = serverSocket.accept();
System.out.println("Client connected");
// Setup the streams
out = new PrintStream(socket.getOutputStream(), true, "UTF-8");
in =
new BufferedReader(new InputStreamReader(socket.getInputStream(),
"UTF8"));
} catch (IOException e) {
// Something went wrong and we were unable to set up a connection. This is
// pretty
// much a fatal error.
// Note: The server does not get restarted automatically if this happens.
e.printStackTrace();
System.exit(1);
}
// Enter the main program loop.
IOLoop();
}
}
| 17,176 | 41.517327 | 81 | java |
null | tesseract-main/java/com/google/scrollview/events/SVEventType.java | // Copyright 2007 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); You may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
// applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
package com.google.scrollview.events;
/**
* These are the defined events which can happen in ScrollView and be
* transferred to the client. They are same events as on the client side part of
* ScrollView (defined in ScrollView.h).
*
* @author wanke@google.com
*/
public enum SVEventType {
SVET_DESTROY, // Window has been destroyed by user.
SVET_EXIT, // User has destroyed the last window by clicking on the 'X'
SVET_CLICK, // Any button pressed that is not a popup trigger.
SVET_SELECTION, // Left button selection.
SVET_INPUT, // Any kind of input
SVET_MOUSE, // The mouse has moved with a button pressed.
SVET_MOTION, // The mouse has moved with no button pressed.
SVET_HOVER, // The mouse has stayed still for a second.
SVET_POPUP, // A command selected through a popup menu
SVET_MENU; // A command selected through the menubar
}
| 1,456 | 44.53125 | 80 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.