Beispiel #1
0
  public boolean enc(String pubfile, String policy, String inputfile, String encfile)
      throws Exception {
    CpabeEncryptedFile encFile;
    BswabePub pub;
    BswabeCph cph;
    BswabeCphKey keyCph;
    byte[] plt, aesBuf, pub_byte;
    Element m;

    /* get BswabePub from pubfile */
    pub_byte = Common.suckFile(pubfile);
    pub = new BswabePub();
    pub.initFromBuffer(pub_byte);

    /* encrypt */
    keyCph = Bswabe.enc(pub, policy);
    cph = keyCph.cph;
    m = keyCph.key;

    if (cph == null) {
      return false;
    }

    /* write file to encrypted */
    plt = Common.suckFile(inputfile);
    aesBuf = AESCoder.encrypt(m.toBytes(), plt);

    encFile = new CpabeEncryptedFile(cph, aesBuf);
    Common.spitFile(encfile, encFile.serialize());

    return true;
  }
  /**
   * Create a session key, encrypt it with the given request and claimDef. Return a serialized JSON
   * node with the session key and challenge.
   *
   * @param request Request from user: Base64 encoded bytes of the request element.
   * @param claimDef Claim definition to use: JSON encoded
   * @return
   * @throws Exception
   */
  public String createChallange(String request, String claimDef) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode claimDefOn = (ObjectNode) mapper.readTree(claimDef);
    IdentityClaimDefinition idClaimDef = new IdentityClaimDefinition(claimDefOn);

    byte[] reqElemBytes = Base64.decode(request);
    Element reqElem = idClaimDef.getParams().getPairing().getG1().newElement();
    reqElem.setFromBytes(reqElemBytes);

    Element sessionKey =
        idClaimDef.getParams().getPairing().getGT().newRandomElement().getImmutable();

    // Encrypt session key
    Encrypt encrypt = new Encrypt();
    encrypt.init(idClaimDef.getParams());
    AECipherTextBlock ct = encrypt.doEncrypt(sessionKey, reqElem);

    JsonNode rootNode = mapper.createObjectNode();
    ObjectNode on = (ObjectNode) rootNode;

    on.put(idClaimDef.getName(), ct.serializeJSON());
    String sk = new String(Base64.encode(sessionKey.toBytes()));
    sk = sk.replaceAll(" ", "");
    on.put("SessionKey", sk);

    return on.toString();
  }
  public Element pairing(Element[] in1, Element[] in2) {
    Element out = pairing((Point) in1[0], (Point) in2[0]);

    for (int i = 1; i < in1.length; i++) out.mul(pairing((Point) in1[i], (Point) in2[i]));

    return out;
  }
  public boolean isValid() {
    Element t0, t1;

    if (infFlag != 0) return true;

    t0 = field.getTargetField().newElement();
    t1 = field.getTargetField().newElement();
    t0.set(x).square().add(getField().getA()).mul(x).add(getField().getB());
    t1.set(y).square();

    return t0.isEqual(t1);
  }
  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 void twiceInternal() {
    // We have P1 = P2 so the tangent line T at P1 ha slope
    // lambda = (3x^2 + a) / 2y
    Element lambda =
        x.duplicate().square().mul(3).add(getField().a).mul(y.duplicate().twice().invert());

    // x3 = lambda^2 - 2x
    Element x3 = lambda.duplicate().square().sub(x.duplicate().twice());

    // y3 = (x - x3) lambda - y
    Element y3 = x.duplicate().sub(x3).mul(lambda).sub(y);

    x.set(x3);
    y.set(y3);
    infFlag = 0;
  }
  public CurveElement<?> mul(Element e) {
    //        counter++;
    // Apply the Chord-Tangent Law of Composition
    // Consider P1 = this = (x1, y1);
    //          P2 = e = (x2, y2);

    if (infFlag != 0) {
      set(e);
      return this;
    }

    CurveElement<?> element = (CurveElement<?>) e;

    if (element.infFlag != 0) return this;

    if (x.isEqual(element.x)) {
      if (y.isEqual(element.y)) {
        if (y.isZero()) {
          infFlag = 1;
          return this;
        } else {
          twiceInternal();
          return this;
        }
      }

      infFlag = 1;
      return this;
    } else {
      // P1 != P2, so the slope of the line L through P1 and P2 is
      // lambda = (y2-y1)/(x2-x1)
      Element lambda = element.y.duplicate().sub(y).mul(element.x.duplicate().sub(x).invert());

      // x3 = lambda^2 - x1 - x2
      Element x3 = lambda.duplicate().square().sub(x).sub(element.x);

      // y3 = (x1-x3)lambda - y1
      Element y3 = x.duplicate().sub(x3).mul(lambda).sub(y);

      x.set(x3);
      y.set(y3);
      infFlag = 0;
    }

    return this;
  }
  public String createChallangeNAClaims(String req, String claimDefs, int size) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode claimDefNodes = (ArrayNode) mapper.readTree(claimDefs);

    req = req.replaceAll("\"", "");
    byte[] reqElemBytes = Base64.decode(req);

    Element reqElem = null;
    ArrayList<IdentityClaimDefinition> icds = new ArrayList<IdentityClaimDefinition>();

    for (int i = 0; i < size; i++) {
      String onVal = claimDefNodes.get(i).getTextValue();

      ObjectNode claimDefOn = (ObjectNode) mapper.readTree(onVal);
      IdentityClaimDefinition idClaimDef = new IdentityClaimDefinition(claimDefOn);
      icds.add(idClaimDef);

      if (reqElem == null) {
        Pairing pairing = idClaimDef.getParams().getPairing();
        reqElem = pairing.getG1().newElement();
        reqElem.setFromBytes(reqElemBytes);
        //				System.out.println(reqElem);
      }
    }

    Pairing pairing = icds.get(0).getParams().getPairing();
    Field gt = pairing.getGT();
    Element sessionKey = gt.newRandomElement().getImmutable();
    Element sessionKeyOrig = sessionKey.getImmutable();
    // System.out.println("Key: " + sessionKey);

    JsonNode rootNode = mapper.createObjectNode();
    ObjectNode on = (ObjectNode) rootNode;
    Encrypt encrypt = new Encrypt();

    for (int i = 0; i < size; i++) {
      IdentityClaimDefinition claimDef = icds.get(i);

      Element share = null;
      if (i < (size - 1)) {
        share = gt.newRandomElement().getImmutable();
        sessionKey = sessionKey.sub(share).getImmutable();
      } else {
        // Last one should be the remaining part of session key
        share = sessionKey;
      }

      encrypt.init(claimDef.getParams());
      // System.out.println("Part : " + i + " : " + share);
      AECipherTextBlock ct = encrypt.doEncrypt(share, reqElem);

      on.put(claimDef.getName(), ct.serializeJSON());
    }

    //		System.out.println(sessionKeyOrig);
    String sk = new String(Base64.encode(sessionKeyOrig.toBytes()));
    sk = sk.replaceAll(" ", "");
    on.put("SessionKey", sk);
    return on.toString();
  }
  public CurveElement<?> setFromHash(byte[] source, int offset, int length) {
    infFlag = 0;
    x.setFromHash(source, offset, length);

    Element t = field.getTargetField().newElement();
    for (; ; ) {
      t.set(x).square().add(curveField.a).mul(x).add(curveField.b);
      if (t.isSqr()) break;

      x.square().add(t.setToOne());
    }
    y.set(t).sqrt();
    if (y.sign() < 0) y.negate();

    if (curveField.cofac != null) mul(curveField.cofac);

    return this;
  }
  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();
  }
  /**
   * left-to-right exponentiation with k-bit window. NB. must have k >= 1.
   *
   * @param n
   */
  protected void elementPowWind(BigInteger n) {
    /* early abort if raising to power 0 */
    if (n.signum() == 0) {
      setToOne();
      return;
    }

    int word = 0; /* the word to look up. 0<word<base */
    int wbits = 0; /* # of bits so far in word. wbits<=k. */
    int k = optimalPowWindowSize(n);
    List<Element> lookup = buildPowWindow(k);
    Element result = field.newElement().setToOne();

    for (int inword = 0, s = n.bitLength() - 1; s >= 0; s--) {
      result.square();
      int bit = n.testBit(s) ? 1 : 0;

      if (inword == 0 && bit == 0) continue; /* keep scanning. note continue. */

      if (inword == 0) {
        /* was scanning, just found word */
        inword = 1; /* so, start new word */
        word = 1;
        wbits = 1;
      } else {
        word = (word << 1) + bit;
        wbits++; /* continue word */
      }

      if (wbits == k || s == 0) {
        result.mul(lookup.get(word));
        inword = 0;
      }
    }

    set(result);
  }
  private void initialize(CurveParameters cp) {
    random = new Random(0);
    // e = PairingFactory.getPairing(cp);

    e = new TypeAPairing(random, cp);

    // Groups G1 and G2 of prime order q
    G1 = e.getG1();
    G2 = e.getGT();

    // Field Zq
    Zq = e.getZr();

    // Global system parameters: g \in G1, Z = e(g,g) \in G2
    g = ((CurveField) G1).getGen().getImmutable();
    //        if(g.isZero()){
    //            System.out.println("g es 0!! :(");
    //            System.exit(-1);
    //        }
    //        g = G1.newRandomElement().getImmutable();
    // System.out.println("g = " + ProxyMain.elementToString(g));

    Z = e.pairing(g, g).getImmutable();

    Z_ppp = Z.pow();
    g_ppp = g.pow();

    /*
    System.out.println(G1.getClass());
    System.out.println(G2.getClass());
    System.out.println(Zq.getClass());
    System.out.println(e.getClass());
    System.out.println(g.getClass());
    System.out.println(g.toBytes()[0]);
    System.out.println(Z.getClass());*/

  }
  public PS06Parameters generateParameters() {
    Element g = pairing.getG1().newRandomElement();

    return new PS06Parameters(curveParams, g.getImmutable(), nU, nM);
  }
 public Element powZn(Element n) {
   return pow(n.toBigInteger());
 }
 public CurveElement<?> powZn(Element e) {
   //        counter++;
   pow(e.toBigInteger());
   return this;
 }
 public Element sub(Element element) {
   add(element.duplicate().negate());
   return this;
 }
 public Element div(Element element) {
   return mul(element.duplicate().invert());
 }
  /**
   * @param request
   * @param claimDefs Array of claim defs
   * @return
   * @throws Exception
   */
  public String createChallangeNClaimsThreads(String requests, String claimDefs) throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    // System.out.println(requests);
    String[] split = requests.split(",");
    ArrayNode claimDefNodes = (ArrayNode) mapper.readTree(claimDefs);

    ArrayList<IdentityClaimDefinition> icds = new ArrayList<IdentityClaimDefinition>();
    ArrayList<Element> reqs = new ArrayList<Element>();

    for (int i = 0; i < split.length; i++) {
      String onVal = claimDefNodes.get(i).getTextValue();
      ObjectNode claimDefOn = (ObjectNode) mapper.readTree(onVal);
      IdentityClaimDefinition idClaimDef = new IdentityClaimDefinition(claimDefOn);
      icds.add(idClaimDef);

      Pairing pairing = idClaimDef.getParams().getPairing();
      // System.out.println(idClaimDef.serializeJSON());
      String tmpReq = split[i].replaceAll("\"", "");

      byte[] reqElemBytes = Base64.decode(tmpReq);
      // System.out.println(reqElemBytes.length);
      Element reqElem = pairing.getG1().newElement();
      reqElem.setFromBytes(reqElemBytes);
      // System.out.println(reqElem.getImmutable());

      reqs.add(reqElem);
    }

    Pairing pairing = icds.get(0).getParams().getPairing();
    Field gt = pairing.getGT();
    Element sessionKey = gt.newRandomElement().getImmutable();
    Element sessionKeyOrig = sessionKey.getImmutable();
    // System.out.println("Key: " + sessionKey);

    JsonNode rootNode = mapper.createObjectNode();
    ObjectNode on = (ObjectNode) rootNode;

    ArrayList<EncrypterThread> ets = new ArrayList<ServiceProvider.EncrypterThread>();

    for (int i = 0; i < split.length; i++) {
      IdentityClaimDefinition claimDef = icds.get(i);

      Element share = null;
      if (i < (split.length - 1)) {
        share = gt.newRandomElement().getImmutable();
        sessionKey = sessionKey.sub(share).getImmutable();
      } else {
        // Last one should be the remaining part of session key
        share = sessionKey;
      }

      EncrypterThread t =
          new EncrypterThread(claimDef.getName(), claimDef.getParams(), share, reqs.get(i), on);
      t.start();
      ets.add(t);
    }

    for (EncrypterThread t : ets) {
      t.join();
    }

    String sk = new String(Base64.encode(sessionKeyOrig.toBytes()));
    sk = sk.replaceAll(" ", "");
    on.put("SessionKey", sk);
    return on.toString();
  }
 public Element mulZn(Element z) {
   return mul(z.toBigInteger());
 }