Search in sources :

Example 6 with SessionKey

use of net.i2p.data.SessionKey in project i2p.i2p by i2p.

the class ElGamalTest method testBasicAES.

public void testBasicAES() {
    SessionKey sessionKey = KeyGenerator.getInstance().generateSessionKey();
    Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
    byte[] iv = new byte[16];
    System.arraycopy(h.getData(), 0, iv, 0, 16);
    String msg = "Hello world01234012345678901234501234567890123450123456789012345";
    h = SHA256Generator.getInstance().calculateHash(DataHelper.getASCII(msg));
    byte[] aesEncr = new byte[DataHelper.getASCII(msg).length];
    byte[] aesDecr = new byte[aesEncr.length];
    _context.aes().encrypt(DataHelper.getASCII(msg), 0, aesEncr, 0, sessionKey, iv, aesEncr.length);
    _context.aes().decrypt(aesEncr, 0, aesDecr, 0, sessionKey, iv, aesEncr.length);
    h = SHA256Generator.getInstance().calculateHash(aesDecr);
    assertEquals(msg, new String(aesDecr));
}
Also used : SessionKey(net.i2p.data.SessionKey) Hash(net.i2p.data.Hash)

Example 7 with SessionKey

use of net.i2p.data.SessionKey in project i2p.i2p by i2p.

the class ElGamalTest method testElGamalAESEngine.

public void testElGamalAESEngine() throws Exception {
    I2PAppContext ctx = I2PAppContext.getGlobalContext();
    ElGamalAESEngine e = new ElGamalAESEngine(ctx);
    Object[] kp = ctx.keyGenerator().generatePKIKeypair();
    PublicKey pubKey = (PublicKey) kp[0];
    PrivateKey privKey = (PrivateKey) kp[1];
    SessionKey sessionKey = ctx.keyGenerator().generateSessionKey();
    for (int i = 0; i < 10; i++) {
        Set<SessionTag> tags = new HashSet<SessionTag>(5);
        if (i == 0) {
            for (int j = 0; j < 5; j++) tags.add(new SessionTag(true));
        }
        byte[] encrypted = e.encrypt(DataHelper.getASCII("blah"), pubKey, sessionKey, tags, null, 1024);
        byte[] decrypted = e.decrypt(encrypted, privKey, _context.sessionKeyManager());
        assertEquals("blah", new String(decrypted));
        ctx.sessionKeyManager().tagsDelivered(pubKey, sessionKey, tags);
    }
}
Also used : PrivateKey(net.i2p.data.PrivateKey) I2PAppContext(net.i2p.I2PAppContext) PublicKey(net.i2p.data.PublicKey) SessionKey(net.i2p.data.SessionKey) SessionTag(net.i2p.data.SessionTag) HashSet(java.util.HashSet)

Example 8 with SessionKey

use of net.i2p.data.SessionKey in project i2p.i2p by i2p.

the class ElGamalTest method testRoundTrip.

public void testRoundTrip() {
    Object[] keys = KeyGenerator.getInstance().generatePKIKeypair();
    PublicKey pubKey = (PublicKey) keys[0];
    PrivateKey privKey = (PrivateKey) keys[1];
    String msg = "Hello world";
    Set toBeDelivered = new HashSet();
    SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
    if (key == null)
        key = _context.sessionKeyManager().createSession(pubKey);
    byte[] encrypted = _context.elGamalAESEngine().encrypt(DataHelper.getASCII(msg), pubKey, key, null, null, 64);
    byte[] decrypted = null;
    try {
        decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey, _context.sessionKeyManager());
    } catch (DataFormatException dfe) {
        dfe.printStackTrace();
        fail();
    }
    assertNotNull(decrypted);
    String read = new String(decrypted);
    assertEquals(msg, read);
}
Also used : PrivateKey(net.i2p.data.PrivateKey) Set(java.util.Set) HashSet(java.util.HashSet) DataFormatException(net.i2p.data.DataFormatException) PublicKey(net.i2p.data.PublicKey) SessionKey(net.i2p.data.SessionKey) HashSet(java.util.HashSet)

Example 9 with SessionKey

use of net.i2p.data.SessionKey in project i2p.i2p by i2p.

the class HMACSHA256Test method testMultiple.

public void testMultiple() {
    int size = 1;
    for (int i = 0; i < 16; i++) {
        SessionKey key = _context.keyGenerator().generateSessionKey();
        byte[] message = new byte[size];
        size *= 2;
        _context.random().nextBytes(message);
        byte[] output = new byte[32];
        _context.hmac().calculate(key, message, 0, message.length, output, 0);
    }
}
Also used : SessionKey(net.i2p.data.SessionKey)

Example 10 with SessionKey

use of net.i2p.data.SessionKey in project i2p.i2p by i2p.

the class EstablishmentManager method establish.

/**
 *  @param queueIfMaxExceeded true normally, false if called from locked_admit so we don't loop
 *  @since 0.9.2
 */
private void establish(OutNetMessage msg, boolean queueIfMaxExceeded) {
    RouterInfo toRouterInfo = msg.getTarget();
    RouterAddress ra = _transport.getTargetAddress(toRouterInfo);
    if (ra == null) {
        _transport.failed(msg, "Remote peer has no address, cannot establish");
        return;
    }
    RouterIdentity toIdentity = toRouterInfo.getIdentity();
    Hash toHash = toIdentity.calculateHash();
    if (toRouterInfo.getNetworkId() != _networkID) {
        _context.banlist().banlistRouter(toHash);
        _transport.markUnreachable(toHash);
        _transport.failed(msg, "Remote peer is on the wrong network, cannot establish");
        return;
    }
    UDPAddress addr = new UDPAddress(ra);
    RemoteHostId maybeTo = null;
    InetAddress remAddr = addr.getHostAddress();
    int port = addr.getPort();
    // claimed address (which we won't be using if indirect)
    if (remAddr != null && port > 0 && port <= 65535) {
        maybeTo = new RemoteHostId(remAddr.getAddress(), port);
        if ((!_transport.isValid(maybeTo.getIP())) || (Arrays.equals(maybeTo.getIP(), _transport.getExternalIP()) && !_transport.allowLocal())) {
            _transport.failed(msg, "Remote peer's IP isn't valid");
            _transport.markUnreachable(toHash);
            // _context.banlist().banlistRouter(msg.getTarget().getIdentity().calculateHash(), "Invalid SSU address", UDPTransport.STYLE);
            _context.statManager().addRateData("udp.establishBadIP", 1);
            return;
        }
        InboundEstablishState inState = _inboundStates.get(maybeTo);
        if (inState != null) {
            // we have an inbound establishment in progress, queue it there instead
            synchronized (inState) {
                switch(inState.getState()) {
                    case IB_STATE_UNKNOWN:
                    case IB_STATE_REQUEST_RECEIVED:
                    case IB_STATE_CREATED_SENT:
                    case IB_STATE_CONFIRMED_PARTIALLY:
                    case IB_STATE_CONFIRMED_COMPLETELY:
                        // queue it
                        inState.addMessage(msg);
                        if (_log.shouldLog(Log.WARN))
                            _log.debug("OB msg queued to IES");
                        break;
                    case IB_STATE_COMPLETE:
                        // race, send it out (but don't call _transport.send() again and risk a loop)
                        _transport.sendIfEstablished(msg);
                        break;
                    case IB_STATE_FAILED:
                        // race, failed
                        _transport.failed(msg, "OB msg failed during IB establish");
                        break;
                }
            }
            return;
        }
    }
    RemoteHostId to;
    boolean isIndirect = addr.getIntroducerCount() > 0 || maybeTo == null;
    if (isIndirect) {
        to = new RemoteHostId(toHash);
    } else {
        to = maybeTo;
    }
    OutboundEstablishState state = null;
    int deferred = 0;
    boolean rejected = false;
    int queueCount = 0;
    state = _outboundStates.get(to);
    if (state == null) {
        state = _outboundByHash.get(toHash);
        if (state != null && _log.shouldLog(Log.INFO))
            _log.info("Found by hash: " + state);
    }
    if (state == null) {
        if (queueIfMaxExceeded && _outboundStates.size() >= getMaxConcurrentEstablish()) {
            if (_queuedOutbound.size() >= MAX_QUEUED_OUTBOUND && !_queuedOutbound.containsKey(to)) {
                rejected = true;
            } else {
                List<OutNetMessage> newQueued = new ArrayList<OutNetMessage>(MAX_QUEUED_PER_PEER);
                List<OutNetMessage> queued = _queuedOutbound.putIfAbsent(to, newQueued);
                if (queued == null) {
                    queued = newQueued;
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("Queueing outbound establish to " + to + ", increase " + PROP_MAX_CONCURRENT_ESTABLISH);
                }
                // There are still races possible but this should prevent AIOOBE and NPE
                synchronized (queued) {
                    queueCount = queued.size();
                    if (queueCount < MAX_QUEUED_PER_PEER) {
                        queued.add(msg);
                        // increment for the stat below
                        queueCount++;
                    } else {
                        rejected = true;
                    }
                    deferred = _queuedOutbound.size();
                }
            }
        } else {
            // must have a valid session key
            byte[] keyBytes = addr.getIntroKey();
            if (keyBytes == null) {
                _transport.markUnreachable(toHash);
                _transport.failed(msg, "Peer has no key, cannot establish");
                return;
            }
            SessionKey sessionKey;
            try {
                sessionKey = new SessionKey(keyBytes);
            } catch (IllegalArgumentException iae) {
                _transport.markUnreachable(toHash);
                _transport.failed(msg, "Peer has bad key, cannot establish");
                return;
            }
            boolean allowExtendedOptions = VersionComparator.comp(toRouterInfo.getVersion(), VERSION_ALLOW_EXTENDED_OPTIONS) >= 0 && !_context.getBooleanProperty(PROP_DISABLE_EXT_OPTS);
            // w/o ext options, it's always 'requested', no need to set
            // don't ask if they are indirect
            boolean requestIntroduction = allowExtendedOptions && !isIndirect && _transport.introducersMaybeRequired();
            state = new OutboundEstablishState(_context, maybeTo, to, toIdentity, allowExtendedOptions, requestIntroduction, sessionKey, addr, _transport.getDHFactory());
            OutboundEstablishState oldState = _outboundStates.putIfAbsent(to, state);
            boolean isNew = oldState == null;
            if (isNew) {
                if (isIndirect && maybeTo != null)
                    _outboundByClaimedAddress.put(maybeTo, state);
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Adding new " + state);
            } else {
                // whoops, somebody beat us to it, throw out the state we just created
                state = oldState;
            }
        }
    }
    if (state != null) {
        state.addMessage(msg);
        List<OutNetMessage> queued = _queuedOutbound.remove(to);
        if (queued != null) {
            // see comments above
            synchronized (queued) {
                for (OutNetMessage m : queued) {
                    state.addMessage(m);
                }
            }
        }
    }
    if (rejected) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Too many pending, rejecting outbound establish to " + to);
        _transport.failed(msg, "Too many pending outbound connections");
        _context.statManager().addRateData("udp.establishRejected", deferred);
        return;
    }
    if (queueCount >= MAX_QUEUED_PER_PEER) {
        _transport.failed(msg, "Too many pending messages for the given peer");
        _context.statManager().addRateData("udp.establishOverflow", queueCount, deferred);
        return;
    }
    if (deferred > 0)
        msg.timestamp("too many deferred establishers");
    else if (state != null)
        msg.timestamp("establish state already waiting");
    notifyActivity();
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) RouterIdentity(net.i2p.data.router.RouterIdentity) ArrayList(java.util.ArrayList) RouterAddress(net.i2p.data.router.RouterAddress) Hash(net.i2p.data.Hash) OutNetMessage(net.i2p.router.OutNetMessage) SessionKey(net.i2p.data.SessionKey) InetAddress(java.net.InetAddress)

Aggregations

SessionKey (net.i2p.data.SessionKey)69 SessionTag (net.i2p.data.SessionTag)15 PublicKey (net.i2p.data.PublicKey)14 I2PAppContext (net.i2p.I2PAppContext)13 HashSet (java.util.HashSet)11 Hash (net.i2p.data.Hash)11 SessionKeyManager (net.i2p.crypto.SessionKeyManager)10 PrivateKey (net.i2p.data.PrivateKey)10 InetAddress (java.net.InetAddress)9 DataFormatException (net.i2p.data.DataFormatException)9 UnknownHostException (java.net.UnknownHostException)7 TagSetHandle (net.i2p.crypto.TagSetHandle)5 Map (java.util.Map)4 GarlicMessage (net.i2p.data.i2np.GarlicMessage)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Set (java.util.Set)3 EncryptedBuildRecord (net.i2p.data.i2np.EncryptedBuildRecord)3 BigInteger (java.math.BigInteger)2