Search in sources :

Example 51 with I2PAppContext

use of net.i2p.I2PAppContext in project i2p.i2p by i2p.

the class BuildMessageTestStandalone method testBuildMessage.

public void testBuildMessage() {
    I2PAppContext ctx = I2PAppContext.getGlobalContext();
    Log log = ctx.logManager().getLog(getClass());
    List<Integer> order = pickOrder();
    TunnelCreatorConfig cfg = createConfig(ctx);
    _replyRouter = new Hash();
    byte[] h = new byte[Hash.HASH_LENGTH];
    Arrays.fill(h, (byte) 0xFF);
    _replyRouter.setData(h);
    _replyTunnel = 42;
    // populate and encrypt the message
    TunnelBuildMessage msg = new TunnelBuildMessage(ctx);
    for (int i = 0; i < order.size(); i++) {
        int hop = order.get(i).intValue();
        PublicKey key = null;
        if (hop < _pubKeys.length)
            key = _pubKeys[hop];
        BuildMessageGenerator.createRecord(i, hop, msg, cfg, _replyRouter, _replyTunnel, ctx, key);
    }
    BuildMessageGenerator.layeredEncrypt(ctx, msg, cfg, order);
    log.debug("\n================================================================" + "\nMessage fully encrypted" + "\n================================================================");
    // now msg is fully encrypted, so lets go through the hops, decrypting and replying
    // as necessary
    BuildMessageProcessor proc = new BuildMessageProcessor(ctx);
    for (int i = 0; i < cfg.getLength(); i++) {
        // this not only decrypts the current hop's record, but encrypts the other records
        // with the reply key
        BuildRequestRecord req = proc.decrypt(msg, _peers[i], _privKeys[i]);
        // If false, no records matched the _peers[i], or the decryption failed
        assertTrue("foo @ " + i, req != null);
        long ourId = req.readReceiveTunnelId();
        byte[] replyIV = req.readReplyIV();
        long nextId = req.readNextTunnelId();
        Hash nextPeer = req.readNextIdentity();
        boolean isInGW = req.readIsInboundGateway();
        boolean isOutEnd = req.readIsOutboundEndpoint();
        long time = req.readRequestTime();
        long now = (ctx.clock().now() / (60l * 60l * 1000l)) * (60 * 60 * 1000);
        int ourSlot = -1;
        EncryptedBuildRecord reply = BuildResponseRecord.create(ctx, 0, req.readReplyKey(), req.readReplyIV(), -1);
        for (int j = 0; j < TunnelBuildMessage.MAX_RECORD_COUNT; j++) {
            if (msg.getRecord(j) == null) {
                ourSlot = j;
                msg.setRecord(j, reply);
                break;
            }
        }
        log.debug("Read slot " + ourSlot + " containing hop " + i + " @ " + _peers[i].toBase64() + " receives on " + ourId + " w/ replyIV " + Base64.encode(replyIV) + " sending to " + nextId + " on " + nextPeer.toBase64() + " inGW? " + isInGW + " outEnd? " + isOutEnd + " time difference " + (now - time));
    }
    log.debug("\n================================================================" + "\nAll hops traversed and replies gathered" + "\n================================================================");
    // now all of the replies are populated, toss 'em into a reply message and handle it
    TunnelBuildReplyMessage reply = new TunnelBuildReplyMessage(ctx);
    for (int i = 0; i < TunnelBuildMessage.MAX_RECORD_COUNT; i++) reply.setRecord(i, msg.getRecord(i));
    int[] statuses = (new BuildReplyHandler(ctx)).decrypt(reply, cfg, order);
    if (statuses == null)
        throw new RuntimeException("bar");
    boolean allAgree = true;
    for (int i = 0; i < cfg.getLength(); i++) {
        Hash peer = cfg.getPeer(i);
        int record = order.get(i).intValue();
        if (statuses[record] != 0)
            allAgree = false;
    // else
    // penalize peer according to the rejection cause
    }
    log.debug("\n================================================================" + "\nAll peers agree? " + allAgree + "\n================================================================");
}
Also used : EncryptedBuildRecord(net.i2p.data.i2np.EncryptedBuildRecord) I2PAppContext(net.i2p.I2PAppContext) Log(net.i2p.util.Log) PublicKey(net.i2p.data.PublicKey) TunnelBuildMessage(net.i2p.data.i2np.TunnelBuildMessage) Hash(net.i2p.data.Hash) BuildRequestRecord(net.i2p.data.i2np.BuildRequestRecord) TunnelBuildReplyMessage(net.i2p.data.i2np.TunnelBuildReplyMessage)

Example 52 with I2PAppContext

use of net.i2p.I2PAppContext in project i2p.i2p by i2p.

the class BlockfileNamingService method main.

/**
 *  BlockfileNamingService [force]
 *  force = force writable
 */
public static void main(String[] args) {
    Properties ctxProps = new Properties();
    if (args.length > 0 && args[0].equals("force"))
        ctxProps.setProperty(PROP_FORCE, "true");
    I2PAppContext ctx = new I2PAppContext(ctxProps);
    BlockfileNamingService bns = new BlockfileNamingService(ctx);
    Properties sprops = new Properties();
    String lname = "privatehosts.txt";
    sprops.setProperty("list", lname);
    System.out.println("List " + lname + " contains " + bns.size(sprops));
    lname = "userhosts.txt";
    sprops.setProperty("list", lname);
    System.out.println("List " + lname + " contains " + bns.size(sprops));
    lname = "hosts.txt";
    sprops.setProperty("list", lname);
    System.out.println("List " + lname + " contains " + bns.size(sprops));
    /**
     **
     *        List<String> names = null;
     *        Properties props = new Properties();
     *        try {
     *            DataHelper.loadProps(props, new File("hosts.txt"), true);
     *            names = new ArrayList(props.keySet());
     *            Collections.shuffle(names);
     *        } catch (IOException ioe) {
     *            System.out.println("No hosts.txt to test with");
     *            bns.close();
     *            return;
     *        }
     *
     *        System.out.println("size() reports " + bns.size());
     *        System.out.println("getEntries() returns " + bns.getEntries().size());
     *
     *        System.out.println("Testing with " + names.size() + " hostnames");
     *        int found = 0;
     *        int notfound = 0;
     *        int rfound = 0;
     *        int rnotfound = 0;
     *        long start = System.currentTimeMillis();
     *        for (String name : names) {
     *             Destination dest = bns.lookup(name);
     *             if (dest != null) {
     *                 found++;
     *                 String reverse = bns.reverseLookup(dest);
     *                 if (reverse != null)
     *                     rfound++;
     *                 else
     *                     rnotfound++;
     *             } else {
     *                 notfound++;
     *             }
     *        }
     *        System.out.println("BFNS took " + DataHelper.formatDuration(System.currentTimeMillis() - start));
     *        System.out.println("found " + found + " notfound " + notfound);
     *        System.out.println("reverse found " + rfound + " notfound " + rnotfound);
     *
     *        //if (true) return;
     *
     *        System.out.println("Removing all " + names.size() + " hostnames");
     *        found = 0;
     *        notfound = 0;
     *        Collections.shuffle(names);
     *        start = System.currentTimeMillis();
     *        for (String name : names) {
     *             if (bns.remove(name))
     *                 found++;
     *             else
     *                 notfound++;
     *        }
     *        System.out.println("BFNS took " + DataHelper.formatDuration(System.currentTimeMillis() - start));
     *        System.out.println("removed " + found + " not removed " + notfound);
     *
     *        System.out.println("Adding back " + names.size() + " hostnames");
     *        found = 0;
     *        notfound = 0;
     *        Collections.shuffle(names);
     *        start = System.currentTimeMillis();
     *        for (String name : names) {
     *            try {
     *                 if (bns.put(name, new Destination(props.getProperty(name))))
     *                     found++;
     *                 else
     *                     notfound++;
     *            } catch (DataFormatException dfe) {}
     *        }
     *        System.out.println("BFNS took " + DataHelper.formatDuration(System.currentTimeMillis() - start));
     *        System.out.println("Added " + found + " not added " + notfound);
     *        System.out.println("size() reports " + bns.size());
     *
     *        //bns.dumpDB();
     ***
     */
    bns.close();
    ctx.logManager().flush();
    System.out.flush();
/**
 **
 *        if (true) return;
 *
 *        HostsTxtNamingService htns = new HostsTxtNamingService(I2PAppContext.getGlobalContext());
 *        found = 0;
 *        notfound = 0;
 *        start = System.currentTimeMillis();
 *        for (String name : names) {
 *             Destination dest = htns.lookup(name);
 *             if (dest != null)
 *                 found++;
 *             else
 *                 notfound++;
 *        }
 *        System.out.println("HTNS took " + DataHelper.formatDuration(System.currentTimeMillis() - start));
 *        System.out.println("found " + found + " notfound " + notfound);
 ***
 */
}
Also used : I2PAppContext(net.i2p.I2PAppContext) Properties(java.util.Properties)

Example 53 with I2PAppContext

use of net.i2p.I2PAppContext in project i2p.i2p by i2p.

the class Daemon method test.

/**
 * @since 0.9.26
 */
public static void test(String[] args) {
    Properties ctxProps = new Properties();
    String PROP_FORCE = "i2p.naming.blockfile.writeInAppContext";
    ctxProps.setProperty(PROP_FORCE, "true");
    I2PAppContext ctx = new I2PAppContext(ctxProps);
    NamingService ns = getNamingService("hosts.txt");
    File published = new File("test-published.txt");
    Log log = new Log(new File("test-log.txt"));
    SubscriptionList subscriptions = new SubscriptionList("test-sub.txt");
    update(ns, published, subscriptions, log);
    ctx.logManager().flush();
}
Also used : I2PAppContext(net.i2p.I2PAppContext) NamingService(net.i2p.client.naming.NamingService) SingleFileNamingService(net.i2p.client.naming.SingleFileNamingService) Properties(java.util.Properties) OrderedProperties(net.i2p.util.OrderedProperties) File(java.io.File)

Example 54 with I2PAppContext

use of net.i2p.I2PAppContext in project i2p.i2p-bote by i2p.

the class Util method decrypt.

/**
 * Decrypts data with an I2P private key
 * @throws DataFormatException
 */
public static byte[] decrypt(byte[] data, PrivateKey key) throws DataFormatException {
    I2PAppContext appContext = I2PAppContext.getGlobalContext();
    SessionKeyManager sessionKeyMgr = new net.i2p.crypto.SessionKeyManager(appContext) {
    };
    return appContext.elGamalAESEngine().decrypt(data, key, sessionKeyMgr);
}
Also used : I2PAppContext(net.i2p.I2PAppContext) SessionKeyManager(net.i2p.crypto.SessionKeyManager)

Example 55 with I2PAppContext

use of net.i2p.I2PAppContext in project i2p.i2p-bote by i2p.

the class EncryptedInputStream method readInputStream.

/**
 * If <code>cachedKey</code> is not <code>null</code>, this method assumes the
 * key has been generated from a valid password.
 * @param inputStream
 * @param password
 * @param cachedKey
 * @return the decrypted data
 * @throws IOException
 * @throws GeneralSecurityException
 * @throws PasswordException
 */
// for net.i2p.crypto.AESEngine
@SuppressWarnings("deprecation")
private byte[] readInputStream(InputStream inputStream, byte[] password, DerivedKey cachedKey) throws IOException, GeneralSecurityException, PasswordException {
    byte[] startOfFile = new byte[START_OF_FILE.length];
    inputStream.read(startOfFile);
    if (!Arrays.equals(START_OF_FILE, startOfFile))
        throw new IOException("Invalid header bytes: " + Arrays.toString(startOfFile) + ", expected: " + Arrays.toString(START_OF_FILE));
    int format = inputStream.read();
    if (format != FORMAT_VERSION)
        throw new IOException("Invalid file format identifier: " + format + ", expected: " + FORMAT_VERSION);
    SCryptParameters scryptParams = new SCryptParameters(inputStream);
    byte[] salt = new byte[SALT_LENGTH];
    inputStream.read(salt);
    // use the cached key if it is suitable, otherwise compute the key
    byte[] keyBytes;
    if (cachedKey != null && Arrays.equals(salt, cachedKey.salt) && scryptParams.equals(cachedKey.scryptParams))
        keyBytes = cachedKey.key;
    else
        keyBytes = FileEncryptionUtil.getEncryptionKey(password, salt, scryptParams);
    byte[] iv = new byte[BLOCK_SIZE];
    inputStream.read(iv);
    byte[] encryptedData = Util.readBytes(inputStream);
    SessionKey key = new SessionKey(keyBytes);
    I2PAppContext appContext = I2PAppContext.getGlobalContext();
    byte[] decryptedData = appContext.aes().safeDecrypt(encryptedData, key, iv);
    // null from safeDecrypt() means failure
    if (decryptedData == null)
        if (cachedKey == null)
            throw new PasswordException();
        else
            // we're assuming password and key are correct.
            throw new GeneralSecurityException("Can't decrypt using cached key.");
    return decryptedData;
}
Also used : I2PAppContext(net.i2p.I2PAppContext) SessionKey(net.i2p.data.SessionKey) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Aggregations

I2PAppContext (net.i2p.I2PAppContext)55 SessionKey (net.i2p.data.SessionKey)13 File (java.io.File)11 IOException (java.io.IOException)11 Properties (java.util.Properties)9 Test (org.junit.Test)7 Getopt (gnu.getopt.Getopt)5 ArrayList (java.util.ArrayList)5 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 InputStream (java.io.InputStream)3 DataFormatException (net.i2p.data.DataFormatException)3 Log (net.i2p.util.Log)3 SecureFileOutputStream (net.i2p.util.SecureFileOutputStream)3 Encoding (i2p.susi.webmail.encoding.Encoding)2 OutputStream (java.io.OutputStream)2 GeneralSecurityException (java.security.GeneralSecurityException)2 HashSet (java.util.HashSet)2 I2PSession (net.i2p.client.I2PSession)2 NamingService (net.i2p.client.naming.NamingService)2