Search in sources :

Example 41 with SessionKey

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

the class DatabaseLookupMessage method readMessage.

public void readMessage(byte[] data, int offset, int dataSize, int type) throws I2NPMessageException {
    if (type != MESSAGE_TYPE)
        throw new I2NPMessageException("Message type is incorrect for this message");
    int curIndex = offset;
    // byte keyData[] = new byte[Hash.HASH_LENGTH];
    // System.arraycopy(data, curIndex, keyData, 0, Hash.HASH_LENGTH);
    _key = Hash.create(data, curIndex);
    curIndex += Hash.HASH_LENGTH;
    // _key = new Hash(keyData);
    // byte fromData[] = new byte[Hash.HASH_LENGTH];
    // System.arraycopy(data, curIndex, fromData, 0, Hash.HASH_LENGTH);
    _fromHash = Hash.create(data, curIndex);
    curIndex += Hash.HASH_LENGTH;
    // _fromHash = new Hash(fromData);
    // as of 0.9.6, ignore other 7 bits of the flag byte
    // TODO store the whole flag byte
    boolean tunnelSpecified = (data[curIndex] & FLAG_TUNNEL) != 0;
    boolean replyKeySpecified = (data[curIndex] & FLAG_ENCRYPT) != 0;
    switch(data[curIndex] & FLAG_TYPE_MASK) {
        case FLAG_TYPE_LS:
            _type = Type.LS;
            break;
        case FLAG_TYPE_RI:
            _type = Type.RI;
            break;
        case FLAG_TYPE_EXPL:
            _type = Type.EXPL;
            break;
        case FLAG_TYPE_ANY:
        default:
            _type = Type.ANY;
            break;
    }
    curIndex++;
    if (tunnelSpecified) {
        _replyTunnel = new TunnelId(DataHelper.fromLong(data, curIndex, 4));
        curIndex += 4;
    }
    int numPeers = (int) DataHelper.fromLong(data, curIndex, 2);
    curIndex += 2;
    if ((numPeers < 0) || (numPeers > MAX_NUM_PEERS))
        throw new I2NPMessageException("Invalid number of peers - " + numPeers);
    List<Hash> peers = numPeers > 0 ? new ArrayList<Hash>(numPeers) : null;
    for (int i = 0; i < numPeers; i++) {
        // byte peer[] = new byte[Hash.HASH_LENGTH];
        // System.arraycopy(data, curIndex, peer, 0, Hash.HASH_LENGTH);
        Hash p = Hash.create(data, curIndex);
        curIndex += Hash.HASH_LENGTH;
        peers.add(p);
    }
    _dontIncludePeers = peers;
    if (replyKeySpecified) {
        byte[] rk = new byte[SessionKey.KEYSIZE_BYTES];
        System.arraycopy(data, curIndex, rk, 0, SessionKey.KEYSIZE_BYTES);
        _replyKey = new SessionKey(rk);
        curIndex += SessionKey.KEYSIZE_BYTES;
        // number of tags, assume always 1 for now
        curIndex++;
        byte[] rt = new byte[SessionTag.BYTE_LENGTH];
        System.arraycopy(data, curIndex, rt, 0, SessionTag.BYTE_LENGTH);
        _replyTag = new SessionTag(rt);
    }
}
Also used : SessionKey(net.i2p.data.SessionKey) SessionTag(net.i2p.data.SessionTag) Hash(net.i2p.data.Hash) TunnelId(net.i2p.data.TunnelId)

Example 42 with SessionKey

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

the class DHSessionKeyBuilder method calculateSessionKey.

/**
 * Calculate a session key based on the private value and the public peer value.
 *
 * This is the first 32 bytes of the exchanged key (nominally 256 bytes),
 * EXCEPT that the first byte will be zero if the most significant bit was a 1
 * (Java BigInteger.toByteArray() format)
 *
 * Side effect - sets extraExchangedBytes to the next 32 bytes.
 */
private final SessionKey calculateSessionKey(BigInteger myPrivateValue, BigInteger publicPeerValue) {
    long start = System.currentTimeMillis();
    SessionKey key = new SessionKey();
    BigInteger exchangedKey = publicPeerValue.modPow(myPrivateValue, CryptoConstants.elgp);
    // surprise! leading zero byte half the time!
    // probably was a mistake, too late now...
    byte[] buf = exchangedKey.toByteArray();
    byte[] val = new byte[SessionKey.KEYSIZE_BYTES];
    if (buf.length < 2 * SessionKey.KEYSIZE_BYTES) {
        // UDP requires at least 32 bytes in _extraExchangedBytes for the mac key
        // Won't ever happen, typ buf is 256 or 257 bytes
        System.arraycopy(buf, 0, val, 0, Math.min(buf.length, SessionKey.KEYSIZE_BYTES));
        // == Hash.HASH_LENGTH
        byte[] remaining = new byte[SessionKey.KEYSIZE_BYTES];
        // non-caching version
        SHA256Generator.getInstance().calculateHash(buf, 0, buf.length, remaining, 0);
        _extraExchangedBytes.setData(remaining);
    // if (_log.shouldLog(Log.DEBUG))
    // _log.debug("Storing " + remaining.length + " bytes from the DH exchange by SHA256 the session key");
    } else {
        // Will always be here, typ buf is 256 or 257 bytes
        System.arraycopy(buf, 0, val, 0, SessionKey.KEYSIZE_BYTES);
        // feed the extra bytes into the PRNG
        RandomSource.getInstance().harvester().feedEntropy("DH", buf, val.length, buf.length - val.length);
        byte[] remaining = new byte[buf.length - val.length];
        System.arraycopy(buf, val.length, remaining, 0, remaining.length);
        _extraExchangedBytes.setData(remaining);
    // if (_log.shouldLog(Log.DEBUG))
    // _log.debug("Storing " + remaining.length + " bytes from the end of the DH exchange");
    }
    key.setData(val);
    long end = System.currentTimeMillis();
    long diff = end - start;
    I2PAppContext.getGlobalContext().statManager().addRateData("crypto.dhCalculateSessionTime", diff);
    // }
    return key;
}
Also used : SessionKey(net.i2p.data.SessionKey) BigInteger(java.math.BigInteger) NativeBigInteger(net.i2p.util.NativeBigInteger)

Example 43 with SessionKey

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

the class ConfigKeyringHelper method render.

/**
 *  @since 0.9.33 moved from PersistentKeyRing
 */
private void render(StringBuilder buf, boolean local) {
    buf.append("\n<table class=\"configtable\"><tr><th align=\"left\">").append(_t("Destination")).append("<th align=\"left\">").append(_t("Name")).append("<th align=\"left\">").append(_t("Encryption Key")).append("</tr>");
    for (Map.Entry<Hash, SessionKey> e : _context.keyRing().entrySet()) {
        Hash h = e.getKey();
        if (local != _context.clientManager().isLocal(h))
            continue;
        buf.append("\n<tr><td>");
        buf.append(h.toBase32());
        buf.append("</td><td>");
        Destination dest = _context.netDb().lookupDestinationLocally(h);
        if (dest != null && local) {
            TunnelPoolSettings in = _context.tunnelManager().getInboundSettings(h);
            if (in != null && in.getDestinationNickname() != null)
                buf.append(in.getDestinationNickname());
        } else {
            String host = _context.namingService().reverseLookup(h);
            if (host != null)
                buf.append(host);
        }
        buf.append("</td><td>");
        SessionKey sk = e.getValue();
        buf.append(sk.toBase64());
        buf.append("</td>\n");
    }
    buf.append("</table>\n");
}
Also used : Destination(net.i2p.data.Destination) SessionKey(net.i2p.data.SessionKey) TunnelPoolSettings(net.i2p.router.TunnelPoolSettings) Hash(net.i2p.data.Hash) Map(java.util.Map)

Example 44 with SessionKey

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

the class ElGamalTest method testAES.

public void testAES() {
    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 world";
    byte[] encrypted = _context.elGamalAESEngine().encryptAESBlock(DataHelper.getASCII(msg), sessionKey, iv, null, null, 64);
    Set<SessionTag> foundTags = new HashSet<SessionTag>();
    SessionKey foundKey = new SessionKey();
    byte[] decrypted = null;
    try {
        decrypted = _context.elGamalAESEngine().decryptAESBlock(encrypted, 0, encrypted.length, sessionKey, iv, null, foundTags, foundKey);
    } catch (DataFormatException dfe) {
        dfe.printStackTrace();
        fail();
    }
    assertNotNull(decrypted);
    String read = new String(decrypted);
    assertEquals(msg, read);
}
Also used : DataFormatException(net.i2p.data.DataFormatException) SessionKey(net.i2p.data.SessionKey) SessionTag(net.i2p.data.SessionTag) Hash(net.i2p.data.Hash) HashSet(java.util.HashSet)

Example 45 with SessionKey

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

the class ElGamalTest method testElGamal.

public void testElGamal() {
    for (int i = 0; i < 2; i++) {
        Object[] keys = KeyGenerator.getInstance().generatePKIKeypair();
        PublicKey pubKey = (PublicKey) keys[0];
        PrivateKey privKey = (PrivateKey) keys[1];
        SessionKey key = KeyGenerator.getInstance().generateSessionKey();
        ByteArrayOutputStream elgSrc = new ByteArrayOutputStream(256);
        try {
            key.writeBytes(elgSrc);
        } catch (DataFormatException dfe) {
            dfe.printStackTrace();
            fail();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail();
        }
        byte[] preIV = new byte[32];
        RandomSource.getInstance().nextBytes(preIV);
        try {
            elgSrc.write(preIV);
            elgSrc.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail();
        }
        byte[] elgEncr = _context.elGamalEngine().encrypt(elgSrc.toByteArray(), pubKey);
        byte[] elgDecr = _context.elGamalEngine().decrypt(elgEncr, privKey);
        ByteArrayInputStream bais = new ByteArrayInputStream(elgDecr);
        SessionKey nk = new SessionKey();
        try {
            nk.readBytes(bais);
        } catch (DataFormatException dfe) {
            dfe.printStackTrace();
            fail();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail();
        }
        byte[] postpreIV = new byte[32];
        int read = 0;
        try {
            read = bais.read(postpreIV);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail();
        }
        assertEquals(read, postpreIV.length);
        assertTrue(DataHelper.eq(preIV, postpreIV));
        assertEquals(key, nk);
    }
}
Also used : PrivateKey(net.i2p.data.PrivateKey) DataFormatException(net.i2p.data.DataFormatException) ByteArrayInputStream(java.io.ByteArrayInputStream) PublicKey(net.i2p.data.PublicKey) SessionKey(net.i2p.data.SessionKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

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