Package net.i2p.util

Examples of net.i2p.util.NativeBigInteger


    }
   
    if(throttleRekey(pn, replyTo)) return;
      

    if(negType >= 8 || DiffieHellman.checkDHExponentialValidity(this.getClass(), new NativeBigInteger(1,hisExponential))) {
      // JFK protects us from weak key attacks on ECDH, so we don't need to check.
        try {
          sendJFKMessage2(nonceInitiator, hisExponential, pn, replyTo, unknownInitiator, setupType, negType);
        } catch (NoContextsException e) {
          handleNoContextsException(e, NoContextsException.CONTEXT.REPLYING);
View Full Code Here


      }
      return;
    }

    if(negType < 8) { // legacy DH
        NativeBigInteger _hisExponential = new NativeBigInteger(1,hisExponential);
        if(!DiffieHellman.checkDHExponentialValidity(this.getClass(), _hisExponential)) {
            Logger.error(this, "We can't accept the exponential "+pn.getPeer()+" sent us!! REDFLAG: IT CAN'T HAPPEN UNLESS AGAINST AN ACTIVE ATTACKER!!");
            return;
        }
      // JFK protects us from weak key attacks on ECDH, so we don't need to check.
    }

    if(negType < 9) {
        // Verify the DSA signature
        byte[] r = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
        byte[] s = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
        System.arraycopy(sig, 0, r, 0, Node.SIGNATURE_PARAMETER_LENGTH);
        System.arraycopy(sig, Node.SIGNATURE_PARAMETER_LENGTH, s, 0, Node.SIGNATURE_PARAMETER_LENGTH);
        DSASignature remoteSignature = new DSASignature(new NativeBigInteger(1,r), new NativeBigInteger(1,s));
        // At that point we don't know if it's "him"; let's check it out
        byte[] locallyExpectedExponentials =  assembleDHParams(hisExponential, pn.peerCryptoGroup);

        if(!DSA.verify(pn.peerPubKey, remoteSignature, new NativeBigInteger(1, SHA256.digest(locallyExpectedExponentials)), false)) {
            Logger.error(this, "The signature verification has failed in JFK(2)!! "+pn.getPeer());
            return;
        }
    } else {
        // Verify the ECDSA signature ; We are assuming that it's the curve we expect
View Full Code Here

    byte[] hmac = Arrays.copyOfRange(payload, inputOffset, inputOffset+HASH_LENGTH);
    inputOffset += HASH_LENGTH;

    byte[] computedExponential;
    if(negType < 8) { // Legacy DH
      NativeBigInteger _hisExponential = new NativeBigInteger(1, initiatorExponential);
      NativeBigInteger _ourExponential = new NativeBigInteger(1, responderExponential);

      DiffieHellmanLightContext ctx = findContextByExponential(_ourExponential);
      if(ctx == null) {
        Logger.error(this, "WTF? the HMAC verified but we don't know about that exponential! SHOULDN'T HAPPEN! - JFK3 - "+pn);
        // Possible this is a replay or severely delayed? We don't keep every exponential we ever use.
        return;
      }
      computedExponential = ctx.getHMACKey(_hisExponential);
        } else {
            ECPublicKey initiatorKey = ECDH.getPublicKey(initiatorExponential, ecdhCurveToUse);
            ECPublicKey responderKey = ECDH.getPublicKey(responderExponential, ecdhCurveToUse);
            ECDHLightContext ctx = findECDHContextByPubKey(responderKey);
            if (ctx == null) {
                Logger.error(this, "WTF? the HMAC verified but we don't know about that exponential! SHOULDN'T HAPPEN! - JFK3 - "+pn);
                // Possible this is a replay or severely delayed? We don't keep
                // every exponential we ever use.
                return;
            }
            computedExponential = ctx.getHMACKey(initiatorKey);
        }
    if(logDEBUG) Logger.debug(this, "The shared Master secret is : "+HexUtil.bytesToHex(computedExponential) +" for " + pn);
   
    /* 0 is the outgoing key for the initiator, 7 for the responder */
    byte[] outgoingKey = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "7");
    byte[] incommingKey = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "0");
    byte[] Ke = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "1");
    byte[] Ka = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "2");

    byte[] hmacKey = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "3");
    byte[] ivKey = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "4");
    byte[] ivNonce = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "5");

    /* Bytes  1-4:  Initial sequence number for the initiator
     * Bytes  5-8:  Initial sequence number for the responder
     * Bytes  9-12: Initial message id for the initiator
     * Bytes 13-16: Initial message id for the responder
     * Note that we are the responder */
    byte[] sharedData = computeJFKSharedKey(computedExponential, nonceInitiatorHashed, nonceResponder, "6");
    Arrays.fill(computedExponential, (byte)0);
    int theirInitialSeqNum = ((sharedData[0] & 0xFF) << 24)
        | ((sharedData[1] & 0xFF) << 16)
        | ((sharedData[2] & 0xFF) << 8)
        | (sharedData[3] & 0xFF);
    int ourInitialSeqNum = ((sharedData[4] & 0xFF) << 24)
        | ((sharedData[5] & 0xFF) << 16)
        | ((sharedData[6] & 0xFF) << 8)
        | (sharedData[7] & 0xFF);
    int theirInitialMsgID, ourInitialMsgID;
    if(negType >= 7) {
      theirInitialMsgID =
        unknownInitiator ? getInitialMessageID(crypto.myIdentity) :
          getInitialMessageID(pn.identity, crypto.myIdentity);
      ourInitialMsgID =
        unknownInitiator ? getInitialMessageID(crypto.myIdentity) :
          getInitialMessageID(crypto.myIdentity, pn.identity);
    } else {
      theirInitialMsgID= ((sharedData[8] & 0xFF) << 24)
        | ((sharedData[9] & 0xFF) << 16)
        | ((sharedData[10] & 0xFF) << 8)
        | (sharedData[11] & 0xFF);
      ourInitialMsgID= ((sharedData[12] & 0xFF) << 24)
        | ((sharedData[13] & 0xFF) << 16)
        | ((sharedData[14] & 0xFF) << 8)
        | (sharedData[15] & 0xFF);
    }
    if(logMINOR)
      Logger.minor(this, "Their initial message ID: "+theirInitialMsgID+" ours "+ourInitialMsgID);

    c.initialize(Ke);
    int ivLength = PCFBMode.lengthIV(c);
    int decypheredPayloadOffset = 0;
    // We compute the HMAC of ("I"+cyphertext) : the cyphertext includes the IV!
    byte[] decypheredPayload = Arrays.copyOf(JFK_PREFIX_INITIATOR, JFK_PREFIX_INITIATOR.length + payload.length - inputOffset);
    decypheredPayloadOffset += JFK_PREFIX_INITIATOR.length;
    System.arraycopy(payload, inputOffset, decypheredPayload, decypheredPayloadOffset, decypheredPayload.length-decypheredPayloadOffset);
    if(!HMAC.verifyWithSHA256(Ka, decypheredPayload, hmac)) {
      Logger.error(this, "The inner-HMAC doesn't match; let's discard the packet JFK(3) - "+pn);
      return;
    }

    final PCFBMode pk = PCFBMode.create(c, decypheredPayload, decypheredPayloadOffset);
    // Get the IV
    decypheredPayloadOffset += ivLength;
    // Decrypt the payload
    pk.blockDecipher(decypheredPayload, decypheredPayloadOffset, decypheredPayload.length-decypheredPayloadOffset);
    /*
     * DecipheredData Format:
     * Signature
     * Node Data (starting with BootID)
     */
    int sigLength = getSignatureLength(negType);
    byte[] sig = new byte[sigLength];
    System.arraycopy(decypheredPayload, decypheredPayloadOffset, sig, 0, sigLength);
    decypheredPayloadOffset += sigLength;
    byte[] data = new byte[decypheredPayload.length - decypheredPayloadOffset];
    System.arraycopy(decypheredPayload, decypheredPayloadOffset, data, 0, decypheredPayload.length - decypheredPayloadOffset);
    int ptr = 0;
    long trackerID;
    trackerID = Fields.bytesToLong(data, ptr);
    if(trackerID < 0) trackerID = -1;
    ptr += 8;
    long bootID = Fields.bytesToLong(data, ptr);
    ptr += 8;
    byte[] hisRef = Arrays.copyOfRange(data, ptr, data.length);

    // construct the peernode
    if(unknownInitiator) {
      pn = getPeerNodeFromUnknownInitiator(hisRef, setupType, pn, replyTo);
    }
    if(pn == null) {
      if(unknownInitiator) {
        // Reject
        Logger.normal(this, "Rejecting... unable to construct PeerNode");
      } else {
        Logger.error(this, "PeerNode is null and unknownInitiator is false!");
      }
      return;
    }

    // verify the signature
    byte[] toVerify = assembleDHParams(nonceInitiatorHashed, nonceResponder, initiatorExponential, responderExponential, crypto.getIdentity(negType, false), data);
    if(negType < 9) {
        byte[] r = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
        System.arraycopy(sig, 0, r, 0, Node.SIGNATURE_PARAMETER_LENGTH);
            byte[] s = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
            System.arraycopy(sig, Node.SIGNATURE_PARAMETER_LENGTH, s, 0, Node.SIGNATURE_PARAMETER_LENGTH);
        DSASignature remoteSignature = new DSASignature(new NativeBigInteger(1,r), new NativeBigInteger(1,s));
        if(!DSA.verify(pn.peerPubKey, remoteSignature, new NativeBigInteger(1, SHA256.digest(toVerify)), false)) {
            Logger.error(this, "The signature verification has failed!! JFK(3) - "+pn.getPeer());
            return;
        }
    } else {
        if(!ECDSA.verify(Curves.P256, pn.peerECDSAPubKey(), sig, toVerify)) {
View Full Code Here

      if(negType < 9) { // DSA sig    
          byte[] r = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
          System.arraycopy(sig, 0, r, 0, Node.SIGNATURE_PARAMETER_LENGTH);
          byte[] s = new byte[Node.SIGNATURE_PARAMETER_LENGTH];
          System.arraycopy(sig, Node.SIGNATURE_PARAMETER_LENGTH, s, 0, Node.SIGNATURE_PARAMETER_LENGTH);
          DSASignature remoteSignature = new DSASignature(new NativeBigInteger(1,r), new NativeBigInteger(1,s));
          byte[] messageHash = SHA256.digest(locallyGeneratedText);
          if(!DSA.verify(pn.peerPubKey, remoteSignature, new NativeBigInteger(1, messageHash), false)) {
              String error = "The signature verification has failed!! JFK(4) -"+pn.getPeer()+" message hash "+HexUtil.bytesToHex(messageHash)+" length "+locallyGeneratedText.length+" hisRef "+hisRef.length+" hash "+Fields.hashCode(hisRef)+" myRef "+pn.jfkMyRef.length+" hash "+Fields.hashCode(pn.jfkMyRef)+" boot ID "+bootID;
              Logger.error(this, error);
              return true;
          }
      } else { // ECDSA sig
View Full Code Here

    pn.setJFKBuffer(toSign);
    byte[] sig = (negType < 9 ? crypto.sign(SHA256.digest(toSign)) : crypto.ecdsaSign(toSign));

    byte[] computedExponential;
    if (negType < 8 ) { // Legacy DH
        NativeBigInteger _hisExponential = new NativeBigInteger(1,hisExponential);
        computedExponential= ((DiffieHellmanLightContext)ctx).getHMACKey(_hisExponential);
    }else {
        computedExponential = ((ECDHLightContext)ctx).getHMACKey(ECDH.getPublicKey(hisExponential, ecdhCurveToUse));
    }
    if(logDEBUG) Logger.debug(this, "The shared Master secret is : "+HexUtil.bytesToHex(computedExponential)+ " for " + pn);
View Full Code Here

      for(int i=0;i<keyLength;i+=hashLength) {
        System.arraycopy(V[i/hashLength], 0, Wbuf, i/8, hashLength/8);
      }
      Wbuf[0] = (byte) (Wbuf[0] | 128);
     
      BigInteger X = new NativeBigInteger(1, Wbuf);
     
      // 9: Let c = X mod 2q. Set p = X - ( c - 1 ). Therefore p mod 2q = 1.
     
      BigInteger c = X.mod(q.add(q));
      BigInteger p = X.subtract(c.subtract(BigInteger.ONE));
     
      if(p.bitLength() >= keyLength-1) {
        if(isPrime(p)) {
          finish(r, hashLength, new NativeBigInteger(p), new NativeBigInteger(q), seed, counter);
          return true;
        }
      }
     
      counter++;
View Full Code Here

      System.out.println("SEED: "+HexUtil.bytesToHex(seed));
      System.out.println("COUNTER: "+counter);
      System.out.println("p: "+p.toString(16)+" ("+p.bitLength()+ ')');
      System.out.println("q: "+q.toString(16)+" ("+q.bitLength()+ ')');
    // Now generate g (algorithm from appendix 4 of FIPS 186-2)
      NativeBigInteger g;
      do {
        BigInteger e = p.subtract(BigInteger.ONE).divide(q);
        NativeBigInteger h;
        do {
          h = new NativeBigInteger(hashLength, r);
        } while(h.compareTo(p.subtract(BigInteger.ONE)) >= 0);
        g = (NativeBigInteger) h.modPow(e, p);
      } while (g.equals(BigInteger.ONE));
      DSAGroup group = new DSAGroup(p, q, g);
      System.out.println("g: "+HexUtil.toHexString(g)+" ("+g.bitLength()+ ')');
      System.out.println("Group: "+group.verboseToString());
      long totalSigTime = 0;
      long totalVerifyTime = 0;
      for(int i=0;i<10000;i++) {
      byte[] testHash = new byte[hashLength/8];
      r.nextBytes(testHash);
      NativeBigInteger m = new NativeBigInteger(1, testHash);
      DSAPrivateKey privKey = new DSAPrivateKey(group, r);
      DSAPublicKey pubKey = new DSAPublicKey(group, privKey);
      long now = System.currentTimeMillis();
      DSASignature sig = DSA.sign(group, privKey, m, r);
      long middle = System.currentTimeMillis();
View Full Code Here

   * Calling the following is costy; avoid
   */
  public byte[] getHMACKey(NativeBigInteger peerExponential) {
    lastUsedTime = System.currentTimeMillis();
    BigInteger P = group.getP();
    NativeBigInteger sharedSecret =
      (NativeBigInteger) peerExponential.modPow(myExponent, P);

    if(logMINOR) {
      Logger.minor(this, "P: "+HexUtil.biToHex(P));
      Logger.minor(this, "My exponent: "+HexUtil.toHexString(myExponent));
      Logger.minor(this, "My exponential: "+HexUtil.toHexString(myExponential));
      Logger.minor(this, "Peer's exponential: "+HexUtil.toHexString(peerExponential));
      Logger.minor(this, "g^ir mod p = " + HexUtil.toHexString(sharedSecret));
    }
   
    return sharedSecret.toByteArray();
  }
View Full Code Here

            if(g.getQ().bitLength() < DSAGroup.Q_BIT_LENGTH)
        throw new IllegalArgumentException("Q is too short! (" + g.getQ().bitLength() + '<' + DSAGroup.Q_BIT_LENGTH + ')');
   
            BigInteger k;
    do {
      k=new NativeBigInteger(DSAGroup.Q_BIT_LENGTH, r);
    } while ((g.getQ().compareTo(k) < 1) || (k.compareTo(BigInteger.ZERO) < 1));
    return k;
  }
View Full Code Here

        if(p.signum() != 1 || q.signum() != 1 || g.signum() != 1)
          throw new IllegalArgumentException();
    }

    private DSAGroup(DSAGroup group) {
      this.p = new NativeBigInteger(1, group.p.toByteArray());
      this.q = new NativeBigInteger(1, group.q.toByteArray());
      this.g = new NativeBigInteger(1, group.g.toByteArray());
  }
View Full Code Here

TOP

Related Classes of net.i2p.util.NativeBigInteger

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.