beginning of format, updated imports. (shendaras)

This commit is contained in:
shendaras
2004-04-10 11:39:00 +00:00
committed by zzz
parent dbe5dea525
commit 8a8e68146f
233 changed files with 10086 additions and 8697 deletions

View File

@@ -1,7 +1,12 @@
package net.i2p.httptunnel;
import java.util.*;
import net.i2p.client.streaming.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
/**
* Produces SocketManagers in a thread and gives them to those who

View File

@@ -1,9 +1,11 @@
package net.i2p.httptunnel.filter;
import net.i2p.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.io.*;
import java.util.*;
import net.i2p.util.Log;
/**
* Chain multiple filters. Decorator pattern...

View File

@@ -50,7 +50,6 @@ import java.util.Set;
import java.util.StringTokenizer;
import net.i2p.I2PException;
import net.i2p.i2ptunnel.socks.I2PSOCKSTunnel;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.naming.NamingService;
@@ -58,6 +57,7 @@ import net.i2p.data.Base64;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.i2ptunnel.socks.I2PSOCKSTunnel;
import net.i2p.util.EventDispatcher;
import net.i2p.util.EventDispatcherImpl;
import net.i2p.util.Log;

View File

@@ -20,8 +20,8 @@ import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.client.streaming.I2PSocketOptions;
import net.i2p.data.Destination;
import net.i2p.util.EventDispatcher;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public abstract class I2PTunnelClientBase extends I2PTunnelTask
implements Runnable {

View File

@@ -13,9 +13,9 @@ import java.util.HashMap;
import net.i2p.client.I2PSession;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2PTunnelRunner extends I2PThread {
private final static Log _log = new Log(I2PTunnelRunner.class);

View File

@@ -11,7 +11,8 @@ import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import java.util.Iterator;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
@@ -22,8 +23,8 @@ import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.data.Base64;
import net.i2p.util.EventDispatcher;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2PTunnelServer extends I2PTunnelTask
implements Runnable {

View File

@@ -14,8 +14,8 @@ import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.data.Destination;
import net.i2p.util.EventDispatcher;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2Ping extends I2PTunnelTask implements Runnable {
private final static Log _log = new Log(I2Ping.class);

View File

@@ -3,15 +3,14 @@
*/
package net.i2p.i2ptunnel;
import net.i2p.util.Log;
import java.util.StringTokenizer;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.StringTokenizer;
import net.i2p.util.Log;
/**
* Runner thread that reads commands from the socket and fires off commands to

View File

@@ -8,14 +8,13 @@ package net.i2p.i2ptunnel.socks;
import java.net.Socket;
import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.client.streaming.I2PSocketOptions;
import net.i2p.data.DataFormatException;
import net.i2p.I2PException;
import net.i2p.i2ptunnel.I2PTunnel;
import net.i2p.util.Log;
/**

View File

@@ -1,10 +1,10 @@
package net.i2p.client.streaming;
import net.i2p.data.Destination;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.data.Destination;
/**
* Minimalistic adapter between the socket api and I2PTunnel's way.

View File

@@ -8,8 +8,8 @@ import java.io.OutputStream;
import net.i2p.I2PException;
import net.i2p.client.I2PSessionException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
* Initial stub implementation for the socket

View File

@@ -1,20 +1,19 @@
package net.i2p.client.streaming;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSessionException;
import net.i2p.I2PException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
/**
* Simplify the creation of I2PSession and transient I2P Destination objects if
* necessary to create a socket manager. This class is most likely how classes

View File

@@ -8,16 +8,16 @@ package net.i2p.phttprelay;
*
*/
import net.i2p.util.Log;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import net.i2p.util.Log;
abstract class PHTTPRelayServlet extends HttpServlet {
private Log _log = new Log(getClass());
protected String _baseDir;

View File

@@ -8,8 +8,15 @@
* Licensed unter GNU General Public License.
*/
import java.io.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
/**
* The main engine for the EchoTester.

View File

@@ -1,4 +1,5 @@
package net.i2p;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -13,8 +14,9 @@ package net.i2p;
*
*/
public class CoreVersion {
public final static String ID = "$Revision: 1.33 $ $Date: 2004/04/04 13:40:34 $";
public final static String ID = "$Revision: 1.1 $ $Date: 2004/04/07 23:48:42 $";
public final static String VERSION = "0.3.0.3";
public static void main(String args[]) {
System.out.println("I2P Core version: " + VERSION);
System.out.println("ID: " + ID);

View File

@@ -1,4 +1,5 @@
package net.i2p;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -22,27 +23,28 @@ public class I2PException extends Exception {
public I2PException() {
this(null, null);
}
public I2PException(String msg) {
this(msg, null);
}
public I2PException(String msg, Throwable source) {
super(msg);
_source = source;
}
public void printStackTrace() {
if (_source != null)
_source.printStackTrace();
if (_source != null) _source.printStackTrace();
super.printStackTrace();
}
public void printStackTrace(PrintStream ps) {
if (_source != null)
_source.printStackTrace(ps);
if (_source != null) _source.printStackTrace(ps);
super.printStackTrace(ps);
}
public void printStackTrace(PrintWriter pw) {
if (_source != null)
_source.printStackTrace(pw);
if (_source != null) _source.printStackTrace(pw);
super.printStackTrace(pw);
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -26,10 +27,10 @@ import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
import net.i2p.util.LogManager;
import net.i2p.util.Clock;
/**
* ATalk - anonymous talk, demonstrating a trivial I2P usage scenario.
@@ -59,18 +60,30 @@ public class ATalk implements I2PSessionListener, Runnable {
/** string that messages must begin with to be treated as files */
private final static String FILE_COMMAND = ".file: ";
/** the, erm, manual */
private final static String MANUAL =
"ATalk: Anonymous Talk, a demo program for the Invisible Internet Project SDK" + NL +
"To generate a new destination:" + NL +
"\tATalk [fileToSavePrivateKeyIn] [fileToSavePublicKeyIn]" + NL +
"To talk to another destination:" + NL +
"\tATalk [myPrivateKeyFile] [peerPublicKey] [shouldLogToScreen]" + NL +
"shouldLogToScreen is 'true' or 'false', depending on whether you want log info on the screen" + NL +
"When talking to another destination, messages are sent after you hit return" + NL +
"To send a file, send a message saying:" + NL +
"\t" + FILE_COMMAND + "[filenameToSend]" + NL +
"The peer will then recieve the file and be notified of where it has been saved" + NL +
"To end the talk session, enter a period on a line by itself and hit return" + NL;
private final static String MANUAL = "ATalk: Anonymous Talk, a demo program for the Invisible Internet Project SDK"
+ NL
+ "To generate a new destination:"
+ NL
+ "\tATalk [fileToSavePrivateKeyIn] [fileToSavePublicKeyIn]"
+ NL
+ "To talk to another destination:"
+ NL
+ "\tATalk [myPrivateKeyFile] [peerPublicKey] [shouldLogToScreen]"
+ NL
+ "shouldLogToScreen is 'true' or 'false', depending on whether you want log info on the screen"
+ NL
+ "When talking to another destination, messages are sent after you hit return"
+ NL
+ "To send a file, send a message saying:"
+ NL
+ "\t"
+ FILE_COMMAND
+ "[filenameToSend]"
+ NL
+ "The peer will then recieve the file and be notified of where it has been saved"
+ NL
+ "To end the talk session, enter a period on a line by itself and hit return"
+ NL;
public final static String PROP_CONFIG_LOCATION = "configFile";
private static final SimpleDateFormat _fmt = new SimpleDateFormat("hh:mm:ss.SSS");
@@ -98,12 +111,11 @@ public class ATalk implements I2PSessionListener, Runnable {
_log.warn("Unable to load up the ATalk config file " + configLocation);
}
// Provide any router or client API configuration here.
if (!props.containsKey(I2PClient.PROP_TCP_HOST))
props.setProperty(I2PClient.PROP_TCP_HOST, "localhost");
if (!props.containsKey(I2PClient.PROP_TCP_PORT))
props.setProperty(I2PClient.PROP_TCP_PORT, "7654");
if (!props.containsKey(I2PClient.PROP_TCP_HOST)) props.setProperty(I2PClient.PROP_TCP_HOST, "localhost");
if (!props.containsKey(I2PClient.PROP_TCP_PORT)) props.setProperty(I2PClient.PROP_TCP_PORT, "7654");
if (!props.containsKey(I2PClient.PROP_RELIABILITY))
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
props.setProperty(I2PClient.PROP_RELIABILITY,
I2PClient.PROP_RELIABILITY_BEST_EFFORT);
_session = client.createSession(new FileInputStream(myFile), props);
_session.setSessionListener(this);
_session.connect();
@@ -129,8 +141,7 @@ public class ATalk implements I2PSessionListener, Runnable {
while (true) {
String line = _in.readLine();
if ( (line == null) || (line.trim().length() <= 0) )
continue;
if ((line == null) || (line.trim().length() <= 0)) continue;
if (".".equals(line)) {
boolean ok = _session.sendMessage(_peerDestination, ("Peer disconnected at " + now()).getBytes());
// ignore ok, we're closing
@@ -163,8 +174,7 @@ public class ATalk implements I2PSessionListener, Runnable {
} finally {
try {
_log.debug("Exiting anonymous talk session");
if (_out != null)
_out.write("Exiting anonymous talk session");
if (_out != null) _out.write("Exiting anonymous talk session");
} catch (IOException ioe) {
// ignored
}
@@ -175,7 +185,10 @@ public class ATalk implements I2PSessionListener, Runnable {
// ignored
}
}
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
}
@@ -201,8 +214,7 @@ public class ATalk implements I2PSessionListener, Runnable {
try {
while (true) {
int len = fin.read(buf);
if (len == -1)
break;
if (len == -1) break;
baos.write(buf, 0, len);
}
} catch (IOException ioe) {
@@ -271,7 +283,8 @@ public class ATalk implements I2PSessionListener, Runnable {
fos.write(buf);
fos.close();
String name = firstline.substring(FILE_COMMAND.length());
_out.write("Recieved a file called [" + name + "] of size [" + lenToCopy + "] bytes, saved as [" + f.getAbsolutePath() + "]" + NL);
_out.write("Recieved a file called [" + name + "] of size [" + lenToCopy + "] bytes, saved as ["
+ f.getAbsolutePath() + "]" + NL);
_out.flush();
}
@@ -282,10 +295,14 @@ public class ATalk implements I2PSessionListener, Runnable {
String myDestinationFile = args[1];
boolean success = generateKeys(myKeyFile, myDestinationFile);
if (success)
_log.debug("Keys generated (private key file: " + myKeyFile + " destination file: " + myDestinationFile + ")");
_log.debug("Keys generated (private key file: " + myKeyFile + " destination file: " + myDestinationFile
+ ")");
else
_log.debug("Keys generation failed");
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
} else if (args.length == 3) {
_log.debug("Starting chat");
String myKeyfile = args[0];
@@ -300,7 +317,10 @@ public class ATalk implements I2PSessionListener, Runnable {
talkThread.start();
} else {
System.out.println(MANUAL);
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
System.exit(-1);
}
}
@@ -330,9 +350,17 @@ public class ATalk implements I2PSessionListener, Runnable {
}
/** required by {@link I2PSessionListener I2PSessionListener} to notify of disconnect */
public void disconnected(I2PSession session) { _log.debug("Disconnected"); }
/** required by {@link I2PSessionListener I2PSessionListener} to notify of error */
public void errorOccurred(I2PSession session, String message, Throwable error) { _log.debug("Error occurred: " + message, error); }
/** required by {@link I2PSessionListener I2PSessionListener} to notify of abuse */
public void reportAbuse(I2PSession session, int severity) { _log.debug("Abuse reported of severity " + severity); }
public void disconnected(I2PSession session) {
_log.debug("Disconnected");
}
/** required by {@link I2PSessionListener I2PSessionListener} to notify of error */
public void errorOccurred(I2PSession session, String message, Throwable error) {
_log.debug("Error occurred: " + message, error);
}
/** required by {@link I2PSessionListener I2PSessionListener} to notify of abuse */
public void reportAbuse(I2PSession session, int severity) {
_log.debug("Abuse reported of severity " + severity);
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,47 +9,42 @@ package net.i2p.client;
*
*/
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.I2CPMessageReader;
import net.i2p.data.i2cp.I2CPMessageException;
import net.i2p.data.i2cp.SessionStatusMessage;
import net.i2p.data.i2cp.SendMessageMessage;
import net.i2p.data.i2cp.CreateSessionMessage;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.data.i2cp.DisconnectMessage;
import net.i2p.data.i2cp.ReceiveMessageBeginMessage;
import net.i2p.data.i2cp.ReceiveMessageEndMessage;
import net.i2p.data.i2cp.MessagePayloadMessage;
import net.i2p.data.i2cp.RequestLeaseSetMessage;
import net.i2p.data.i2cp.SessionId;
import net.i2p.data.i2cp.MessageId;
import net.i2p.data.i2cp.SessionConfig;
import net.i2p.data.Destination;
import net.i2p.data.Payload;
import net.i2p.data.TunnelId;
import net.i2p.data.RouterIdentity;
import net.i2p.data.PublicKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.Certificate;
import net.i2p.crypto.KeyGenerator;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.Iterator;
import java.util.Date;
import java.net.Socket;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.crypto.KeyGenerator;
import net.i2p.data.Certificate;
import net.i2p.data.Destination;
import net.i2p.data.Payload;
import net.i2p.data.PublicKey;
import net.i2p.data.RouterIdentity;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.TunnelId;
import net.i2p.data.i2cp.CreateSessionMessage;
import net.i2p.data.i2cp.DisconnectMessage;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.I2CPMessageException;
import net.i2p.data.i2cp.I2CPMessageReader;
import net.i2p.data.i2cp.MessageId;
import net.i2p.data.i2cp.MessagePayloadMessage;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.data.i2cp.ReceiveMessageBeginMessage;
import net.i2p.data.i2cp.ReceiveMessageEndMessage;
import net.i2p.data.i2cp.RequestLeaseSetMessage;
import net.i2p.data.i2cp.SendMessageMessage;
import net.i2p.data.i2cp.SessionConfig;
import net.i2p.data.i2cp.SessionId;
import net.i2p.data.i2cp.SessionStatusMessage;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Run the server side of a connection as part of the TestServer. This class
@@ -86,15 +82,33 @@ class ConnectionRunner implements I2CPMessageReader.I2CPMessageEventListener {
private Object _sessionIdLock = new Object();
private Object _messageIdLock = new Object();
// this *should* be mod 65536, but UnsignedInteger is still b0rked. FIXME
protected int getNextSessionId() { synchronized (_sessionIdLock) { int id = (++_id)%32767; _id = id; return id; } }
protected int getNextSessionId() {
synchronized (_sessionIdLock) {
int id = (++_id) % 32767;
_id = id;
return id;
}
}
// this *should* be mod 65536, but UnsignedInteger is still b0rked. FIXME
protected int getNextMessageId() { synchronized (_messageIdLock) { int id = (++_messageId)%32767; _messageId = id; return id; } }
protected SessionId getSessionId() { return _sessionId; }
protected int getNextMessageId() {
synchronized (_messageIdLock) {
int id = (++_messageId) % 32767;
_messageId = id;
return id;
}
}
protected SessionId getSessionId() {
return _sessionId;
}
protected ConnectionRunner getRunner(Destination dest) {
return (ConnectionRunner) _connections.get(dest);
}
protected Set getRunnerDestinations() {
return new HashSet(_connections.keySet());
}
@@ -209,8 +223,12 @@ class ConnectionRunner implements I2CPMessageReader.I2CPMessageEventListener {
}
protected void sessionCreated() { }
protected SessionConfig getConfig() { return _config; }
protected void sessionCreated() {
}
protected SessionConfig getConfig() {
return _config;
}
/**
* Handle a SendMessageMessage
@@ -306,7 +324,8 @@ class ConnectionRunner implements I2CPMessageReader.I2CPMessageEventListener {
msg.setSessionId(_sessionId);
Payload payload = (Payload) _messages.get(message.getMessageId());
if (payload == null) {
_log.error("Payload for message id [" + message.getMessageId() + "] is null! Unknown message id?", new Exception("Error, null payload"));
_log.error("Payload for message id [" + message.getMessageId() + "] is null! Unknown message id?",
new Exception("Error, null payload"));
StringBuffer buf = new StringBuffer();
for (Iterator iter = _messages.keySet().iterator(); iter.hasNext();) {
buf.append("messageId: ").append(iter.next()).append(", ");
@@ -366,6 +385,7 @@ class ConnectionRunner implements I2CPMessageReader.I2CPMessageEventListener {
}
private Object _sendLock = new Object();
protected void doSend(I2CPMessage msg) throws I2CPMessageException, IOException {
synchronized (_sendLock) {
msg.writeMessage(_out);

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,7 +9,8 @@ package net.i2p.client;
*
*/
import net.i2p.data.i2cp.*;
import net.i2p.data.i2cp.DisconnectMessage;
import net.i2p.data.i2cp.I2CPMessage;
/**
* Handle I2CP disconnect messages from the router
@@ -19,6 +21,7 @@ class DisconnectMessageHandler extends HandlerImpl {
public DisconnectMessageHandler() {
super(DisconnectMessage.MESSAGE_TYPE);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
_log.debug("Handle message " + message);
session.destroySession(false);

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -18,9 +19,13 @@ import net.i2p.util.Log;
abstract class HandlerImpl implements I2CPMessageHandler {
protected Log _log;
private int _type;
public HandlerImpl(int type) {
_type = type;
_log = new Log(getClass());
}
public int getType() { return _type; }
public int getType() {
return _type;
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -17,5 +18,6 @@ import net.i2p.data.i2cp.I2CPMessage;
*/
interface I2CPMessageHandler {
public int getType();
public void handleMessage(I2CPMessage message, I2PSessionImpl session);
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -78,7 +79,8 @@ class I2CPMessageProducer {
* Package up and send the payload to the router for delivery
*
*/
public void sendMessage(I2PSessionImpl session, Destination dest, long nonce, byte[] payload, SessionTag tag, SessionKey key, Set tags, SessionKey newKey) throws I2PSessionException {
public void sendMessage(I2PSessionImpl session, Destination dest, long nonce, byte[] payload, SessionTag tag,
SessionKey key, Set tags, SessionKey newKey) throws I2PSessionException {
SendMessageMessage msg = new SendMessageMessage();
msg.setDestination(dest);
msg.setSessionId(session.getSessionId());
@@ -92,11 +94,10 @@ class I2CPMessageProducer {
* Create a new signed payload and send it off to the destination
*
*/
private Payload createPayload(Destination dest, byte[] payload, SessionTag tag, SessionKey key, Set tags, SessionKey newKey) throws I2PSessionException {
if (dest == null)
throw new I2PSessionException("No destination specified");
if (payload == null)
throw new I2PSessionException("No payload specified");
private Payload createPayload(Destination dest, byte[] payload, SessionTag tag, SessionKey key, Set tags,
SessionKey newKey) throws I2PSessionException {
if (dest == null) throw new I2PSessionException("No destination specified");
if (payload == null) throw new I2PSessionException("No payload specified");
Payload data = new Payload();
// randomize padding
@@ -106,7 +107,8 @@ class I2CPMessageProducer {
// generateNewTags would only generate tags if necessary
data.setEncryptedData(encr);
_log.debug("Encrypting the payload to public key " + dest.getPublicKey().toBase64() + "\nPayload: " + data.calculateHash());
_log.debug("Encrypting the payload to public key " + dest.getPublicKey().toBase64() + "\nPayload: "
+ data.calculateHash());
return data;
}
@@ -142,7 +144,8 @@ class I2CPMessageProducer {
* to the router
*
*/
public void createLeaseSet(I2PSessionImpl session, LeaseSet leaseSet, SigningPrivateKey signingPriv, PrivateKey priv) throws I2PSessionException {
public void createLeaseSet(I2PSessionImpl session, LeaseSet leaseSet, SigningPrivateKey signingPriv, PrivateKey priv)
throws I2PSessionException {
CreateLeaseSetMessage msg = new CreateLeaseSetMessage();
msg.setLeaseSet(leaseSet);
msg.setPrivateKey(priv);

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,16 +9,15 @@ package net.i2p.client;
*
*/
import net.i2p.I2PException;
import net.i2p.data.Destination;
import net.i2p.data.Certificate;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.data.Certificate;
import net.i2p.data.Destination;
/**
* Define the standard means of interacting with the I2P system
*

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,11 +9,16 @@ package net.i2p.client;
*
*/
import net.i2p.data.i2cp.*;
import net.i2p.util.Log;
import java.util.Map;
import java.util.HashMap;
import java.util.Map;
import net.i2p.data.i2cp.DisconnectMessage;
import net.i2p.data.i2cp.MessagePayloadMessage;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.data.i2cp.RequestLeaseSetMessage;
import net.i2p.data.i2cp.SessionStatusMessage;
import net.i2p.data.i2cp.SetDateMessage;
import net.i2p.util.Log;
/**
* Contains a map of message handlers that a session will want to use

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -11,8 +12,8 @@ package net.i2p.client;
import java.util.Set;
import net.i2p.data.Destination;
import net.i2p.data.SessionKey;
import net.i2p.data.PrivateKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SigningPrivateKey;
/**
@@ -30,6 +31,7 @@ public interface I2PSession {
* @return whether it was accepted by the router for delivery or not
*/
public boolean sendMessage(Destination dest, byte[] payload) throws I2PSessionException;
/**
* Like sendMessage above, except the key used and the tags sent are exposed to the
* application. <p />
@@ -57,7 +59,8 @@ public interface I2PSession {
* the contents of the set is ignored during the call, but afterwards it contains a set of SessionTag
* objects that were sent along side the given keyUsed.
*/
public boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent) throws I2PSessionException;
public boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent)
throws I2PSessionException;
/** Receive a message that the router has notified the client about, returning
* the payload.

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,8 +9,8 @@ package net.i2p.client;
*
*/
import net.i2p.util.Log;
import net.i2p.I2PException;
import net.i2p.util.Log;
/**
* Thrown when there is a problem doing something on the session
@@ -22,6 +23,7 @@ public class I2PSessionException extends I2PException {
public I2PSessionException(String msg, Throwable t) {
super(msg, t);
}
public I2PSessionException(String msg) {
super(msg);
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -137,7 +138,9 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
try {
_portNum = Integer.parseInt(portNum);
} catch (NumberFormatException nfe) {
if (_log.shouldLog(Log.WARN)) _log.warn("Invalid port number specified, defaulting to "+TestServer.LISTEN_PORT, nfe);
if (_log.shouldLog(Log.WARN))
_log.warn("Invalid port number specified, defaulting to "
+ TestServer.LISTEN_PORT, nfe);
_portNum = TestServer.LISTEN_PORT;
}
}
@@ -160,7 +163,12 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
} else if (key.startsWith("line")) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Skipping line.* property: " + key);
} else if ((key.length() > 255) || (val.length() > 255)) {
if (_log.shouldLog(Log.WARN)) _log.warn("Not passing on property [" + key + "] in the session configuration as the value is too long (max = 255): " + val);
if (_log.shouldLog(Log.WARN))
_log
.warn("Not passing on property ["
+ key
+ "] in the session configuration as the value is too long (max = 255): "
+ val);
} else {
rv.setProperty(key, val);
}
@@ -176,7 +184,10 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
}
}
}
LeaseSet getLeaseSet() { return _leaseSet; }
LeaseSet getLeaseSet() {
return _leaseSet;
}
/**
* Load up the destKeyFile for our Destination, PrivateKey, and SigningPrivateKey
@@ -220,8 +231,11 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
if (_log.shouldLog(Log.DEBUG)) _log.debug("After getDate / begin waiting for a response");
while (!_dateReceived) {
try {
synchronized (_dateReceivedLock) { _dateReceivedLock.wait(1000); }
} catch (InterruptedException ie) {}
synchronized (_dateReceivedLock) {
_dateReceivedLock.wait(1000);
}
} catch (InterruptedException ie) {
}
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("After received a SetDate response");
@@ -232,11 +246,17 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
// wait until we have created a lease set
while (_leaseSet == null) {
synchronized (_leaseSetWait) {
try { _leaseSetWait.wait(1000); } catch (InterruptedException ie) {}
try {
_leaseSetWait.wait(1000);
} catch (InterruptedException ie) {
}
}
}
long connected = Clock.getInstance().now();
if (_log.shouldLog(Log.INFO)) _log.info("Lease set created with inbound tunnels after " + (connected-startConnect) + "ms - ready to participate in the network!");
if (_log.shouldLog(Log.INFO))
_log.info("Lease set created with inbound tunnels after "
+ (connected - startConnect)
+ "ms - ready to participate in the network!");
} catch (UnknownHostException uhe) {
_closed = true;
throw new I2PSessionException("Invalid session configuration", uhe);
@@ -272,11 +292,16 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
*
*/
public abstract boolean sendMessage(Destination dest, byte[] payload) throws I2PSessionException;
public abstract boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent) throws I2PSessionException;
public abstract boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent)
throws I2PSessionException;
public abstract void receiveStatus(int msgId, long nonce, int status);
protected boolean isGuaranteed() {
return I2PClient.PROP_RELIABILITY_GUARANTEED.equals(_options.getProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED));
return I2PClient.PROP_RELIABILITY_GUARANTEED
.equals(_options.getProperty(I2PClient.PROP_RELIABILITY,
I2PClient.PROP_RELIABILITY_GUARANTEED));
}
protected static final Set createNewTags(int num) {
@@ -294,13 +319,14 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
final int id = msg.getMessageId().getMessageId();
byte data[] = msg.getPayload().getUnencryptedData();
if ((data == null) || (data.length <= 0)) {
if (_log.shouldLog(Log.ERROR)) _log.error("addNewMessage of a message with no unencrypted data", new Exception("Empty message"));
if (_log.shouldLog(Log.ERROR))
_log.error("addNewMessage of a message with no unencrypted data",
new Exception("Empty message"));
} else {
final long size = data.length;
Thread notifier = new I2PThread(new Runnable() {
public void run() {
if (_sessionListener != null)
_sessionListener.messageAvailable(I2PSessionImpl.this, id, size);
if (_sessionListener != null) _sessionListener.messageAvailable(I2PSessionImpl.this, id, size);
}
});
notifier.setName("Notifier [" + _sessionId + "/" + id + "]");
@@ -316,9 +342,13 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
public void messageReceived(I2CPMessageReader reader, I2CPMessage message) {
I2CPMessageHandler handler = I2PClientMessageHandlerMap.getHandler(message.getType());
if (handler == null) {
if (_log.shouldLog(Log.WARN)) _log.warn("Unknown message or unhandleable message received: type = " + message.getType());
if (_log.shouldLog(Log.WARN))
_log.warn("Unknown message or unhandleable message received: type = "
+ message.getType());
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Message received of type " + message.getType() + " to be handled by " + handler);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message received of type " + message.getType()
+ " to be handled by " + handler);
handler.handleMessage(message, this);
}
}
@@ -335,27 +365,45 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
/**
* Retrieve the destination of the session
*/
public Destination getMyDestination() { return _myDestination; }
public Destination getMyDestination() {
return _myDestination;
}
/**
* Retrieve the decryption PrivateKey
*/
public PrivateKey getDecryptionKey() { return _privateKey; }
public PrivateKey getDecryptionKey() {
return _privateKey;
}
/**
* Retrieve the signing SigningPrivateKey
*/
public SigningPrivateKey getPrivateKey() { return _signingPrivateKey; }
public SigningPrivateKey getPrivateKey() {
return _signingPrivateKey;
}
/**
* Retrieve the helper that generates I2CP messages
*/
I2CPMessageProducer getProducer() { return _producer; }
I2CPMessageProducer getProducer() {
return _producer;
}
/**
* Retrieve the configuration options
*/
Properties getOptions() { return _options; }
Properties getOptions() {
return _options;
}
/**
* Retrieve the session's ID
*/
SessionId getSessionId() { return _sessionId; }
SessionId getSessionId() {
return _sessionId;
}
/**
* Configure the session's ID
*/
@@ -364,10 +412,14 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
}
/** configure the listener */
public void setSessionListener(I2PSessionListener lsnr) { _sessionListener = lsnr; }
public void setSessionListener(I2PSessionListener lsnr) {
_sessionListener = lsnr;
}
/** has the session been closed (or not yet connected)? */
public boolean isClosed() { return _closed; }
public boolean isClosed() {
return _closed;
}
/**
* Deliver an I2CP message to the router
@@ -395,14 +447,16 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
*/
void propogateError(String msg, Throwable error) {
if (_log.shouldLog(Log.ERROR)) _log.error("Error occurred: " + msg, error);
if (_sessionListener != null)
_sessionListener.errorOccurred(this, msg, error);
if (_sessionListener != null) _sessionListener.errorOccurred(this, msg, error);
}
/**
* Tear down the session, and do NOT reconnect
*/
public void destroySession() { destroySession(true); }
public void destroySession() {
destroySession(true);
}
public void destroySession(boolean sendDisconnect) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Destroy the session", new Exception("DestroySession()"));
_closed = true;
@@ -414,8 +468,7 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
}
}
closeSocket();
if (_sessionListener != null)
_sessionListener.disconnected(this);
if (_sessionListener != null) _sessionListener.disconnected(this);
}
/**
@@ -425,8 +478,7 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
private void closeSocket() {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Closing the socket", new Exception("closeSocket"));
_closed = true;
if (_reader != null)
_reader.stopReading();
if (_reader != null) _reader.stopReading();
_reader = null;
if (_socket != null) {
@@ -459,9 +511,9 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
}
}
_log.error("Disconned from the router, and not trying to reconnect further. I hope you're not hoping anything else will happen");
if (_sessionListener != null)
_sessionListener.disconnected(this);
_log
.error("Disconned from the router, and not trying to reconnect further. I hope you're not hoping anything else will happen");
if (_sessionListener != null) _sessionListener.disconnected(this);
closeSocket();
}
@@ -469,13 +521,18 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
private final static int MAX_RECONNECT_ATTEMPTS = 1;
private final static int MAX_TOTAL_RECONNECT_ATTEMPTS = 3;
protected boolean shouldReconnect() { return true; }
protected boolean shouldReconnect() {
return true;
}
protected boolean reconnect() {
closeSocket();
if (_totalReconnectAttempts < MAX_TOTAL_RECONNECT_ATTEMPTS) {
_totalReconnectAttempts++;
} else {
if (_log.shouldLog(Log.CRIT)) _log.log(Log.CRIT, "Max number of reconnects exceeded [" + _totalReconnectAttempts + "], we give up!");
if (_log.shouldLog(Log.CRIT))
_log.log(Log.CRIT, "Max number of reconnects exceeded ["
+ _totalReconnectAttempts + "], we give up!");
return false;
}
if (_log.shouldLog(Log.INFO)) _log.info("Reconnecting...");

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -16,10 +17,10 @@ import java.util.Set;
import net.i2p.crypto.KeyGenerator;
import net.i2p.crypto.SessionKeyManager;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
import net.i2p.data.DataHelper;
import net.i2p.data.i2cp.MessageId;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.util.Clock;
@@ -52,7 +53,9 @@ class I2PSessionImpl2 extends I2PSessionImpl {
_sendingStates = new HashSet(32);
}
protected long getTimeout() { return SEND_TIMEOUT; }
protected long getTimeout() {
return SEND_TIMEOUT;
}
public void destroySession(boolean sendDisconnect) {
clearStates();
@@ -63,10 +66,10 @@ class I2PSessionImpl2 extends I2PSessionImpl {
return sendMessage(dest, payload, new SessionKey(), new HashSet(64));
}
public boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent) throws I2PSessionException {
public boolean sendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set tagsSent)
throws I2PSessionException {
if (isClosed()) throw new I2PSessionException("Already closed");
if (SHOULD_COMPRESS)
payload = DataHelper.compress(payload);
if (SHOULD_COMPRESS) payload = DataHelper.compress(payload);
if (isGuaranteed()) {
return sendGuaranteed(dest, payload, keyUsed, tagsSent);
} else {
@@ -85,11 +88,10 @@ class I2PSessionImpl2 extends I2PSessionImpl {
return compressed;
}
private boolean sendBestEffort(Destination dest, byte payload[], SessionKey keyUsed, Set tagsSent) throws I2PSessionException {
private boolean sendBestEffort(Destination dest, byte payload[], SessionKey keyUsed, Set tagsSent)
throws I2PSessionException {
SessionKey key = SessionKeyManager.getInstance().getCurrentKey(dest.getPublicKey());
if (key == null)
key = SessionKeyManager.getInstance().createSession(dest.getPublicKey());
if (key == null) key = SessionKeyManager.getInstance().createSession(dest.getPublicKey());
SessionTag tag = SessionKeyManager.getInstance().consumeNextAvailableTag(dest.getPublicKey(), key);
Set sentTags = null;
if (SessionKeyManager.getInstance().getAvailableTags(dest.getPublicKey(), key) < 10) {
@@ -126,29 +128,39 @@ class I2PSessionImpl2 extends I2PSessionImpl {
synchronized (_sendingStates) {
_sendingStates.add(state);
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("Adding sending state " + state.getMessageId() + " / " + state.getNonce());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Adding sending state " + state.getMessageId() + " / "
+ state.getNonce());
_producer.sendMessage(this, dest, nonce, payload, tag, key, sentTags, newKey);
state.waitFor(MessageStatusMessage.STATUS_SEND_ACCEPTED, Clock.getInstance().now() + getTimeout());
synchronized (_sendingStates) {
_sendingStates.remove(state);
}
boolean found = state.received(MessageStatusMessage.STATUS_SEND_ACCEPTED);
if (_log.shouldLog(Log.DEBUG)) _log.debug("After waitFor sending state " + state.getMessageId().getMessageId() + " / " + state.getNonce() + " found = " + found);
if (_log.shouldLog(Log.DEBUG))
_log.debug("After waitFor sending state " + state.getMessageId().getMessageId()
+ " / " + state.getNonce() + " found = " + found);
if (found) {
if (_log.shouldLog(Log.INFO)) _log.info("Message sent after " + state.getElapsed() + "ms with " + payload.length + " bytes");
if (_log.shouldLog(Log.INFO))
_log.info("Message sent after " + state.getElapsed() + "ms with "
+ payload.length + " bytes");
} else {
if (_log.shouldLog(Log.INFO)) _log.info("Message send failed after " + state.getElapsed() + "ms with " + payload.length + " bytes");
if (_log.shouldLog(Log.ERROR)) _log.error("Never received *accepted* from the router! dropping and reconnecting");
if (_log.shouldLog(Log.INFO))
_log.info("Message send failed after " + state.getElapsed() + "ms with "
+ payload.length + " bytes");
if (_log.shouldLog(Log.ERROR))
_log
.error("Never received *accepted* from the router! dropping and reconnecting");
disconnect();
return false;
}
return found;
}
private boolean sendGuaranteed(Destination dest, byte payload[], SessionKey keyUsed, Set tagsSent) throws I2PSessionException {
private boolean sendGuaranteed(Destination dest, byte payload[], SessionKey keyUsed, Set tagsSent)
throws I2PSessionException {
SessionKey key = SessionKeyManager.getInstance().getCurrentKey(dest.getPublicKey());
if (key == null)
key = SessionKeyManager.getInstance().createSession(dest.getPublicKey());
if (key == null) key = SessionKeyManager.getInstance().createSession(dest.getPublicKey());
SessionTag tag = SessionKeyManager.getInstance().consumeNextAvailableTag(dest.getPublicKey(), key);
Set sentTags = null;
if (SessionKeyManager.getInstance().getAvailableTags(dest.getPublicKey(), key) < 10) {
@@ -182,11 +194,12 @@ class I2PSessionImpl2 extends I2PSessionImpl {
}
}
synchronized (_sendingStates) {
_sendingStates.add(state);
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("Adding sending state " + state.getMessageId() + " / " + state.getNonce());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Adding sending state " + state.getMessageId() + " / "
+ state.getNonce());
_producer.sendMessage(this, dest, nonce, payload, tag, key, sentTags, newKey);
state.waitFor(MessageStatusMessage.STATUS_SEND_GUARANTEED_SUCCESS, Clock.getInstance().now() + SEND_TIMEOUT);
synchronized (_sendingStates) {
@@ -196,37 +209,53 @@ class I2PSessionImpl2 extends I2PSessionImpl {
boolean accepted = state.received(MessageStatusMessage.STATUS_SEND_ACCEPTED);
if ((!accepted) || (state.getMessageId() == null)) {
if (_log.shouldLog(Log.ERROR)) _log.error("State with nonce " + state.getNonce() + " was not accepted? (no messageId!!)");
if (_log.shouldLog(Log.ERROR))
_log.error("State with nonce " + state.getNonce()
+ " was not accepted? (no messageId!!)");
nackTags(state);
if (_log.shouldLog(Log.CRIT)) _log.log(Log.CRIT,"Disconnecting/reconnecting because we never were accepted!");
if (_log.shouldLog(Log.CRIT))
_log.log(Log.CRIT,
"Disconnecting/reconnecting because we never were accepted!");
disconnect();
return false;
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("After waitFor sending state " + state.getMessageId().getMessageId() + " / " + state.getNonce() + " found = " + found);
if (_log.shouldLog(Log.DEBUG))
_log.debug("After waitFor sending state " + state.getMessageId().getMessageId()
+ " / " + state.getNonce() + " found = " + found);
if (found) {
if (_log.shouldLog(Log.INFO)) _log.info("Message sent after " + state.getElapsed() + "ms with " + payload.length + " bytes");
if (_log.shouldLog(Log.INFO))
_log.info("Message sent after " + state.getElapsed() + "ms with "
+ payload.length + " bytes");
ackTags(state);
} else {
if (_log.shouldLog(Log.INFO)) _log.info("Message send failed after " + state.getElapsed() + "ms with " + payload.length + " bytes");
if (_log.shouldLog(Log.INFO))
_log.info("Message send failed after " + state.getElapsed() + "ms with "
+ payload.length + " bytes");
nackTags(state);
}
return found;
}
private void ackTags(MessageState state) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("ack tags for msgId " + state.getMessageId() + " / " + state.getNonce() + " key = " + state.getKey() + ", tags = " + state.getTags());
if (_log.shouldLog(Log.DEBUG))
_log.debug("ack tags for msgId " + state.getMessageId() + " / "
+ state.getNonce() + " key = " + state.getKey() + ", tags = "
+ state.getTags());
if ((state.getTags() != null) && (state.getTags().size() > 0)) {
if (state.getNewKey() == null)
SessionKeyManager.getInstance().tagsDelivered(state.getTo().getPublicKey(), state.getKey(), state.getTags());
SessionKeyManager.getInstance().tagsDelivered(state.getTo().getPublicKey(), state.getKey(),
state.getTags());
else
SessionKeyManager.getInstance().tagsDelivered(state.getTo().getPublicKey(), state.getNewKey(), state.getTags());
SessionKeyManager.getInstance().tagsDelivered(state.getTo().getPublicKey(), state.getNewKey(),
state.getTags());
}
}
private void nackTags(MessageState state) {
if (_log.shouldLog(Log.INFO)) _log.info("nack tags for msgId " + state.getMessageId() + " / " + state.getNonce() + " key = " + state.getKey());
if (_log.shouldLog(Log.INFO))
_log.info("nack tags for msgId " + state.getMessageId() + " / " + state.getNonce()
+ " key = " + state.getKey());
SessionKeyManager.getInstance().failTags(state.getTo().getPublicKey());
}
@@ -258,7 +287,9 @@ class I2PSessionImpl2 extends I2PSessionImpl {
}
state.receive(status);
} else {
if (_log.shouldLog(Log.INFO)) _log.info("No matching state for messageId " + msgId + " / " + nonce + " w/ status = " + status);
if (_log.shouldLog(Log.INFO))
_log.info("No matching state for messageId " + msgId + " / " + nonce
+ " w/ status = " + status);
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -27,6 +28,7 @@ class MessagePayloadMessageHandler extends HandlerImpl {
public MessagePayloadMessageHandler() {
super(MessagePayloadMessage.MESSAGE_TYPE);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
_log.debug("Handle message " + message);
try {
@@ -53,7 +55,9 @@ class MessagePayloadMessageHandler extends HandlerImpl {
Payload payload = msg.getPayload();
byte[] data = ElGamalAESEngine.decrypt(payload.getEncryptedData(), session.getDecryptionKey());
if (data == null) {
_log.error("Error decrypting the payload to public key " + session.getMyDestination().getPublicKey().toBase64() + "\nPayload: " + payload.calculateHash());
_log
.error("Error decrypting the payload to public key "
+ session.getMyDestination().getPublicKey().toBase64() + "\nPayload: " + payload.calculateHash());
throw new DataFormatException("Unable to decrypt the payload");
}
payload.setUnencryptedData(data);

View File

@@ -1,18 +1,17 @@
package net.i2p.client;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.i2p.data.Destination;
import net.i2p.data.SessionKey;
import net.i2p.data.i2cp.MessageId;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.data.SessionKey;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import net.i2p.util.Log;
/**
* Contains the state of a payload message being sent to a peer
@@ -30,6 +29,7 @@ class MessageState {
private boolean _cancelled;
private long _created;
private Object _lock = new Object();
public MessageState(long nonce) {
_nonce = nonce;
_id = null;
@@ -41,6 +41,7 @@ class MessageState {
_to = null;
_created = Clock.getInstance().now();
}
public void receive(int status) {
synchronized (_receivedStatus) {
_receivedStatus.add(new Integer(status));
@@ -50,22 +51,54 @@ class MessageState {
}
}
public void setMessageId(MessageId id) { _id = id; }
public MessageId getMessageId() { return _id; }
public long getNonce() { return _nonce; }
public void setMessageId(MessageId id) {
_id = id;
}
public MessageId getMessageId() {
return _id;
}
public long getNonce() {
return _nonce;
}
public void setKey(SessionKey key) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Setting key [" + _key + "] to [" + key + "]");
_key = key;
}
public SessionKey getKey() { return _key; }
public void setNewKey(SessionKey key) { _newKey = key; }
public SessionKey getNewKey() { return _newKey; }
public void setTags(Set tags) { _tags = tags; }
public Set getTags() { return _tags; }
public void setTo(Destination dest) { _to = dest; }
public Destination getTo() { return _to; }
public long getElapsed() { return Clock.getInstance().now() - _created; }
public SessionKey getKey() {
return _key;
}
public void setNewKey(SessionKey key) {
_newKey = key;
}
public SessionKey getNewKey() {
return _newKey;
}
public void setTags(Set tags) {
_tags = tags;
}
public Set getTags() {
return _tags;
}
public void setTo(Destination dest) {
_to = dest;
}
public Destination getTo() {
return _to;
}
public long getElapsed() {
return Clock.getInstance().now() - _created;
}
public void waitFor(int status, long expiration) {
while (true) {
@@ -85,7 +118,8 @@ class MessageState {
synchronized (_lock) {
try {
_lock.wait(timeToWait);
} catch (InterruptedException ie) {}
} catch (InterruptedException ie) {
}
}
}
}
@@ -105,32 +139,44 @@ class MessageState {
int recv = val.intValue();
switch (recv) {
case MessageStatusMessage.STATUS_SEND_BEST_EFFORT_FAILURE:
if (_log.shouldLog(Log.WARN)) _log.warn("Received best effort failure after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.WARN))
_log.warn("Received best effort failure after " + getElapsed() + " from "
+ this.toString());
rv = false;
break;
case MessageStatusMessage.STATUS_SEND_GUARANTEED_FAILURE:
if (_log.shouldLog(Log.WARN)) _log.warn("Received guaranteed failure after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.WARN))
_log.warn("Received guaranteed failure after " + getElapsed() + " from "
+ this.toString());
rv = false;
break;
case MessageStatusMessage.STATUS_SEND_ACCEPTED:
if (wantedStatus == MessageStatusMessage.STATUS_SEND_ACCEPTED) {
return true; // if we're only looking for accepted, take it directly (don't let any GUARANTEED_* override it)
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Got accepted, but we're waiting for more from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Got accepted, but we're waiting for more from "
+ this.toString());
continue;
// ignore accepted, as we want something better
}
case MessageStatusMessage.STATUS_SEND_BEST_EFFORT_SUCCESS:
if (_log.shouldLog(Log.DEBUG)) _log.debug("Received best effort success after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Received best effort success after " + getElapsed()
+ " from " + this.toString());
if (wantedStatus == recv) {
rv = true;
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Not guaranteed success, but best effort after " + getElapsed() + " will do... from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not guaranteed success, but best effort after "
+ getElapsed() + " will do... from " + this.toString());
rv = true;
}
break;
case MessageStatusMessage.STATUS_SEND_GUARANTEED_SUCCESS:
if (_log.shouldLog(Log.DEBUG)) _log.debug("Received guaranteed success after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Received guaranteed success after " + getElapsed() + " from "
+ this.toString());
// even if we're waiting for best effort success, guaranteed is good enough
rv = true;
break;
@@ -142,6 +188,7 @@ class MessageState {
}
return rv;
}
private boolean isFailure(int wantedStatus) {
List received = null;
synchronized (_receivedStatus) {
@@ -156,33 +203,45 @@ class MessageState {
int recv = val.intValue();
switch (recv) {
case MessageStatusMessage.STATUS_SEND_BEST_EFFORT_FAILURE:
if (_log.shouldLog(Log.DEBUG)) _log.warn("Received best effort failure after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.warn("Received best effort failure after " + getElapsed() + " from "
+ this.toString());
rv = true;
break;
case MessageStatusMessage.STATUS_SEND_GUARANTEED_FAILURE:
if (_log.shouldLog(Log.DEBUG)) _log.warn("Received guaranteed failure after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.warn("Received guaranteed failure after " + getElapsed() + " from "
+ this.toString());
rv = true;
break;
case MessageStatusMessage.STATUS_SEND_ACCEPTED:
if (wantedStatus == MessageStatusMessage.STATUS_SEND_ACCEPTED) {
rv = false;
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Got accepted, but we're waiting for more from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Got accepted, but we're waiting for more from "
+ this.toString());
continue;
// ignore accepted, as we want something better
}
break;
case MessageStatusMessage.STATUS_SEND_BEST_EFFORT_SUCCESS:
if (_log.shouldLog(Log.DEBUG)) _log.debug("Received best effort success after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Received best effort success after " + getElapsed()
+ " from " + this.toString());
if (wantedStatus == recv) {
rv = false;
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Not guaranteed success, but best effort after " + getElapsed() + " will do... from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not guaranteed success, but best effort after "
+ getElapsed() + " will do... from " + this.toString());
rv = false;
}
break;
case MessageStatusMessage.STATUS_SEND_GUARANTEED_SUCCESS:
if (_log.shouldLog(Log.DEBUG)) _log.debug("Received guaranteed success after " + getElapsed() + " from " + this.toString());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Received guaranteed success after " + getElapsed() + " from "
+ this.toString());
// even if we're waiting for best effort success, guaranteed is good enough
rv = false;
break;
@@ -199,6 +258,7 @@ class MessageState {
public boolean received(int status) {
return isSuccess(status);
}
public void cancel() {
_cancelled = true;
synchronized (_lock) {

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,7 +9,9 @@ package net.i2p.client;
*
*/
import net.i2p.data.i2cp.*;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.MessageStatusMessage;
import net.i2p.data.i2cp.ReceiveMessageBeginMessage;
/**
* Handle I2CP MessageStatusMessages from the router. This currently only takes
@@ -21,10 +24,12 @@ class MessageStatusMessageHandler extends HandlerImpl {
public MessageStatusMessageHandler() {
super(MessageStatusMessage.MESSAGE_TYPE);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
boolean skipStatus = true;
if (I2PClient.PROP_RELIABILITY_GUARANTEED.equals(session.getOptions().getProperty(
I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT)))
if (I2PClient.PROP_RELIABILITY_GUARANTEED.equals(session.getOptions()
.getProperty(I2PClient.PROP_RELIABILITY,
I2PClient.PROP_RELIABILITY_BEST_EFFORT)))
skipStatus = false;
_log.debug("Handle message " + message);
MessageStatusMessage msg = (MessageStatusMessage) message;

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -38,6 +39,7 @@ class RequestLeaseSetMessageHandler extends HandlerImpl {
super(RequestLeaseSetMessage.MESSAGE_TYPE);
_existingLeaseSets = new HashMap(32);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
_log.debug("Handle message " + message);
RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message;
@@ -98,26 +100,34 @@ class RequestLeaseSetMessageHandler extends HandlerImpl {
_signingPubKey = (SigningPublicKey) signKeys[0];
_signingPrivKey = (SigningPrivateKey) signKeys[1];
}
public PublicKey getPublicKey() { return _pubKey; }
public PrivateKey getPrivateKey() { return _privKey; }
public SigningPublicKey getSigningPublicKey() { return _signingPubKey; }
public SigningPrivateKey getSigningPrivateKey() { return _signingPrivKey; }
public PublicKey getPublicKey() {
return _pubKey;
}
public PrivateKey getPrivateKey() {
return _privKey;
}
public SigningPublicKey getSigningPublicKey() {
return _signingPubKey;
}
public SigningPrivateKey getSigningPrivateKey() {
return _signingPrivKey;
}
public int hashCode() {
return DataHelper.hashCode(_pubKey) +
7*DataHelper.hashCode(_privKey) +
7*7*DataHelper.hashCode(_signingPubKey) +
7*7*7*DataHelper.hashCode(_signingPrivKey);
return DataHelper.hashCode(_pubKey) + 7 * DataHelper.hashCode(_privKey) + 7 * 7
* DataHelper.hashCode(_signingPubKey) + 7 * 7 * 7 * DataHelper.hashCode(_signingPrivKey);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof LeaseInfo) )
return false;
if ((obj == null) || !(obj instanceof LeaseInfo)) return false;
LeaseInfo li = (LeaseInfo) obj;
return DataHelper.eq(_pubKey, li.getPublicKey()) &&
DataHelper.eq(_privKey, li.getPrivateKey()) &&
DataHelper.eq(_signingPubKey, li.getSigningPublicKey()) &&
DataHelper.eq(_signingPrivKey, li.getSigningPrivateKey());
return DataHelper.eq(_pubKey, li.getPublicKey()) && DataHelper.eq(_privKey, li.getPrivateKey())
&& DataHelper.eq(_signingPubKey, li.getSigningPublicKey())
&& DataHelper.eq(_signingPrivKey, li.getSigningPrivateKey());
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,7 +9,8 @@ package net.i2p.client;
*
*/
import net.i2p.data.i2cp.*;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.SessionStatusMessage;
/**
* Handle I2CP SessionStatusMessagese from the router, updating the session as
@@ -20,6 +22,7 @@ class SessionStatusMessageHandler extends HandlerImpl {
public SessionStatusMessageHandler() {
super(SessionStatusMessage.MESSAGE_TYPE);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
_log.debug("Handle message " + message);
SessionStatusMessage msg = (SessionStatusMessage) message;

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,7 +9,8 @@ package net.i2p.client;
*
*/
import net.i2p.data.i2cp.*;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.SetDateMessage;
import net.i2p.util.Clock;
/**
@@ -20,6 +22,7 @@ class SetDateMessageHandler extends HandlerImpl {
public SetDateMessageHandler() {
super(SetDateMessage.MESSAGE_TYPE);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
_log.debug("Handle message " + message);
SetDateMessage msg = (SetDateMessage) message;

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -61,19 +62,30 @@ public class TestClient implements I2PSessionListener {
// wait until the other one is connected
while ((_dest1 == null) || (_dest2 == null))
try { Thread.sleep(500); } catch (InterruptedException ie) {}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
if (isDest1) {
Destination otherD = (isDest1 ? _dest2 : _dest1);
boolean accepted = session.sendMessage(otherD, ("Hello other side. I am" + (isDest1 ? "" : " NOT") + " dest1").getBytes());
boolean accepted = session
.sendMessage(
otherD,
("Hello other side. I am" + (isDest1 ? "" : " NOT") + " dest1")
.getBytes());
} else {
while (_stillRunning) {
try {
_log.debug("waiting for a message...");
Thread.sleep(1000);
} catch (InterruptedException ie) {}
} catch (InterruptedException ie) {
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
System.exit(0);
}
//session.destroySession();
@@ -84,11 +96,23 @@ public class TestClient implements I2PSessionListener {
public static void main(String args[]) {
doTest();
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) {
}
}
static void doTest() {
Thread test1 = new I2PThread(new Runnable() { public void run() { (new TestClient()).runTest("test1.keyfile", true); } } );
Thread test2 = new I2PThread(new Runnable() { public void run() { (new TestClient()).runTest("test2.keyfile", false); } } );
Thread test1 = new I2PThread(new Runnable() {
public void run() {
(new TestClient()).runTest("test1.keyfile", true);
}
});
Thread test2 = new I2PThread(new Runnable() {
public void run() {
(new TestClient()).runTest("test2.keyfile", false);
}
});
test1.start();
test2.start();
_log.debug("Test threads started");

View File

@@ -1,4 +1,5 @@
package net.i2p.client;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -28,7 +29,9 @@ public class TestServer implements Runnable {
private ServerSocket _socket;
public static int LISTEN_PORT = 7654;
protected void setPort(int port) { LISTEN_PORT = port; }
protected void setPort(int port) {
LISTEN_PORT = port;
}
/**
* Start up the socket listener, listens for connections, and
@@ -63,7 +66,9 @@ public class TestServer implements Runnable {
runner.doYourThing();
}
public void run() { runServer(); }
public void run() {
runServer();
}
/**
* Fire up the router

View File

@@ -35,8 +35,7 @@ public class HostsTxtNamingService extends NamingService {
// Try to look it up in hosts.txt
// Reload file each time to catch changes.
// (and it's easier :P
String hostsfile=System.getProperty(PROP_HOSTS_FILE,
DEFAULT_HOSTS_FILE );
String hostsfile = System.getProperty(PROP_HOSTS_FILE, DEFAULT_HOSTS_FILE);
Properties hosts = new Properties();
FileInputStream fis = null;
try {
@@ -50,7 +49,10 @@ public class HostsTxtNamingService extends NamingService {
} catch (Exception ioe) {
_log.error("Error loading hosts file " + hostsfile, ioe);
} finally {
if (fis != null) try {fis.close();} catch (IOException ioe) {}
if (fis != null) try {
fis.close();
} catch (IOException ioe) {
}
}
String res = hosts.getProperty(hostname);
// If we can't find name in hosts, assume it's a key.

View File

@@ -19,8 +19,7 @@ public abstract class NamingService {
private final static Log _log = new Log(NamingService.class);
private static final String PROP_IMPL = "i2p.naming.impl";
private static final String DEFAULT_IMPL=
"net.i2p.client.naming.HostsTxtNamingService";
private static final String DEFAULT_IMPL = "net.i2p.client.naming.HostsTxtNamingService";
/**
* Look up a host name.
@@ -48,8 +47,7 @@ public abstract class NamingService {
result.fromBase64(hostname);
return result;
} catch (DataFormatException dfe) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error translating [" + hostname + "]", dfe);
if (_log.shouldLog(Log.WARN)) _log.warn("Error translating [" + hostname + "]", dfe);
return null;
}
}
@@ -64,8 +62,7 @@ public abstract class NamingService {
*/
public static synchronized NamingService getInstance() {
if (instance == null) {
String impl = System.getProperty(PROP_IMPL,
DEFAULT_IMPL);
String impl = System.getProperty(PROP_IMPL, DEFAULT_IMPL);
try {
instance = (NamingService) Class.forName(impl).newInstance();
} catch (Exception ex) {

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,17 +9,17 @@ package net.i2p.crypto;
*
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import net.i2p.data.DataFormatException;
import net.i2p.data.SessionKey;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.util.Log;
import net.i2p.util.RandomSource;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
/**
* Wrapper singleton for AES cypher operation.
*
@@ -33,7 +34,10 @@ public class AESEngine {
else
_engine = new CryptixAESEngine();
}
public static AESEngine getInstance() { return _engine; }
public static AESEngine getInstance() {
return _engine;
}
/** Encrypt the payload with the session key
* @param payload data to be encrypted
@@ -42,8 +46,8 @@ public class AESEngine {
* @return encrypted data
*/
public byte[] encrypt(byte payload[], SessionKey sessionKey, byte initializationVector[]) {
if ( (initializationVector == null) || (payload == null) || (sessionKey == null) || (initializationVector.length != 16) )
return null;
if ((initializationVector == null) || (payload == null) || (sessionKey == null)
|| (initializationVector.length != 16)) return null;
byte cyphertext[] = new byte[payload.length + (16 - (payload.length % 16))];
_log.warn("Warning: AES is disabled");
@@ -52,8 +56,7 @@ public class AESEngine {
}
public byte[] safeEncrypt(byte payload[], SessionKey sessionKey, byte iv[], int paddedSize) {
if ( (iv == null) || (payload == null) || (sessionKey == null) || (iv.length != 16) )
return null;
if ((iv == null) || (payload == null) || (sessionKey == null) || (iv.length != 16)) return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(paddedSize + 64);
Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
@@ -74,8 +77,7 @@ public class AESEngine {
}
public byte[] safeDecrypt(byte payload[], SessionKey sessionKey, byte iv[]) {
if ( (iv == null) || (payload == null) || (sessionKey == null) || (iv.length != 16) )
return null;
if ((iv == null) || (payload == null) || (sessionKey == null) || (iv.length != 16)) return null;
byte decr[] = decrypt(payload, sessionKey, iv);
if (decr == null) {
@@ -88,7 +90,8 @@ public class AESEngine {
Hash rh = new Hash();
rh.readBytes(bais);
if (!h.equals(rh)) {
_log.error("Hash does not match [key=" + sessionKey + " / iv =" + DataHelper.toString(iv, iv.length) + "]", new Exception("Hash error"));
_log.error("Hash does not match [key=" + sessionKey + " / iv =" + DataHelper.toString(iv, iv.length)
+ "]", new Exception("Hash error"));
return null;
}
long len = DataHelper.readLong(bais, 4);
@@ -108,7 +111,6 @@ public class AESEngine {
}
}
/** decrypt the data with the session key provided
* @param cyphertext encrypted data
* @param sessionKey private session key
@@ -116,8 +118,8 @@ public class AESEngine {
* @return unencrypted data
*/
public byte[] decrypt(byte cyphertext[], SessionKey sessionKey, byte initializationVector[]) {
if ( (initializationVector == null) || (cyphertext == null) || (sessionKey == null) || (initializationVector.length != 16) )
return null;
if ((initializationVector == null) || (cyphertext == null) || (sessionKey == null)
|| (initializationVector.length != 16)) return null;
byte payload[] = new byte[cyphertext.length];
_log.warn("Warning: AES is disabled");

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -20,8 +21,8 @@ import net.i2p.data.Base64;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.RandomSource;
/**
@@ -74,7 +75,8 @@ public class AESInputStream extends FilterInputStream {
if (_eofFound)
return -1;
else {
throw new IOException("Not EOF, but none available? " + _readyBuf.size() + "/" + _encryptedBuf.size() + "/" + _cumulativeRead + "... impossible");
throw new IOException("Not EOF, but none available? " + _readyBuf.size() + "/" + _encryptedBuf.size()
+ "/" + _cumulativeRead + "... impossible");
}
}
}
@@ -99,21 +101,23 @@ public class AESInputStream extends FilterInputStream {
public int read(byte dest[], int off, int len) throws IOException {
byte buf[] = new byte[len];
int read = read(buf);
if (read == -1)
return -1;
if (read == -1) return -1;
System.arraycopy(buf, 0, dest, off, read);
return read;
}
public long skip(long numBytes) throws IOException {
for (long l = 0; l < numBytes; l++) {
int val = read();
if (val == -1)
return l;
if (val == -1) return l;
}
return numBytes;
}
public int available() throws IOException { return _readyBuf.size(); }
public int available() throws IOException {
return _readyBuf.size();
}
public void close() throws IOException {
//_log.debug("We have " + _encryptedBuf.size() + " available to decrypt... doing so");
//decrypt();
@@ -126,12 +130,21 @@ public class AESInputStream extends FilterInputStream {
_readyBuf.clear();
_encryptedBuf.reset();
in.close();
_log.debug("Cumulative bytes read from source/decrypted/stripped: " + _cumulativeRead + "/"+_cumulativePrepared +"/" + _cumulativePaddingStripped + "] remaining [" + ready + " ready, " + encrypted + " still encrypted]");
_log.debug("Cumulative bytes read from source/decrypted/stripped: " + _cumulativeRead + "/"
+ _cumulativePrepared + "/" + _cumulativePaddingStripped + "] remaining [" + ready + " ready, "
+ encrypted + " still encrypted]");
}
public void mark(int readLimit) {}
public void reset() throws IOException { throw new IOException("Reset not supported"); }
public boolean markSupported() { return false; }
public void mark(int readLimit) {
}
public void reset() throws IOException {
throw new IOException("Reset not supported");
}
public boolean markSupported() {
return false;
}
/**
* Retrieve the next ready byte, or null if no bytes are ready. this does not refill or block
@@ -201,7 +214,8 @@ public class AESInputStream extends FilterInputStream {
byte nencrypted[] = new byte[encrypted.length - trailing];
System.arraycopy(encrypted, 0, nencrypted, 0, nencrypted.length);
encrypted = nencrypted;
_log.warn("Decrypt got odd segment - " + trailing + " bytes pushed back for later decryption - corrupted or slow data stream perhaps?");
_log.warn("Decrypt got odd segment - " + trailing
+ " bytes pushed back for later decryption - corrupted or slow data stream perhaps?");
} else {
//_log.info(encrypted.length + " bytes makes up " + numBlocks + " blocks to decrypt normally");
}
@@ -227,8 +241,14 @@ public class AESInputStream extends FilterInputStream {
int remaining = encrypted.length % BLOCK_SIZE;
if (remaining != 0) {
_encryptedBuf.write(encrypted, encrypted.length - remaining, remaining);
_log.debug("After pushing " + remaining + " bytes back onto the buffer, lets delay 1s our action so we don't fast busy until the net transfers data");
try { Thread.sleep(1000); } catch (InterruptedException ie) {}
_log
.debug("After pushing "
+ remaining
+ " bytes back onto the buffer, lets delay 1s our action so we don't fast busy until the net transfers data");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
} else {
//_log.debug("No remaining encrypted bytes beyond the block size");
}
@@ -250,15 +270,13 @@ public class AESInputStream extends FilterInputStream {
*/
private int[] stripPadding(byte data[]) throws IOException {
int numPadBytes = (int) data[data.length - 1];
if ( (numPadBytes >= data.length) || (numPadBytes <= 0) )
throw new IOException("Invalid number of pad bytes");
if ((numPadBytes >= data.length) || (numPadBytes <= 0)) throw new IOException("Invalid number of pad bytes");
int rv[] = new int[data.length - numPadBytes];
// optional, but a really good idea: verify the padding
if (true) {
for (int i = data.length - numPadBytes; i < data.length; i++) {
if (data[i] != (byte)numPadBytes) {
throw new IOException("Incorrect padding on decryption: data["+i+"] = " + data[i] + " not " + numPadBytes);
}
if (data[i] != (byte) numPadBytes) { throw new IOException("Incorrect padding on decryption: data[" + i
+ "] = " + data[i] + " not " + numPadBytes); }
}
}
for (int i = 0; i < rv.length; i++)
@@ -267,8 +285,13 @@ public class AESInputStream extends FilterInputStream {
return rv;
}
int remainingBytes() { return _encryptedBuf.size(); }
int readyBytes() { return _readyBuf.size(); }
int remainingBytes() {
return _encryptedBuf.size();
}
int readyBytes() {
return _readyBuf.size();
}
/**
* Test AESOutputStream/AESInputStream
@@ -316,7 +339,10 @@ public class AESInputStream extends FilterInputStream {
_log.info("Done testing offset test (it should have come back with a statement NOT EQUAL!)");
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) {
}
}
private static void runTest(byte orig[], SessionKey key, byte[] iv) {
@@ -335,8 +361,7 @@ public class AESInputStream extends FilterInputStream {
ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
byte buf[] = new byte[1024 * 32];
int read = DataHelper.read(in, buf);
if (read > 0)
baos.write(buf, 0, read);
if (read > 0) baos.write(buf, 0, read);
in.close();
byte fin[] = baos.toByteArray();
long end = Clock.getInstance().now();
@@ -383,8 +408,7 @@ public class AESInputStream extends FilterInputStream {
int remaining = in.remainingBytes();
int readyBytes = in.readyBytes();
_log.info("Read: " + read);
if (read > 0)
baos.write(buf, 0, read);
if (read > 0) baos.write(buf, 0, read);
in.close();
byte fin[] = baos.toByteArray();
_log.info("fin.length: " + fin.length + " remaining: " + remaining + " ready: " + readyBytes);

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -52,29 +53,33 @@ public class AESOutputStream extends FilterOutputStream {
public void write(int val) throws IOException {
_cumulativeProvided++;
_inBuf.write(val);
if (_inBuf.size() > MAX_BUF)
doFlush();
if (_inBuf.size() > MAX_BUF) doFlush();
}
public void write(byte src[]) throws IOException {
_cumulativeProvided += src.length;
_inBuf.write(src);
if (_inBuf.size() > MAX_BUF)
doFlush();
if (_inBuf.size() > MAX_BUF) doFlush();
}
public void write(byte src[], int off, int len) throws IOException {
_cumulativeProvided += len;
_inBuf.write(src, off, len);
if (_inBuf.size() > MAX_BUF)
doFlush();
if (_inBuf.size() > MAX_BUF) doFlush();
}
public void close() throws IOException {
flush();
out.close();
_inBuf.reset();
_log.debug("Cumulative bytes provided to this stream / written out / padded: " + _cumulativeProvided + "/" + _cumulativeWritten + "/" + _cumulativePadding);
_log.debug("Cumulative bytes provided to this stream / written out / padded: " + _cumulativeProvided + "/"
+ _cumulativeWritten + "/" + _cumulativePadding);
}
public void flush() throws IOException {
doFlush();
out.flush();
}
public void flush() throws IOException { doFlush(); out.flush(); }
private void doFlush() throws IOException {
writeEncrypted(_inBuf.toByteArray());

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -28,8 +29,8 @@ public class CryptixAESEngine extends AESEngine {
private final static byte FAKE_KEY = 0x2A;
public byte[] encrypt(byte payload[], SessionKey sessionKey, byte initializationVector[]) {
if ( (initializationVector == null) || (payload == null) || (payload.length <= 0) || (sessionKey == null) || (initializationVector.length != 16) )
return null;
if ((initializationVector == null) || (payload == null) || (payload.length <= 0) || (sessionKey == null)
|| (initializationVector.length != 16)) return null;
if (USE_FAKE_CRYPTO) {
_log.warn("AES Crypto disabled! Using trivial XOR");
@@ -40,8 +41,7 @@ public class CryptixAESEngine extends AESEngine {
}
int numblock = payload.length / 16;
if (payload.length % 16 != 0)
numblock++;
if (payload.length % 16 != 0) numblock++;
byte[][] plain = new byte[numblock][16];
for (int x = 0; x < numblock; x++) {
for (int y = 0; y < 16; y++) {
@@ -66,8 +66,8 @@ public class CryptixAESEngine extends AESEngine {
}
public byte[] decrypt(byte payload[], SessionKey sessionKey, byte initializationVector[]) {
if ( (initializationVector == null) || (payload == null) || (payload.length <= 0) || (sessionKey == null) || (initializationVector.length != 16) )
return null;
if ((initializationVector == null) || (payload == null) || (payload.length <= 0) || (sessionKey == null)
|| (initializationVector.length != 16)) return null;
if (USE_FAKE_CRYPTO) {
_log.warn("AES Crypto disabled! Using trivial XOR");
@@ -78,8 +78,7 @@ public class CryptixAESEngine extends AESEngine {
}
int numblock = payload.length / 16;
if (payload.length % 16 != 0)
numblock++;
if (payload.length % 16 != 0) numblock++;
byte[][] cipher = new byte[numblock][16];
for (int x = 0; x < numblock; x++) {
for (int y = 0; y < 16; y++) {
@@ -103,10 +102,8 @@ public class CryptixAESEngine extends AESEngine {
return ret;
}
final static byte[] xor(byte[] a, byte[] b) {
if ( (a == null) || (b == null) || (a.length != b.length) )
return null;
if ((a == null) || (b == null) || (a.length != b.length)) return null;
byte[] ret = new byte[a.length];
for (int x = 0; x < a.length; x++) {
ret[x] = (byte) (a[x] ^ b[x]);
@@ -130,6 +127,7 @@ public class CryptixAESEngine extends AESEngine {
return null;
}
}
/** decrypt the data with the session key provided
* @param payload encrypted data
* @param sessionKey private session key

View File

@@ -4,10 +4,11 @@
*/
package net.i2p.crypto;
import net.i2p.util.Clock;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import net.i2p.util.Clock;
//...........................................................................
/**
* Rijndael --pronounced Reindaal-- is a variable block-size (128-, 192- and
@@ -41,12 +42,17 @@ public final class CryptixRijndael_Algorithm // implicit no-argument constructor
static final boolean _TRACE = false; // Rijndael_Properties.isTraceable(NAME);
static void debug (String s) { _err.println(">>> "+_NAME+": "+s); }
static void debug(String s) {
_err.println(">>> " + _NAME + ": " + s);
}
static void trace(boolean in, String s) {
if (_TRACE) _err.println((in ? "==> " : "<== ") + _NAME + "." + s);
}
static void trace (String s) { if (_TRACE) _err.println("<=> "+_NAME+"."+s); }
static void trace(String s) {
if (_TRACE) _err.println("<=> " + _NAME + "." + s);
}
// Constants and variables
//...........................................................................
@@ -72,16 +78,12 @@ public final class CryptixRijndael_Algorithm // implicit no-argument constructor
static final int[] _U4 = new int[256];
static final byte[] _rcon = new byte[30];
static final int[][][] _shifts = new int[][][] {
{ {0, 0}, {1, 3}, {2, 2}, {3, 1} },
static final int[][][] _shifts = new int[][][] { { { 0, 0}, { 1, 3}, { 2, 2}, { 3, 1}},
{ { 0, 0}, { 1, 5}, { 2, 4}, { 3, 3}},
{ {0, 0}, {1, 7}, {3, 5}, {4, 4} }
};
private static final char[] _HEX_DIGITS = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
{ { 0, 0}, { 1, 7}, { 3, 5}, { 4, 4}}};
private static final char[] _HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F'};
// Static code - to intialise S-boxes and T-boxes
//...........................................................................
@@ -107,17 +109,11 @@ System.out.println();
if ((j & 0x100) != 0) j ^= ROOT;
_alog[i] = j;
}
for (i = 1; i < 255; i++) _log[_alog[i]] = i;
byte[][] A = new byte[][] {
{1, 1, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 1, 1, 1, 1},
{1, 1, 0, 0, 0, 1, 1, 1},
{1, 1, 1, 0, 0, 0, 1, 1},
{1, 1, 1, 1, 0, 0, 0, 1}
};
for (i = 1; i < 255; i++)
_log[_alog[i]] = i;
byte[][] A = new byte[][] { { 1, 1, 1, 1, 1, 0, 0, 0}, { 0, 1, 1, 1, 1, 1, 0, 0}, { 0, 0, 1, 1, 1, 1, 1, 0},
{ 0, 0, 0, 1, 1, 1, 1, 1}, { 1, 0, 0, 0, 1, 1, 1, 1}, { 1, 1, 0, 0, 0, 1, 1, 1},
{ 1, 1, 1, 0, 0, 0, 1, 1}, { 1, 1, 1, 1, 0, 0, 0, 1}};
byte[] B = new byte[] { 0, 1, 1, 0, 0, 0, 1, 1};
//
@@ -153,15 +149,11 @@ System.out.println();
//
// T-boxes
//
byte[][] G = new byte[][] {
{2, 1, 1, 3},
{3, 2, 1, 1},
{1, 3, 2, 1},
{1, 1, 3, 2}
};
byte[][] G = new byte[][] { { 2, 1, 1, 3}, { 3, 2, 1, 1}, { 1, 3, 2, 1}, { 1, 1, 3, 2}};
byte[][] AA = new byte[4][8];
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) AA[i][j] = G[i][j];
for (j = 0; j < 4; j++)
AA[i][j] = G[i][j];
AA[i][i + 4] = 1;
}
byte pivot, tmp;
@@ -184,9 +176,7 @@ System.out.println();
}
}
for (j = 0; j < 8; j++)
if (AA[i][j] != 0)
AA[i][j] = (byte)
_alog[(255 + _log[AA[i][j] & 0xFF] - _log[pivot & 0xFF]) % 255];
if (AA[i][j] != 0) AA[i][j] = (byte) _alog[(255 + _log[AA[i][j] & 0xFF] - _log[pivot & 0xFF]) % 255];
for (t = 0; t < 4; t++)
if (i != t) {
for (j = i + 1; j < 8; j++)
@@ -195,7 +185,8 @@ System.out.println();
}
}
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++) iG[i][j] = AA[i][j + 4];
for (j = 0; j < 4; j++)
iG[i][j] = AA[i][j + 4];
int s;
for (t = 0; t < 256; t++) {
@@ -221,7 +212,8 @@ System.out.println();
//
_rcon[0] = 1;
int r = 1;
for (t = 1; t < 30; ) _rcon[t++] = (byte)(r = mul(2, r));
for (t = 1; t < 30;)
_rcon[t++] = (byte) (r = mul(2, r));
time = Clock.getInstance().now() - time;
@@ -230,41 +222,121 @@ System.out.println("==========");
System.out.println();
System.out.println("Static Data");
System.out.println();
System.out.println("S[]:"); for(i=0;i<16;i++) { for(j=0;j<16;j++) System.out.print("0x"+byteToString(_S[i*16+j])+", "); System.out.println();}
System.out.println("S[]:");
for (i = 0; i < 16; i++) {
for (j = 0; j < 16; j++)
System.out.print("0x" + byteToString(_S[i * 16 + j]) + ", ");
System.out.println();
System.out.println("Si[]:"); for(i=0;i<16;i++) { for(j=0;j<16;j++) System.out.print("0x"+byteToString(_Si[i*16+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("Si[]:");
for (i = 0; i < 16; i++) {
for (j = 0; j < 16; j++)
System.out.print("0x" + byteToString(_Si[i * 16 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("iG[]:"); for(i=0;i<4;i++){for(j=0;j<4;j++) System.out.print("0x"+byteToString(iG[i][j])+", "); System.out.println();}
System.out.println("iG[]:");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + byteToString(iG[i][j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("T1[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T1[i*4+j])+", "); System.out.println();}
System.out.println("T1[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T1[i * 4 + j]) + ", ");
System.out.println();
System.out.println("T2[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T2[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("T3[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T3[i*4+j])+", "); System.out.println();}
System.out.println("T2[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T2[i * 4 + j]) + ", ");
System.out.println();
System.out.println("T4[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T4[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("T5[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T5[i*4+j])+", "); System.out.println();}
System.out.println("T3[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T3[i * 4 + j]) + ", ");
System.out.println();
System.out.println("T6[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T6[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("T7[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T7[i*4+j])+", "); System.out.println();}
System.out.println("T4[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T4[i * 4 + j]) + ", ");
System.out.println();
System.out.println("T8[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_T8[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("T5[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T5[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("T6[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T6[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("T7[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T7[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("T8[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_T8[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("U1[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_U1[i*4+j])+", "); System.out.println();}
System.out.println("U1[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_U1[i * 4 + j]) + ", ");
System.out.println();
System.out.println("U2[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_U2[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("U3[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_U3[i*4+j])+", "); System.out.println();}
System.out.println("U2[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_U2[i * 4 + j]) + ", ");
System.out.println();
System.out.println("U4[]:"); for(i=0;i<64;i++){for(j=0;j<4;j++) System.out.print("0x"+intToString(_U4[i*4+j])+", "); System.out.println();}
}
System.out.println();
System.out.println("U3[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_U3[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("U4[]:");
for (i = 0; i < 64; i++) {
for (j = 0; j < 4; j++)
System.out.print("0x" + intToString(_U4[i * 4 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("rcon[]:"); for(i=0;i<5;i++){for(j=0;j<6;j++) System.out.print("0x"+byteToString(_rcon[i*6+j])+", "); System.out.println();}
System.out.println("rcon[]:");
for (i = 0; i < 5; i++) {
for (j = 0; j < 6; j++)
System.out.print("0x" + byteToString(_rcon[i * 6 + j]) + ", ");
System.out.println();
}
System.out.println();
System.out.println("Total initialization time: " + time + " ms.");
@@ -274,9 +346,7 @@ System.out.println();
// multiply two elements of GF(2^m)
static final int mul(int a, int b) {
return (a != 0 && b != 0) ?
_alog[(_log[a & 0xFF] + _log[b & 0xFF]) % 255] :
0;
return (a != 0 && b != 0) ? _alog[(_log[a & 0xFF] + _log[b & 0xFF]) % 255] : 0;
}
// convenience method used in generating Transposition boxes
@@ -290,7 +360,6 @@ System.out.println();
return a0 << 24 | a1 << 16 | a2 << 8 | a3;
}
// Basic API methods
//...........................................................................
@@ -315,55 +384,36 @@ System.out.println();
* @param sessionKey The session key to use for encryption.
* @return The ciphertext generated from a plaintext using the session key.
*/
public static final void
blockEncrypt (byte[] in, byte[] result, int inOffset, Object sessionKey) {
public static final void blockEncrypt(byte[] in, byte[] result, int inOffset, Object sessionKey) {
if (_RDEBUG) trace(_IN, "blockEncrypt(" + in + ", " + inOffset + ", " + sessionKey + ")");
int[][] Ke = (int[][]) ((Object[]) sessionKey)[0]; // extract encryption round keys
int ROUNDS = Ke.length - 1;
int[] Ker = Ke[0];
// plaintext to ints + key
int t0 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Ker[0];
int t1 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Ker[1];
int t2 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Ker[2];
int t3 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Ker[3];
int t0 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Ker[0];
int t1 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Ker[1];
int t2 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Ker[2];
int t3 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Ker[3];
int a0, a1, a2, a3;
for (int r = 1; r < ROUNDS; r++) { // apply round transforms
Ker = Ke[r];
a0 = (_T1[(t0 >>> 24) & 0xFF] ^
_T2[(t1 >>> 16) & 0xFF] ^
_T3[(t2 >>> 8) & 0xFF] ^
_T4[ t3 & 0xFF] ) ^ Ker[0];
a1 = (_T1[(t1 >>> 24) & 0xFF] ^
_T2[(t2 >>> 16) & 0xFF] ^
_T3[(t3 >>> 8) & 0xFF] ^
_T4[ t0 & 0xFF] ) ^ Ker[1];
a2 = (_T1[(t2 >>> 24) & 0xFF] ^
_T2[(t3 >>> 16) & 0xFF] ^
_T3[(t0 >>> 8) & 0xFF] ^
_T4[ t1 & 0xFF] ) ^ Ker[2];
a3 = (_T1[(t3 >>> 24) & 0xFF] ^
_T2[(t0 >>> 16) & 0xFF] ^
_T3[(t1 >>> 8) & 0xFF] ^
_T4[ t2 & 0xFF] ) ^ Ker[3];
a0 = (_T1[(t0 >>> 24) & 0xFF] ^ _T2[(t1 >>> 16) & 0xFF] ^ _T3[(t2 >>> 8) & 0xFF] ^ _T4[t3 & 0xFF]) ^ Ker[0];
a1 = (_T1[(t1 >>> 24) & 0xFF] ^ _T2[(t2 >>> 16) & 0xFF] ^ _T3[(t3 >>> 8) & 0xFF] ^ _T4[t0 & 0xFF]) ^ Ker[1];
a2 = (_T1[(t2 >>> 24) & 0xFF] ^ _T2[(t3 >>> 16) & 0xFF] ^ _T3[(t0 >>> 8) & 0xFF] ^ _T4[t1 & 0xFF]) ^ Ker[2];
a3 = (_T1[(t3 >>> 24) & 0xFF] ^ _T2[(t0 >>> 16) & 0xFF] ^ _T3[(t1 >>> 8) & 0xFF] ^ _T4[t2 & 0xFF]) ^ Ker[3];
t0 = a0;
t1 = a1;
t2 = a2;
t3 = a3;
if (_RDEBUG && _debuglevel > 6) System.out.println("CT"+r+"="+intToString(t0)+intToString(t1)+intToString(t2)+intToString(t3));
if (_RDEBUG && _debuglevel > 6)
System.out.println("CT" + r + "=" + intToString(t0) + intToString(t1) + intToString(t2)
+ intToString(t3));
}
// last round is special
@@ -405,55 +455,36 @@ if (_RDEBUG) trace(_OUT, "blockEncrypt()");
* @param sessionKey The session key to use for decryption.
* @return The plaintext generated from a ciphertext using the session key.
*/
public static final void
blockDecrypt (byte[] in, byte[] result, int inOffset, Object sessionKey) {
public static final void blockDecrypt(byte[] in, byte[] result, int inOffset, Object sessionKey) {
if (_RDEBUG) trace(_IN, "blockDecrypt(" + in + ", " + inOffset + ", " + sessionKey + ")");
int[][] Kd = (int[][]) ((Object[]) sessionKey)[1]; // extract decryption round keys
int ROUNDS = Kd.length - 1;
int[] Kdr = Kd[0];
// ciphertext to ints + key
int t0 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Kdr[0];
int t1 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Kdr[1];
int t2 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Kdr[2];
int t3 = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Kdr[3];
int t0 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Kdr[0];
int t1 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Kdr[1];
int t2 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Kdr[2];
int t3 = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Kdr[3];
int a0, a1, a2, a3;
for (int r = 1; r < ROUNDS; r++) { // apply round transforms
Kdr = Kd[r];
a0 = (_T5[(t0 >>> 24) & 0xFF] ^
_T6[(t3 >>> 16) & 0xFF] ^
_T7[(t2 >>> 8) & 0xFF] ^
_T8[ t1 & 0xFF] ) ^ Kdr[0];
a1 = (_T5[(t1 >>> 24) & 0xFF] ^
_T6[(t0 >>> 16) & 0xFF] ^
_T7[(t3 >>> 8) & 0xFF] ^
_T8[ t2 & 0xFF] ) ^ Kdr[1];
a2 = (_T5[(t2 >>> 24) & 0xFF] ^
_T6[(t1 >>> 16) & 0xFF] ^
_T7[(t0 >>> 8) & 0xFF] ^
_T8[ t3 & 0xFF] ) ^ Kdr[2];
a3 = (_T5[(t3 >>> 24) & 0xFF] ^
_T6[(t2 >>> 16) & 0xFF] ^
_T7[(t1 >>> 8) & 0xFF] ^
_T8[ t0 & 0xFF] ) ^ Kdr[3];
a0 = (_T5[(t0 >>> 24) & 0xFF] ^ _T6[(t3 >>> 16) & 0xFF] ^ _T7[(t2 >>> 8) & 0xFF] ^ _T8[t1 & 0xFF]) ^ Kdr[0];
a1 = (_T5[(t1 >>> 24) & 0xFF] ^ _T6[(t0 >>> 16) & 0xFF] ^ _T7[(t3 >>> 8) & 0xFF] ^ _T8[t2 & 0xFF]) ^ Kdr[1];
a2 = (_T5[(t2 >>> 24) & 0xFF] ^ _T6[(t1 >>> 16) & 0xFF] ^ _T7[(t0 >>> 8) & 0xFF] ^ _T8[t3 & 0xFF]) ^ Kdr[2];
a3 = (_T5[(t3 >>> 24) & 0xFF] ^ _T6[(t2 >>> 16) & 0xFF] ^ _T7[(t1 >>> 8) & 0xFF] ^ _T8[t0 & 0xFF]) ^ Kdr[3];
t0 = a0;
t1 = a1;
t2 = a2;
t3 = a3;
if (_RDEBUG && _debuglevel > 6) System.out.println("PT"+r+"="+intToString(t0)+intToString(t1)+intToString(t2)+intToString(t3));
if (_RDEBUG && _debuglevel > 6)
System.out.println("PT" + r + "=" + intToString(t0) + intToString(t1) + intToString(t2)
+ intToString(t3));
}
// last round is special
@@ -486,14 +517,17 @@ if (_RDEBUG) trace(_OUT, "blockDecrypt()");
}
/** A basic symmetric encryption/decryption test. */
public static boolean self_test() { return self_test(_BLOCK_SIZE); }
public static boolean self_test() {
return self_test(_BLOCK_SIZE);
}
// Rijndael own methods
//...........................................................................
/** @return The default length in bytes of the Algorithm input block. */
public static final int blockSize() { return _BLOCK_SIZE; }
public static final int blockSize() {
return _BLOCK_SIZE;
}
/**
* Expand a user-supplied key material into a session key.
@@ -502,11 +536,9 @@ if (_RDEBUG) trace(_OUT, "blockDecrypt()");
* @param blockSize The block size in bytes of this Rijndael.
* @exception InvalidKeyException If the key is invalid.
*/
public static final /* synchronized */ Object makeKey (byte[] k, int blockSize)
throws InvalidKeyException {
public static final/* synchronized */Object makeKey(byte[] k, int blockSize) throws InvalidKeyException {
if (_RDEBUG) trace(_IN, "makeKey(" + k + ", " + blockSize + ")");
if (k == null)
throw new InvalidKeyException("Empty key");
if (k == null) throw new InvalidKeyException("Empty key");
if (!(k.length == 16 || k.length == 24 || k.length == 32))
throw new InvalidKeyException("Incorrect key length");
int ROUNDS = getRounds(k.length, blockSize);
@@ -520,10 +552,7 @@ if (_RDEBUG) trace(_IN, "makeKey("+k+", "+blockSize+")");
// copy user material bytes into temporary ints
for (i = 0, j = 0; i < KC;)
tk[i++] = (k[j++] & 0xFF) << 24 |
(k[j++] & 0xFF) << 16 |
(k[j++] & 0xFF) << 8 |
(k[j++] & 0xFF);
tk[i++] = (k[j++] & 0xFF) << 24 | (k[j++] & 0xFF) << 16 | (k[j++] & 0xFF) << 8 | (k[j++] & 0xFF);
// copy values into round key arrays
int t = 0;
for (j = 0; (j < KC) && (t < ROUND_KEY_COUNT); j++, t++) {
@@ -534,11 +563,9 @@ if (_RDEBUG) trace(_IN, "makeKey("+k+", "+blockSize+")");
while (t < ROUND_KEY_COUNT) {
// extrapolate using phi (the round key evolution function)
tt = tk[KC - 1];
tk[0] ^= (_S[(tt >>> 16) & 0xFF] & 0xFF) << 24 ^
(_S[(tt >>> 8) & 0xFF] & 0xFF) << 16 ^
(_S[ tt & 0xFF] & 0xFF) << 8 ^
(_S[(tt >>> 24) & 0xFF] & 0xFF) ^
(_rcon[rconpointer++] & 0xFF) << 24;
tk[0] ^= (_S[(tt >>> 16) & 0xFF] & 0xFF) << 24 ^ (_S[(tt >>> 8) & 0xFF] & 0xFF) << 16
^ (_S[tt & 0xFF] & 0xFF) << 8 ^ (_S[(tt >>> 24) & 0xFF] & 0xFF)
^ (_rcon[rconpointer++] & 0xFF) << 24;
if (KC != 8)
for (i = 1, j = 0; i < KC;) {
//tk[i++] ^= tk[j++];
@@ -556,10 +583,8 @@ if (_RDEBUG) trace(_IN, "makeKey("+k+", "+blockSize+")");
i++;
}
tt = tk[KC / 2 - 1];
tk[KC / 2] ^= (_S[ tt & 0xFF] & 0xFF) ^
(_S[(tt >>> 8) & 0xFF] & 0xFF) << 8 ^
(_S[(tt >>> 16) & 0xFF] & 0xFF) << 16 ^
(_S[(tt >>> 24) & 0xFF] & 0xFF) << 24;
tk[KC / 2] ^= (_S[tt & 0xFF] & 0xFF) ^ (_S[(tt >>> 8) & 0xFF] & 0xFF) << 8
^ (_S[(tt >>> 16) & 0xFF] & 0xFF) << 16 ^ (_S[(tt >>> 24) & 0xFF] & 0xFF) << 24;
for (j = KC / 2, i = j + 1; i < KC;) {
//tk[i++] ^= tk[j++];
// The above line replaced with the code below in order to work around
@@ -574,13 +599,11 @@ if (_RDEBUG) trace(_IN, "makeKey("+k+", "+blockSize+")");
Kd[ROUNDS - (t / BC)][t % BC] = tk[j];
}
}
for (int r = 1; r < ROUNDS; r++) // inverse MixColumn where needed
for (int r = 1; r < ROUNDS; r++)
// inverse MixColumn where needed
for (j = 0; j < BC; j++) {
tt = Kd[r][j];
Kd[r][j] = _U1[(tt >>> 24) & 0xFF] ^
_U2[(tt >>> 16) & 0xFF] ^
_U3[(tt >>> 8) & 0xFF] ^
_U4[ tt & 0xFF];
Kd[r][j] = _U1[(tt >>> 24) & 0xFF] ^ _U2[(tt >>> 16) & 0xFF] ^ _U3[(tt >>> 8) & 0xFF] ^ _U4[tt & 0xFF];
}
// assemble the encryption (Ke) and decryption (Kd) round keys into
// one sessionKey object
@@ -599,8 +622,7 @@ if (_RDEBUG) trace(_OUT, "makeKey()");
* @param blockSize The block size in bytes of this Rijndael.
* @return The ciphertext generated from a plaintext using the session key.
*/
public static final void
blockEncrypt (byte[] in, byte[] result, int inOffset, Object sessionKey, int blockSize) {
public static final void blockEncrypt(byte[] in, byte[] result, int inOffset, Object sessionKey, int blockSize) {
if (blockSize == _BLOCK_SIZE) {
blockEncrypt(in, result, inOffset, sessionKey);
return;
@@ -620,17 +642,15 @@ if (_RDEBUG) trace(_IN, "blockEncrypt("+in+", "+inOffset+", "+sessionKey+", "+bl
int i;
int j = 0, tt;
for (i = 0; i < BC; i++) // plaintext to ints + key
t[i] = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Ke[0][i];
for (i = 0; i < BC; i++)
// plaintext to ints + key
t[i] = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Ke[0][i];
for (int r = 1; r < ROUNDS; r++) { // apply round transforms
for (i = 0; i < BC; i++)
a[i] = (_T1[(t[ i ] >>> 24) & 0xFF] ^
_T2[(t[(i + s1) % BC] >>> 16) & 0xFF] ^
_T3[(t[(i + s2) % BC] >>> 8) & 0xFF] ^
_T4[ t[(i + s3) % BC] & 0xFF] ) ^ Ke[r][i];
a[i] = (_T1[(t[i] >>> 24) & 0xFF] ^ _T2[(t[(i + s1) % BC] >>> 16) & 0xFF]
^ _T3[(t[(i + s2) % BC] >>> 8) & 0xFF] ^ _T4[t[(i + s3) % BC] & 0xFF])
^ Ke[r][i];
System.arraycopy(a, 0, t, 0, BC);
if (_RDEBUG && _debuglevel > 6) System.out.println("CT" + r + "=" + toString(t));
}
@@ -658,8 +678,7 @@ if (_RDEBUG) trace(_OUT, "blockEncrypt()");
* @param blockSize The block size in bytes of this Rijndael.
* @return The plaintext generated from a ciphertext using the session key.
*/
public static final void
blockDecrypt (byte[] in, byte[] result, int inOffset, Object sessionKey, int blockSize) {
public static final void blockDecrypt(byte[] in, byte[] result, int inOffset, Object sessionKey, int blockSize) {
if (blockSize == _BLOCK_SIZE) {
blockDecrypt(in, result, inOffset, sessionKey);
return;
@@ -680,17 +699,15 @@ if (_RDEBUG) trace(_IN, "blockDecrypt("+in+", "+inOffset+", "+sessionKey+", "+bl
int i;
int j = 0, tt;
for (i = 0; i < BC; i++) // ciphertext to ints + key
t[i] = ((in[inOffset++] & 0xFF) << 24 |
(in[inOffset++] & 0xFF) << 16 |
(in[inOffset++] & 0xFF) << 8 |
(in[inOffset++] & 0xFF) ) ^ Kd[0][i];
for (i = 0; i < BC; i++)
// ciphertext to ints + key
t[i] = ((in[inOffset++] & 0xFF) << 24 | (in[inOffset++] & 0xFF) << 16 | (in[inOffset++] & 0xFF) << 8 | (in[inOffset++] & 0xFF))
^ Kd[0][i];
for (int r = 1; r < ROUNDS; r++) { // apply round transforms
for (i = 0; i < BC; i++)
a[i] = (_T5[(t[ i ] >>> 24) & 0xFF] ^
_T6[(t[(i + s1) % BC] >>> 16) & 0xFF] ^
_T7[(t[(i + s2) % BC] >>> 8) & 0xFF] ^
_T8[ t[(i + s3) % BC] & 0xFF] ) ^ Kd[r][i];
a[i] = (_T5[(t[i] >>> 24) & 0xFF] ^ _T6[(t[(i + s1) % BC] >>> 16) & 0xFF]
^ _T7[(t[(i + s2) % BC] >>> 8) & 0xFF] ^ _T8[t[(i + s3) % BC] & 0xFF])
^ Kd[r][i];
System.arraycopy(a, 0, t, 0, BC);
if (_RDEBUG && _debuglevel > 6) System.out.println("PT" + r + "=" + toString(t));
}
@@ -748,10 +765,8 @@ System.out.println("CT="+toString(ct));
blockDecrypt(ct, cpt, 0, key, _BLOCK_SIZE);
ok = areEqual(pt, cpt);
if (!ok)
throw new RuntimeException("Symmetric operation failed");
}
catch (Exception x) {
if (!ok) throw new RuntimeException("Symmetric operation failed");
} catch (Exception x) {
if (_RDEBUG && _debuglevel > 0) {
debug("Exception encountered during self-test: " + x.getMessage());
x.printStackTrace();
@@ -776,12 +791,12 @@ if (_RDEBUG) trace(_OUT, "self_test()");
return blockSize == 16 ? 10 : (blockSize == 24 ? 12 : 14);
case 24:
return blockSize != 32 ? 12 : 14;
default: // 32 bytes = 256 bits
default:
// 32 bytes = 256 bits
return 14;
}
}
// utility static methods (from cryptix.util.core ArrayUtil and Hex classes)
//...........................................................................
@@ -792,11 +807,9 @@ if (_RDEBUG) trace(_OUT, "self_test()");
*/
private static final boolean areEqual(byte[] a, byte[] b) {
int aLength = a.length;
if (aLength != b.length)
return false;
if (aLength != b.length) return false;
for (int i = 0; i < aLength; i++)
if (a[i] != b[i])
return false;
if (a[i] != b[i]) return false;
return true;
}
@@ -805,10 +818,7 @@ if (_RDEBUG) trace(_OUT, "self_test()");
* digit first) corresponding to the lowest 8 bits of <i>n</i>.
*/
private static final String byteToString(int n) {
char[] buf = {
_HEX_DIGITS[(n >>> 4) & 0x0F],
_HEX_DIGITS[ n & 0x0F]
};
char[] buf = { _HEX_DIGITS[(n >>> 4) & 0x0F], _HEX_DIGITS[n & 0x0F]};
return new String(buf);
}
@@ -862,7 +872,6 @@ if (_RDEBUG) trace(_OUT, "self_test()");
return new String(buf);
}
// main(): use to generate the Intermediate Values KAT
//...........................................................................

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
@@ -29,6 +30,7 @@ package net.i2p.crypto;
*/
import java.math.BigInteger;
import net.i2p.util.NativeBigInteger;
/**
@@ -37,28 +39,28 @@ import net.i2p.util.NativeBigInteger;
*/
public class CryptoConstants {
public static final BigInteger dsap = new NativeBigInteger(
"9c05b2aa960d9b97b8931963c9cc9e8c3026e9b8ed92fad0a69cc886d5bf8015fcadae31"+
"a0ad18fab3f01b00a358de237655c4964afaa2b337e96ad316b9fb1cc564b5aec5b69a9f"+
"f6c3e4548707fef8503d91dd8602e867e6d35d2235c1869ce2479c3b9d5401de04e0727f"+
"b33d6511285d4cf29538d9e3b6051f5b22cc1c93", 16);
public static final BigInteger dsaq = new NativeBigInteger(
"a5dfc28fef4ca1e286744cd8eed9d29d684046b7", 16);
"9c05b2aa960d9b97b8931963c9cc9e8c3026e9b8ed92fad0a69cc886d5bf8015fcadae31"
+ "a0ad18fab3f01b00a358de237655c4964afaa2b337e96ad316b9fb1cc564b5aec5b69a9f"
+ "f6c3e4548707fef8503d91dd8602e867e6d35d2235c1869ce2479c3b9d5401de04e0727f"
+ "b33d6511285d4cf29538d9e3b6051f5b22cc1c93",
16);
public static final BigInteger dsaq = new NativeBigInteger("a5dfc28fef4ca1e286744cd8eed9d29d684046b7", 16);
public static final BigInteger dsag = new NativeBigInteger(
"c1f4d27d40093b429e962d7223824e0bbc47e7c832a39236fc683af84889581075ff9082"+
"ed32353d4374d7301cda1d23c431f4698599dda02451824ff369752593647cc3ddc197de"+
"985e43d136cdcfc6bd5409cd2f450821142a5e6f8eb1c3ab5d0484b8129fcf17bce4f7f3"+
"3321c3cb3dbb14a905e7b2b3e93be4708cbcc82", 16);
public static final BigInteger elgp = new NativeBigInteger(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"+
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"+
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"+
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"+
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"+
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"+
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"+
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"+
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"+
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"+
"15728E5A8AACAA68FFFFFFFFFFFFFFFF", 16);
"c1f4d27d40093b429e962d7223824e0bbc47e7c832a39236fc683af84889581075ff9082"
+ "ed32353d4374d7301cda1d23c431f4698599dda02451824ff369752593647cc3ddc197de"
+ "985e43d136cdcfc6bd5409cd2f450821142a5e6f8eb1c3ab5d0484b8129fcf17bce4f7f3"
+ "3321c3cb3dbb14a905e7b2b3e93be4708cbcc82",
16);
public static final BigInteger elgp = new NativeBigInteger("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AACAA68FFFFFFFFFFFFFFFF", 16);
public static final BigInteger elgg = new NativeBigInteger("2");
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,18 +9,18 @@ package net.i2p.crypto;
*
*/
import net.i2p.data.SessionKey;
import net.i2p.data.ByteArray;
import net.i2p.util.RandomSource;
import net.i2p.util.Log;
import net.i2p.util.NativeBigInteger;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import net.i2p.data.ByteArray;
import net.i2p.data.SessionKey;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
import net.i2p.util.NativeBigInteger;
import net.i2p.util.RandomSource;
/**
* Generate a new session key through a diffie hellman exchange. This uses the
* constants defined in CryptoConstants, which causes the exchange to create a
@@ -83,7 +84,9 @@ public class DHSessionKeyBuilder {
CALC_DELAY = val;
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("DH Precalc (minimum: " + MIN_NUM_BUILDERS + " max: " + MAX_NUM_BUILDERS + ", delay: " + CALC_DELAY + ")");
if (_log.shouldLog(Log.DEBUG))
_log.debug("DH Precalc (minimum: " + MIN_NUM_BUILDERS + " max: " + MAX_NUM_BUILDERS + ", delay: "
+ CALC_DELAY + ")");
_precalcThread = new I2PThread(new DHSessionKeyBuilderPrecalcRunner(MIN_NUM_BUILDERS, MAX_NUM_BUILDERS));
_precalcThread.setName("DH Precalc");
@@ -91,6 +94,7 @@ public class DHSessionKeyBuilder {
_precalcThread.setPriority(Thread.MIN_PRIORITY);
_precalcThread.start();
}
/**
* Construct a new DH key builder
*
@@ -130,7 +134,12 @@ public class DHSessionKeyBuilder {
_extraExchangedBytes = new ByteArray();
}
private static final int getSize() { synchronized (_builders) { return _builders.size(); } }
private static final int getSize() {
synchronized (_builders) {
return _builders.size();
}
}
private static final int addBuilder(DHSessionKeyBuilder builder) {
int sz = 0;
synchronized (_builders) {
@@ -139,6 +148,7 @@ public class DHSessionKeyBuilder {
}
return sz;
}
/**
* Create a new private value for the DH exchange, and return the number to
* be exchanged, leaving the actual private value accessible through getMyPrivateValue()
@@ -151,7 +161,8 @@ public class DHSessionKeyBuilder {
long end = Clock.getInstance().now();
long diff = end - start;
if (diff > 1000) {
if (_log.shouldLog(Log.WARN)) _log.warn("Took more than a second (" + diff + "ms) to generate local DH value");
if (_log.shouldLog(Log.WARN))
_log.warn("Took more than a second (" + diff + "ms) to generate local DH value");
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Took " + diff + "ms to generate local DH value");
}
@@ -161,22 +172,30 @@ public class DHSessionKeyBuilder {
/**
* Retrieve the private value used by the local participant in the DH exchange
*/
public BigInteger getMyPrivateValue() { return _myPrivateValue; }
public BigInteger getMyPrivateValue() {
return _myPrivateValue;
}
/**
* Retrieve the public value used by the local participant in the DH exchange,
* generating it if necessary
*/
public BigInteger getMyPublicValue() {
if (_myPublicValue == null)
_myPublicValue = generateMyValue();
if (_myPublicValue == null) _myPublicValue = generateMyValue();
return _myPublicValue;
}
/**
* Specify the value given by the peer for use in the session key negotiation
*
*/
public void setPeerPublicValue(BigInteger peerVal) { _peerValue = peerVal; }
public BigInteger getPeerPublicValue() { return _peerValue; }
public void setPeerPublicValue(BigInteger peerVal) {
_peerValue = peerVal;
}
public BigInteger getPeerPublicValue() {
return _peerValue;
}
/**
* Retrieve the session key, calculating it if necessary (and if possible).
@@ -189,7 +208,9 @@ public class DHSessionKeyBuilder {
if (_myPrivateValue == null) generateMyValue();
_sessionKey = calculateSessionKey(_myPrivateValue, _peerValue);
} else {
System.err.println("Not ready yet.. privateValue and peerValue must be set (" + (_myPrivateValue != null ? "set":"null") + "," + (_peerValue != null ? "set":"null") + ")");
System.err.println("Not ready yet.. privateValue and peerValue must be set ("
+ (_myPrivateValue != null ? "set" : "null") + ","
+ (_peerValue != null ? "set" : "null") + ")");
}
return _sessionKey;
}
@@ -200,7 +221,9 @@ public class DHSessionKeyBuilder {
* the SHA256 of the key itself is used.
*
*/
public ByteArray getExtraBytes() { return _extraExchangedBytes; }
public ByteArray getExtraBytes() {
return _extraExchangedBytes;
}
/**
* Calculate a session key based on the private value and the public peer value
@@ -216,13 +239,15 @@ public class DHSessionKeyBuilder {
System.arraycopy(buf, 0, val, 0, buf.length);
byte remaining[] = SHA256Generator.getInstance().calculateHash(val).getData();
_extraExchangedBytes.setData(remaining);
if (_log.shouldLog(Log.DEBUG)) _log.debug("Storing " + remaining.length + " bytes from the DH exchange by SHA256 the session key");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Storing " + remaining.length + " bytes from the DH exchange by SHA256 the session key");
} else { // (buf.length >= val.length)
System.arraycopy(buf, 0, val, 0, 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");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Storing " + remaining.length + " bytes from the end of the DH exchange");
}
key.setData(val);
long end = Clock.getInstance().now();
@@ -237,7 +262,10 @@ public class DHSessionKeyBuilder {
public static void main(String args[]) {
RandomSource.getInstance().nextBoolean(); // warm it up
try { Thread.sleep(20*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException ie) {
}
_log.debug("\n\n\n\nBegin test\n");
long negTime = 0;
for (int i = 0; i < 5; i++) {
@@ -270,16 +298,21 @@ public class DHSessionKeyBuilder {
_log.error("**ERROR: D(E(val)) != val [val=(" + tranVal + "), origVal=(" + origVal + ")");
}
_log.debug("Negotiation time for 5 runs: " + negTime + " @ " + negTime / 5l + "ms each");
try { Thread.sleep(2000); } catch (InterruptedException ie) {}
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
}
}
private static class DHSessionKeyBuilderPrecalcRunner implements Runnable {
private int _minSize;
private int _maxSize;
private DHSessionKeyBuilderPrecalcRunner(int minSize, int maxSize) {
_minSize = minSize;
_maxSize = maxSize;
}
public void run() {
while (true) {
@@ -291,15 +324,24 @@ public class DHSessionKeyBuilder {
while (curSize < _maxSize) {
curSize = addBuilder(precalc(curSize));
// for some relief...
try { Thread.sleep(CALC_DELAY); } catch (InterruptedException ie) {}
try {
Thread.sleep(CALC_DELAY);
} catch (InterruptedException ie) {
}
}
}
long end = Clock.getInstance().now();
int numCalc = curSize - startSize;
if (numCalc > 0) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Precalced " + numCalc + " to " + curSize + " in " + (end-start-CALC_DELAY*numCalc) + "ms (not counting " + (CALC_DELAY*numCalc) + "ms relief). now sleeping");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Precalced " + numCalc + " to " + curSize + " in "
+ (end - start - CALC_DELAY * numCalc) + "ms (not counting "
+ (CALC_DELAY * numCalc) + "ms relief). now sleeping");
}
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) {
}
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
@@ -28,23 +29,24 @@ package net.i2p.crypto;
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.math.BigInteger;
import net.i2p.data.Hash;
import net.i2p.data.Signature;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.Hash;
import net.i2p.crypto.CryptoConstants;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.NativeBigInteger;
import net.i2p.util.RandomSource;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import java.math.BigInteger;
public class DSAEngine {
private final static Log _log = new Log(DSAEngine.class);
private static DSAEngine _instance = new DSAEngine();
public static DSAEngine getInstance() { return _instance; }
public static DSAEngine getInstance() {
return _instance;
}
public boolean verifySignature(Signature signature, byte signedData[], SigningPublicKey verifyingKey) {
long start = Clock.getInstance().now();
@@ -63,9 +65,16 @@ public class DSAEngine {
BigInteger r = new NativeBigInteger(1, rbytes);
BigInteger y = new NativeBigInteger(1, verifyingKey.getData());
BigInteger w = s.modInverse(CryptoConstants.dsaq);
BigInteger u1 = ((new NativeBigInteger(1, calculateHash(signedData).getData())).multiply(w)).mod(CryptoConstants.dsaq);
BigInteger u1 = ((new NativeBigInteger(1, calculateHash(signedData).getData())).multiply(w))
.mod(CryptoConstants.dsaq);
BigInteger u2 = r.multiply(w).mod(CryptoConstants.dsaq);
BigInteger v = ((CryptoConstants.dsag.modPow(u1, CryptoConstants.dsap)).multiply(y.modPow(u2, CryptoConstants.dsap))).mod(CryptoConstants.dsap).mod(CryptoConstants.dsaq);
BigInteger v = ((CryptoConstants.dsag.modPow(u1, CryptoConstants.dsap))
.multiply(y.modPow(u2,
CryptoConstants.dsap)))
.mod(
CryptoConstants.dsap)
.mod(
CryptoConstants.dsaq);
boolean ok = v.compareTo(r) == 0;
@@ -138,9 +147,7 @@ public class DSAEngine {
return sig;
}
private int[] H0 = {
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0
};
private int[] H0 = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
private Hash calculateHash(byte[] source) {
long length = source.length * 8;
@@ -240,9 +247,7 @@ public class DSAEngine {
return 0x6ed9eba1;
} else if (t > 39 && t < 60) {
return 0x8f1bbcdc;
} else if (t > 59 && t < 80) {
return 0xca62c1d6;
}
} else if (t > 59 && t < 80) { return 0xca62c1d6; }
return 0x00000000;
}
@@ -253,9 +258,7 @@ public class DSAEngine {
return Parity(x, y, z);
} else if (t > 39 && t < 60) {
return Maj(x, y, z);
} else if (t > 59 && t < 80) {
return Parity(x, y, z);
}
} else if (t > 59 && t < 80) { return Parity(x, y, z); }
return 0x00000000;
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -26,7 +27,8 @@ public class DummyElGamalEngine extends ElGamalEngine {
private final static Log _log = new Log(DummyElGamalEngine.class);
public DummyElGamalEngine() {
_log.log(Log.CRIT, "Dummy ElGamal engine in use! NO DATA SECURITY. Danger Will Robinson, Danger!", new Exception("I really hope you know what you're doing"));
_log.log(Log.CRIT, "Dummy ElGamal engine in use! NO DATA SECURITY. Danger Will Robinson, Danger!",
new Exception("I really hope you know what you're doing"));
}
/** encrypt the data to the public key
@@ -35,7 +37,8 @@ public class DummyElGamalEngine extends ElGamalEngine {
* @param data data to encrypt
*/
public byte[] encrypt(byte data[], PublicKey publicKey) {
if ( (data == null) || (data.length >= 223) ) throw new IllegalArgumentException("Data to encrypt must be < 223 bytes at the moment");
if ((data == null) || (data.length >= 223))
throw new IllegalArgumentException("Data to encrypt must be < 223 bytes at the moment");
if (publicKey == null) throw new IllegalArgumentException("Null public key specified");
ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
try {
@@ -60,13 +63,13 @@ public class DummyElGamalEngine extends ElGamalEngine {
* @return unencrypted data
*/
public byte[] decrypt(byte encrypted[], PrivateKey privateKey) {
if ( (encrypted == null) || (encrypted.length > 514) ) throw new IllegalArgumentException("Data to decrypt must be <= 514 bytes at the moment");
if ((encrypted == null) || (encrypted.length > 514))
throw new IllegalArgumentException("Data to decrypt must be <= 514 bytes at the moment");
byte val[] = new byte[257];
System.arraycopy(encrypted, 0, val, 0, val.length);
int i = 0;
for (i = 0; i < val.length; i++)
if (val[i] != (byte)0x00)
break;
if (val[i] != (byte) 0x00) break;
ByteArrayInputStream bais = new ByteArrayInputStream(val, i, val.length - i);
Hash hash = new Hash();
byte rv[] = null;
@@ -84,7 +87,8 @@ public class DummyElGamalEngine extends ElGamalEngine {
_log.debug("Hash matches: " + DataHelper.toString(hash.getData(), hash.getData().length));
return rv;
} else {
_log.debug("Doesn't match hash [calc=" + calcHash + " sent hash=" + hash + "]\ndata = " + new String(rv), new Exception("Doesn't match"));
_log.debug("Doesn't match hash [calc=" + calcHash + " sent hash=" + hash + "]\ndata = " + new String(rv),
new Exception("Doesn't match"));
return null;
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -24,10 +25,10 @@ import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
import net.i2p.stat.StatManager;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.RandomSource;
import net.i2p.util.Clock;
import net.i2p.stat.StatManager;
/**
* Handles the actual ElGamal+AES encryption and decryption scenarios using the
@@ -38,16 +39,26 @@ public class ElGamalAESEngine {
private final static int MIN_ENCRYPTED_SIZE = 80; // smallest possible resulting size
static {
StatManager.getInstance().createFrequencyStat("crypto.elGamalAES.encryptNewSession",
"how frequently we encrypt to a new ElGamal/AES+SessionTag session?", "Encryption", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l } );
StatManager.getInstance().createFrequencyStat("crypto.elGamalAES.encryptExistingSession",
"how frequently we encrypt to an existing ElGamal/AES+SessionTag session?", "Encryption", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l } );
StatManager.getInstance().createFrequencyStat("crypto.elGamalAES.decryptNewSession",
"how frequently we decrypt with a new ElGamal/AES+SessionTag session?", "Encryption", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l } );
StatManager.getInstance().createFrequencyStat("crypto.elGamalAES.decryptExistingSession",
"how frequently we decrypt with an existing ElGamal/AES+SessionTag session?", "Encryption", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l } );
StatManager.getInstance().createFrequencyStat("crypto.elGamalAES.decryptFail",
"how frequently we fail to decrypt with ElGamal/AES+SessionTag?", "Encryption", new long[] { 60*60*1000l, 24*60*60*1000l } );
StatManager.getInstance()
.createFrequencyStat("crypto.elGamalAES.encryptNewSession",
"how frequently we encrypt to a new ElGamal/AES+SessionTag session?",
"Encryption", new long[] { 60 * 1000l, 60 * 60 * 1000l, 24 * 60 * 60 * 1000l});
StatManager.getInstance()
.createFrequencyStat("crypto.elGamalAES.encryptExistingSession",
"how frequently we encrypt to an existing ElGamal/AES+SessionTag session?",
"Encryption", new long[] { 60 * 1000l, 60 * 60 * 1000l, 24 * 60 * 60 * 1000l});
StatManager.getInstance()
.createFrequencyStat("crypto.elGamalAES.decryptNewSession",
"how frequently we decrypt with a new ElGamal/AES+SessionTag session?",
"Encryption", new long[] { 60 * 1000l, 60 * 60 * 1000l, 24 * 60 * 60 * 1000l});
StatManager.getInstance()
.createFrequencyStat("crypto.elGamalAES.decryptExistingSession",
"how frequently we decrypt with an existing ElGamal/AES+SessionTag session?",
"Encryption", new long[] { 60 * 1000l, 60 * 60 * 1000l, 24 * 60 * 60 * 1000l});
StatManager.getInstance()
.createFrequencyStat("crypto.elGamalAES.decryptFail",
"how frequently we fail to decrypt with ElGamal/AES+SessionTag?", "Encryption",
new long[] { 60 * 60 * 1000l, 24 * 60 * 60 * 1000l});
}
/**
@@ -60,7 +71,8 @@ public class ElGamalAESEngine {
if (_log.shouldLog(Log.WARN)) _log.warn("Null data being decrypted?");
return null;
} else if (data.length < MIN_ENCRYPTED_SIZE) {
if (_log.shouldLog(Log.WARN)) _log.warn("Data is less than the minimum size (" + data.length +" < " + MIN_ENCRYPTED_SIZE + ")");
if (_log.shouldLog(Log.WARN))
_log.warn("Data is less than the minimum size (" + data.length + " < " + MIN_ENCRYPTED_SIZE + ")");
return null;
}
@@ -120,7 +132,8 @@ public class ElGamalAESEngine {
*
* @return null if decryption fails
*/
static byte[] decryptNewSession(byte data[], PrivateKey targetPrivateKey, Set foundTags, SessionKey usedKey, SessionKey foundKey) throws DataFormatException {
static byte[] decryptNewSession(byte data[], PrivateKey targetPrivateKey, Set foundTags, SessionKey usedKey,
SessionKey foundKey) throws DataFormatException {
if (data == null) {
if (_log.shouldLog(Log.WARN)) _log.warn("Data is null, unable to decrypt new session");
return null;
@@ -135,8 +148,7 @@ public class ElGamalAESEngine {
System.arraycopy(data, 0, elgEncr, 514 - data.length, data.length);
}
byte elgDecr[] = ElGamalEngine.getInstance().decrypt(elgEncr, targetPrivateKey);
if (elgDecr == null)
return null;
if (elgDecr == null) return null;
ByteArrayInputStream bais = new ByteArrayInputStream(elgDecr);
byte preIV[] = null;
@@ -147,8 +159,7 @@ public class ElGamalAESEngine {
int read = bais.read(preIV);
if (read != preIV.length) {
// hmm, this can't really happen...
throw new DataFormatException("Somehow ElGamal broke and 256 bytes is less than 32 bytes...");
}
throw new DataFormatException("Somehow ElGamal broke and 256 bytes is less than 32 bytes..."); }
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) _log.error("Error decrypting the new session", ioe);
return null;
@@ -165,7 +176,9 @@ public class ElGamalAESEngine {
byte aesDecr[] = decryptAESBlock(aesEncr, usedKey, iv, null, foundTags, foundKey);
if (_log.shouldLog(Log.DEBUG)) _log.debug("Decrypt with a NEW session successfull: # tags read = " + foundTags.size(), new Exception("Decrypted by"));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Decrypt with a NEW session successfull: # tags read = " + foundTags.size(),
new Exception("Decrypted by"));
return aesDecr;
}
@@ -187,7 +200,8 @@ public class ElGamalAESEngine {
* @param foundKey session key which may be filled with a new sessionKey found during decryption
*
*/
static byte[] decryptExistingSession(byte data[], SessionKey key, PrivateKey targetPrivateKey, Set foundTags, SessionKey usedKey, SessionKey foundKey) throws DataFormatException {
static byte[] decryptExistingSession(byte data[], SessionKey key, PrivateKey targetPrivateKey, Set foundTags,
SessionKey usedKey, SessionKey foundKey) throws DataFormatException {
byte preIV[] = new byte[32];
System.arraycopy(data, 0, preIV, 0, preIV.length);
byte encr[] = new byte[data.length - 32];
@@ -203,11 +217,14 @@ public class ElGamalAESEngine {
byte decrypted[] = decryptAESBlock(encr, key, iv, preIV, foundTags, foundKey);
if (decrypted == null) {
// it begins with a valid session tag, but thats just a coincidence.
if (_log.shouldLog(Log.DEBUG)) _log.debug("Decrypt with a non session tag, but tags read: " + foundTags.size());
if (_log.shouldLog(Log.DEBUG))
_log.debug("Decrypt with a non session tag, but tags read: " + foundTags.size());
return decryptNewSession(data, targetPrivateKey, foundTags, usedKey, foundKey);
} else {
// existing session decrypted successfully!
if (_log.shouldLog(Log.DEBUG)) _log.debug("Decrypt with an EXISTING session tag successfull, # tags read: " + foundTags.size(), new Exception("Decrypted by"));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Decrypt with an EXISTING session tag successfull, # tags read: " + foundTags.size(),
new Exception("Decrypted by"));
return decrypted;
}
}
@@ -229,7 +246,8 @@ public class ElGamalAESEngine {
* @param foundTags set which is filled with any sessionTags found during decryption
* @param foundKey session key which may be filled with a new sessionKey found during decryption
*/
static byte[] decryptAESBlock(byte encrypted[], SessionKey key, byte iv[], byte sentTag[], Set foundTags, SessionKey foundKey) throws DataFormatException {
static byte[] decryptAESBlock(byte encrypted[], SessionKey key, byte iv[], byte sentTag[], Set foundTags,
SessionKey foundKey) throws DataFormatException {
//_log.debug("iv for decryption: " + DataHelper.toString(iv, 16));
//_log.debug("decrypting AES block. encr.length = " + (encrypted == null? -1 : encrypted.length) + " sentTag: " + DataHelper.toString(sentTag, 32));
byte decrypted[] = AESEngine.getInstance().decrypt(encrypted, key, iv);
@@ -243,44 +261,39 @@ public class ElGamalAESEngine {
ByteArrayInputStream bais = new ByteArrayInputStream(decrypted);
long numTags = DataHelper.readLong(bais, 2);
//_log.debug("# tags: " + numTags);
if ( (numTags < 0) || (numTags > 65535) )
throw new Exception("Invalid number of session tags");
if ((numTags < 0) || (numTags > 65535)) throw new Exception("Invalid number of session tags");
for (int i = 0; i < numTags; i++) {
byte tag[] = new byte[32];
int read = bais.read(tag);
if (read != 32)
throw new Exception("Invalid session tag - # tags: " + numTags + " curTag #: " + i + " read: " + read);
throw new Exception("Invalid session tag - # tags: " + numTags + " curTag #: " + i + " read: "
+ read);
tags.add(new SessionTag(tag));
}
long len = DataHelper.readLong(bais, 4);
//_log.debug("len: " + len);
if ( (len < 0) || (len > encrypted.length) )
throw new Exception("Invalid size of payload");
if ((len < 0) || (len > encrypted.length)) throw new Exception("Invalid size of payload");
byte hashval[] = new byte[32];
int read = bais.read(hashval);
if (read != hashval.length)
throw new Exception("Invalid size of hash");
if (read != hashval.length) throw new Exception("Invalid size of hash");
readHash = new Hash();
readHash.setData(hashval);
byte flag = (byte) bais.read();
if (flag == 0x01) {
byte rekeyVal[] = new byte[32];
read = bais.read(rekeyVal);
if (read != rekeyVal.length)
throw new Exception("Invalid size of the rekeyed session key");
if (read != rekeyVal.length) throw new Exception("Invalid size of the rekeyed session key");
newKey = new SessionKey();
newKey.setData(rekeyVal);
}
byte unencrData[] = new byte[(int) len];
read = bais.read(unencrData);
if (read != unencrData.length)
throw new Exception("Invalid size of the data read");
if (read != unencrData.length) throw new Exception("Invalid size of the data read");
Hash calcHash = SHA256Generator.getInstance().calculateHash(unencrData);
if (calcHash.equals(readHash)) {
// everything matches. w00t.
foundTags.addAll(tags);
if (newKey != null)
foundKey.setData(newKey.getData());
if (newKey != null) foundKey.setData(newKey.getData());
return unencrData;
} else {
throw new Exception("Hash does not match");
@@ -291,7 +304,6 @@ public class ElGamalAESEngine {
}
}
/**
* Encrypt the unencrypted data to the target. The total size returned will be
* no less than the paddedSize parameter, but may be more. This method uses the
@@ -305,13 +317,16 @@ public class ElGamalAESEngine {
* @param paddedSize minimum size in bytes of the body after padding it (if less than the
* body's real size, no bytes are appended but the body is not truncated)
*/
public static byte[] encrypt(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery, SessionTag currentTag, SessionKey newKey, long paddedSize) {
public static byte[] encrypt(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery,
SessionTag currentTag, SessionKey newKey, long paddedSize) {
if (currentTag == null) {
if (_log.shouldLog(Log.INFO)) _log.info("Current tag is null, encrypting as new session", new Exception("encrypt new"));
if (_log.shouldLog(Log.INFO))
_log.info("Current tag is null, encrypting as new session", new Exception("encrypt new"));
StatManager.getInstance().updateFrequency("crypto.elGamalAES.encryptNewSession");
return encryptNewSession(data, target, key, tagsForDelivery, newKey, paddedSize);
} else {
if (_log.shouldLog(Log.INFO)) _log.info("Current tag is NOT null, encrypting as existing session", new Exception("encrypt existing"));
if (_log.shouldLog(Log.INFO))
_log.info("Current tag is NOT null, encrypting as existing session", new Exception("encrypt existing"));
StatManager.getInstance().updateFrequency("crypto.elGamalAES.encryptExistingSession");
return encryptExistingSession(data, target, key, tagsForDelivery, currentTag, newKey, paddedSize);
}
@@ -320,7 +335,8 @@ public class ElGamalAESEngine {
/**
* Encrypt the data to the target using the given key and deliver the specified tags
*/
public static byte[] encrypt(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery, SessionTag currentTag, long paddedSize) {
public static byte[] encrypt(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery,
SessionTag currentTag, long paddedSize) {
return encrypt(data, target, key, tagsForDelivery, currentTag, null, paddedSize);
}
@@ -354,7 +370,8 @@ public class ElGamalAESEngine {
* - random bytes, padding the total size to greater than paddedSize with a mod 16 = 0
*
*/
static byte[] encryptNewSession(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery, SessionKey newKey, long paddedSize) {
static byte[] encryptNewSession(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery,
SessionKey newKey, long paddedSize) {
//_log.debug("Encrypting to a NEW session");
try {
ByteArrayOutputStream elgSrc = new ByteArrayOutputStream(64);
@@ -372,7 +389,8 @@ public class ElGamalAESEngine {
long before = Clock.getInstance().now();
byte elgEncr[] = ElGamalEngine.getInstance().encrypt(elgSrc.toByteArray(), target);
long after = Clock.getInstance().now();
if (_log.shouldLog(Log.INFO)) _log.info("elgEngine.encrypt of the session key took " + (after-before) + "ms");
if (_log.shouldLog(Log.INFO))
_log.info("elgEngine.encrypt of the session key took " + (after - before) + "ms");
if (elgEncr.length < 514) {
byte elg[] = new byte[514];
int diff = elg.length - elgEncr.length;
@@ -393,7 +411,8 @@ public class ElGamalAESEngine {
System.arraycopy(aesEncr, 0, rv, elgEncr.length, aesEncr.length);
//_log.debug("Return length: " + rv.length);
long finish = Clock.getInstance().now();
if (_log.shouldLog(Log.DEBUG)) _log.debug("after the elgEngine.encrypt took a total of " + (finish-after) +"ms");
if (_log.shouldLog(Log.DEBUG))
_log.debug("after the elgEngine.encrypt took a total of " + (finish - after) + "ms");
return rv;
} catch (IOException ioe) {
_log.error("Error encrypting the new session", ioe);
@@ -417,7 +436,8 @@ public class ElGamalAESEngine {
* - random bytes, padding the total size to greater than paddedSize with a mod 16 = 0
*
*/
static byte[] encryptExistingSession(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery, SessionTag currentTag, SessionKey newKey, long paddedSize) {
static byte[] encryptExistingSession(byte data[], PublicKey target, SessionKey key, Set tagsForDelivery,
SessionTag currentTag, SessionKey newKey, long paddedSize) {
//_log.debug("Encrypting to an EXISTING session");
byte rawTag[] = currentTag.getData();
@@ -449,7 +469,8 @@ public class ElGamalAESEngine {
* - random bytes, padding the total size to greater than paddedSize with a mod 16 = 0
*
*/
final static byte[] encryptAESBlock(byte data[], SessionKey key, byte[] iv, Set tagsForDelivery, SessionKey newKey, long paddedSize) {
final static byte[] encryptAESBlock(byte data[], SessionKey key, byte[] iv, Set tagsForDelivery, SessionKey newKey,
long paddedSize) {
//_log.debug("iv for encryption: " + DataHelper.toString(iv, 16));
//_log.debug("Encrypting AES");
try {
@@ -497,7 +518,6 @@ public class ElGamalAESEngine {
}
}
/**
* Return random bytes for padding the data to a mod 16 size so that it is
* at least minPaddedSize
@@ -510,8 +530,7 @@ public class ElGamalAESEngine {
}
int numPadding = diff;
if (((curSize + diff) % 16) != 0)
numPadding += (16-((curSize + diff) % 16));
if (((curSize + diff) % 16) != 0) numPadding += (16 - ((curSize + diff) % 16));
byte rv[] = new byte[numPadding];
RandomSource.getInstance().nextBytes(rv);
return rv;

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
@@ -37,11 +38,11 @@ import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.stat.StatManager;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.NativeBigInteger;
import net.i2p.util.RandomSource;
import net.i2p.stat.StatManager;
/**
* Wrapper for ElGamal encryption/signature schemes.
@@ -64,14 +65,21 @@ public class ElGamalEngine {
_engine = new ElGamalEngine();
StatManager.getInstance().createRateStat("crypto.elGamal.encrypt",
"how long does it take to do a full ElGamal encryption", "Encryption", new long[] { 60*1000, 60*60*1000, 24*60*60*1000 } );
"how long does it take to do a full ElGamal encryption", "Encryption",
new long[] { 60 * 1000, 60 * 60 * 1000, 24 * 60 * 60 * 1000});
StatManager.getInstance().createRateStat("crypto.elGamal.decrypt",
"how long does it take to do a full ElGamal decryption", "Encryption", new long[] { 60*1000, 60*60*1000, 24*60*60*1000 } );
"how long does it take to do a full ElGamal decryption", "Encryption",
new long[] { 60 * 1000, 60 * 60 * 1000, 24 * 60 * 60 * 1000});
}
public static ElGamalEngine getInstance() {
return _engine;
}
public static ElGamalEngine getInstance() { return _engine; }
private final static BigInteger _two = new NativeBigInteger(1, new byte[] { 0x02});
private BigInteger[] getNextYK() { return YKGenerator.getNextYK(); }
private BigInteger[] getNextYK() {
return YKGenerator.getNextYK();
}
/** encrypt the data to the public key
* @return encrypted data
@@ -79,7 +87,8 @@ public class ElGamalEngine {
* @param data data to encrypt
*/
public byte[] encrypt(byte data[], PublicKey publicKey) {
if ( (data == null) || (data.length >= 223) ) throw new IllegalArgumentException("Data to encrypt must be < 223 bytes at the moment");
if ((data == null) || (data.length >= 223))
throw new IllegalArgumentException("Data to encrypt must be < 223 bytes at the moment");
if (publicKey == null) throw new IllegalArgumentException("Null public key specified");
long start = Clock.getInstance().now();
@@ -120,8 +129,10 @@ public class ElGamalEngine {
byte[] ybytes = y.toByteArray();
byte[] dbytes = d.toByteArray();
byte[] out = new byte[514];
System.arraycopy(ybytes, 0, out, (ybytes.length < 257 ? 257 - ybytes.length : 0), (ybytes.length > 257 ? 257 : ybytes.length));
System.arraycopy(dbytes, 0, out, (dbytes.length < 257 ? 514 - dbytes.length : 257), (dbytes.length > 257 ? 257 : dbytes.length));
System.arraycopy(ybytes, 0, out, (ybytes.length < 257 ? 257 - ybytes.length : 0),
(ybytes.length > 257 ? 257 : ybytes.length));
System.arraycopy(dbytes, 0, out, (dbytes.length < 257 ? 514 - dbytes.length : 257),
(dbytes.length > 257 ? 257 : dbytes.length));
StringBuffer buf = new StringBuffer(1024);
buf.append("Timing\n");
buf.append("0-1: ").append(t1 - t0).append('\n');
@@ -152,7 +163,8 @@ public class ElGamalEngine {
* @return unencrypted data
*/
public byte[] decrypt(byte encrypted[], PrivateKey privateKey) {
if ( (encrypted == null) || (encrypted.length > 514) ) throw new IllegalArgumentException("Data to decrypt must be <= 514 bytes at the moment");
if ((encrypted == null) || (encrypted.length > 514))
throw new IllegalArgumentException("Data to decrypt must be <= 514 bytes at the moment");
long start = Clock.getInstance().now();
byte[] ybytes = new byte[257];
@@ -164,12 +176,12 @@ public class ElGamalEngine {
BigInteger a = new NativeBigInteger(1, privateKey.getData());
BigInteger y1p = CryptoConstants.elgp.subtract(BigInteger.ONE).subtract(a);
BigInteger ya = y.modPow(y1p, CryptoConstants.elgp);
BigInteger m = ya.multiply(d); m = m.mod(CryptoConstants.elgp);
BigInteger m = ya.multiply(d);
m = m.mod(CryptoConstants.elgp);
byte val[] = m.toByteArray();
int i = 0;
for (i = 0; i < val.length; i++)
if (val[i] != (byte)0x00)
break;
if (val[i] != (byte) 0x00) break;
ByteArrayInputStream bais = new ByteArrayInputStream(val, i, val.length - i);
Hash hash = new Hash();
@@ -184,7 +196,6 @@ public class ElGamalEngine {
return null;
}
Hash calcHash = SHA256Generator.getInstance().calculateHash(rv);
boolean ok = calcHash.equals(hash);
@@ -192,7 +203,8 @@ public class ElGamalEngine {
long diff = end - start;
if (diff > 1000) {
if (_log.shouldLog(Log.WARN)) _log.warn("Took too long to decrypt and verify ElGamal block (" + diff + "ms)");
if (_log.shouldLog(Log.WARN))
_log.warn("Took too long to decrypt and verify ElGamal block (" + diff + "ms)");
}
StatManager.getInstance().addRateData("crypto.elGamal.decrypt", diff, diff);
@@ -201,7 +213,9 @@ public class ElGamalEngine {
//_log.debug("Hash matches: " + DataHelper.toString(hash.getData(), hash.getData().length));
return rv;
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Doesn't match hash [calc=" + calcHash + " sent hash=" + hash + "]\ndata = " + Base64.encode(rv), new Exception("Doesn't match"));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Doesn't match hash [calc=" + calcHash + " sent hash=" + hash + "]\ndata = "
+ Base64.encode(rv), new Exception("Doesn't match"));
return null;
}
}
@@ -211,12 +225,15 @@ public class ElGamalEngine {
long dTime = 0;
long gTime = 0;
int numRuns = 100;
if (args.length > 0)
try {
if (args.length > 0) try {
numRuns = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {}
} catch (NumberFormatException nfe) {
}
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) {
}
RandomSource.getInstance().nextBoolean();
@@ -242,7 +259,8 @@ public class ElGamalEngine {
if (!DataHelper.eq(decr, buf)) {
System.out.println("PublicKey : " + DataHelper.toString(pubkey.getData(), pubkey.getData().length));
System.out.println("PrivateKey : " + DataHelper.toString(privkey.getData(), privkey.getData().length));
System.out.println("PrivateKey : "
+ DataHelper.toString(privkey.getData(), privkey.getData().length));
System.out.println("orig : " + DataHelper.toString(buf, buf.length));
System.out.println("d(e(orig) : " + DataHelper.toString(decr, decr.length));
System.out.println("orig.len : " + buf.length);
@@ -250,9 +268,12 @@ public class ElGamalEngine {
System.out.println("Not equal!");
System.exit(0);
} else {
System.out.println("*Run " +i+" is successful, with encr.length = " + encr.length + " [E: " + (endE-startE) + " D: " + (endD-endE) + " G: " + (endG - startG) + "]\n");
System.out.println("*Run " + i + " is successful, with encr.length = " + encr.length + " [E: "
+ (endE - startE) + " D: " + (endD - endE) + " G: " + (endG - startG) + "]\n");
}
}
System.out.println("\n\nAll "+numRuns+" tests successful, average encryption time: " + (eTime/numRuns) + " average decryption time: " + (dTime / numRuns) + " average key generation time: " + (gTime / numRuns));
System.out.println("\n\nAll " + numRuns + " tests successful, average encryption time: " + (eTime / numRuns)
+ " average decryption time: " + (dTime / numRuns) + " average key generation time: "
+ (gTime / numRuns));
}
}

View File

@@ -1,8 +1,8 @@
package net.i2p.crypto;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.data.DataHelper;
/**
* Calculate the HMAC-SHA256 of a key+message. Currently FAKE - returns a stupid
@@ -11,7 +11,10 @@ import net.i2p.data.DataHelper;
*/
public abstract class HMACSHA256Generator {
private static HMACSHA256Generator _generator = new DummyHMACSHA256Generator();
public static HMACSHA256Generator getInstance() { return _generator; }
public static HMACSHA256Generator getInstance() {
return _generator;
}
public abstract Hash calculate(SessionKey key, byte data[]);
}
@@ -20,6 +23,7 @@ public abstract class HMACSHA256Generator {
* jrandom smells.
*
*/
class DummyHMACSHA256Generator extends HMACSHA256Generator {
public Hash calculate(SessionKey key, byte data[]) {
if ((key == null) || (key.getData() == null) || (data == null))
@@ -30,4 +34,3 @@ class DummyHMACSHA256Generator extends HMACSHA256Generator {
return SHA256Generator.getInstance().calculateHash(DataHelper.xor(hkey.getData(), hdata.getData()));
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -29,7 +30,10 @@ public class KeyGenerator {
private final static Log _log = new Log(KeyGenerator.class);
private static final RandomSource _random = RandomSource.getInstance();
private static KeyGenerator _generator = new KeyGenerator();
public static KeyGenerator getInstance() { return _generator; }
public static KeyGenerator getInstance() {
return _generator;
}
/** Generate a private 256 bit session key
* @return session key
@@ -90,7 +94,6 @@ public class KeyGenerator {
return keys;
}
/**
* Pad the buffer w/ leading 0s or trim off leading bits so the result is the
* given length.
@@ -102,7 +105,8 @@ public class KeyGenerator {
System.arraycopy(src, src.length - buf.length, buf, 0, buf.length);
else if (src.length < buf.length) // short bits, padd w/ 0s
System.arraycopy(src, 0, buf, buf.length - src.length, src.length);
else // eq
else
// eq
System.arraycopy(src, 0, buf, 0, buf.length);
return buf;
@@ -153,6 +157,9 @@ public class KeyGenerator {
}
log.info("Session keygen 1000 times: " + time + "ms");
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -45,7 +46,8 @@ public class PersistentSessionKeyManager extends TransientSessionKeyManager {
public void saveState(OutputStream out) throws IOException, DataFormatException {
Set tagSets = getInboundTagSets();
Set sessions = getOutboundSessions();
_log.info("Saving state with " + tagSets.size() + " inbound tagSets and " + sessions.size() + " outbound sessions");
_log.info("Saving state with " + tagSets.size() + " inbound tagSets and " + sessions.size()
+ " outbound sessions");
DataHelper.writeLong(out, 4, tagSets.size());
for (Iterator iter = tagSets.iterator(); iter.hasNext();) {
@@ -59,7 +61,6 @@ public class PersistentSessionKeyManager extends TransientSessionKeyManager {
}
}
/**
* Load the session key data from the given stream
*
@@ -78,7 +79,8 @@ public class PersistentSessionKeyManager extends TransientSessionKeyManager {
sessions.add(sess);
}
_log.info("Loading state with " + tagSets.size() + " inbound tagSets and " + sessions.size() + " outbound sessions");
_log.info("Loading state with " + tagSets.size() + " inbound tagSets and " + sessions.size()
+ " outbound sessions");
setData(tagSets, sessions);
}
@@ -133,7 +135,8 @@ public class PersistentSessionKeyManager extends TransientSessionKeyManager {
byte val[] = new byte[SessionTag.BYTE_LENGTH];
int read = DataHelper.read(in, val);
if (read != SessionTag.BYTE_LENGTH)
throw new IOException("Unable to fully read a session tag [" + read + " not " + SessionTag.BYTE_LENGTH + ")");
throw new IOException("Unable to fully read a session tag [" + read + " not " + SessionTag.BYTE_LENGTH
+ ")");
tag.setData(val);
tags.add(tag);
}
@@ -159,6 +162,9 @@ public class PersistentSessionKeyManager extends TransientSessionKeyManager {
} catch (Throwable t) {
_log.error("Error loading/storing sessionKeys", t);
}
try { Thread.sleep(3000); } catch (Throwable t) {}
try {
Thread.sleep(3000);
} catch (Throwable t) {
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
@@ -38,22 +39,21 @@ import net.i2p.data.Hash;
*/
public class SHA256Generator {
private static SHA256Generator _generator = new SHA256Generator();
public static SHA256Generator getInstance() { return _generator; }
static int[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
public static SHA256Generator getInstance() {
return _generator;
}
static int[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
static int[] H0 = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
static int[] H0 = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
/** Calculate the SHA-256 has of the source
* @param source what to hash
@@ -105,8 +105,14 @@ public class SHA256Generator {
}
int blocks = M0.length / 16;
for (int bl = 0; bl < blocks; bl++) {
int a = H[0]; int b = H[1]; int c = H[2]; int d = H[3];
int e = H[4]; int f = H[5]; int g = H[6]; int h = H[7];
int a = H[0];
int b = H[1];
int c = H[2];
int d = H[3];
int e = H[4];
int f = H[5];
int g = H[6];
int h = H[7];
int[] W = new int[64];
for (x = 0; x < 64; x++) {
if (x < 16) {
@@ -118,10 +124,23 @@ public class SHA256Generator {
for (x = 0; x < 64; x++) {
int T1 = add(h, add(e1(e), add(Ch(e, f, g), add(K[x], W[x]))));
int T2 = add(e0(a), Maj(a, b, c));
h = g; g = f; f = e; e = add(d, T1); d = c; c = b; b = a; a = add(T1, T2);
h = g;
g = f;
f = e;
e = add(d, T1);
d = c;
c = b;
b = a;
a = add(T1, T2);
}
H[0] = add(a, H[0]); H[1] = add(b, H[1]); H[2] = add(c, H[2]); H[3] = add(d, H[3]);
H[4] = add(e, H[4]); H[5] = add(f, H[5]); H[6] = add(g, H[6]); H[7] = add(h, H[7]);
H[0] = add(a, H[0]);
H[1] = add(b, H[1]);
H[2] = add(c, H[2]);
H[3] = add(d, H[3]);
H[4] = add(e, H[4]);
H[5] = add(f, H[5]);
H[6] = add(g, H[6]);
H[7] = add(h, H[7]);
}
byte[] hashbytes = new byte[32];
for (x = 0; x < 8; x++) {

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,12 +9,12 @@ package net.i2p.crypto;
*
*/
import java.util.Set;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
import java.util.Set;
/**
* Manage the session keys and session tags used for encryption and decryption.
* This base implementation simply ignores sessions and acts as if everything is
@@ -23,21 +24,27 @@ import java.util.Set;
*/
public class SessionKeyManager {
private final static SessionKeyManager _instance = new PersistentSessionKeyManager(); // new TransientSessionKeyManager(); // SessionKeyManager();
public final static SessionKeyManager getInstance() { return _instance; }
public final static SessionKeyManager getInstance() {
return _instance;
}
/**
* Retrieve the session key currently associated with encryption to the target,
* or null if a new session key should be generated.
*
*/
public SessionKey getCurrentKey(PublicKey target) { return null; }
public SessionKey getCurrentKey(PublicKey target) {
return null;
}
/**
* Associate a new session key with the specified target. Metrics to determine
* when to expire that key begin with this call.
*
*/
public void createSession(PublicKey target, SessionKey key) { }
public void createSession(PublicKey target, SessionKey key) {
}
/**
* Generate a new session key and associate it with the specified target.
@@ -56,20 +63,26 @@ public class SessionKeyManager {
* NOT be used)
*
*/
public SessionTag consumeNextAvailableTag(PublicKey target, SessionKey key) { return null; }
public SessionTag consumeNextAvailableTag(PublicKey target, SessionKey key) {
return null;
}
/**
* Determine (approximately) how many available session tags for the current target
* have been confirmed and are available
*
*/
public int getAvailableTags(PublicKey target, SessionKey key) { return 0; }
public int getAvailableTags(PublicKey target, SessionKey key) {
return 0;
}
/**
* Determine how long the available tags will be available for before expiring, in
* milliseconds
*/
public long getAvailableTimeLeft(PublicKey target, SessionKey key) { return 0; }
public long getAvailableTimeLeft(PublicKey target, SessionKey key) {
return 0;
}
/**
* Take note of the fact that the given sessionTags associated with the key for
@@ -77,7 +90,8 @@ public class SessionKeyManager {
* method after receiving an ack to a message delivering them)
*
*/
public void tagsDelivered(PublicKey target, SessionKey key, Set sessionTags) { }
public void tagsDelivered(PublicKey target, SessionKey key, Set sessionTags) {
}
/**
* Mark all of the tags delivered to the target up to this point as invalid, since the peer
@@ -85,13 +99,15 @@ public class SessionKeyManager {
* from corrupted tag sets and crashes
*
*/
public void failTags(PublicKey target) {}
public void failTags(PublicKey target) {
}
/**
* Accept the given tags and associate them with the given key for decryption
*
*/
public void tagsReceived(SessionKey key, Set sessionTags) { }
public void tagsReceived(SessionKey key, Set sessionTags) {
}
/**
* Determine if we have received a session key associated with the given session tag,
@@ -100,12 +116,15 @@ public class SessionKeyManager {
* matches
*
*/
public SessionKey consumeTag(SessionTag tag) { return null; }
public SessionKey consumeTag(SessionTag tag) {
return null;
}
/**
* Called when the system is closing down, instructing the session key manager to take
* whatever precautions are necessary (saving state, etc)
*
*/
public void shutdown() {}
public void shutdown() {
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,22 +9,21 @@ package net.i2p.crypto;
*
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.i2p.data.DataHelper;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
import net.i2p.data.DataHelper;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import net.i2p.util.Log;
/**
* Implement the session key management, but keep everything in memory (don't write
@@ -64,14 +64,17 @@ class TransientSessionKeyManager extends SessionKeyManager {
return new HashSet(_inboundTagSets.values());
}
}
/** OutboundSession */
protected Set getOutboundSessions() {
synchronized (_outboundSessions) {
return new HashSet(_outboundSessions.values());
}
}
protected void setData(Set inboundTagSets, Set outboundSessions) {
_log.info("Loading " + inboundTagSets.size() + " inbound tag sets, and " + outboundSessions.size() + " outbound sessions");
_log.info("Loading " + inboundTagSets.size() + " inbound tag sets, and " + outboundSessions.size()
+ " outbound sessions");
Map tagSets = new HashMap(inboundTagSets.size());
for (Iterator iter = inboundTagSets.iterator(); iter.hasNext();) {
TagSet ts = (TagSet) iter.next();
@@ -105,7 +108,8 @@ class TransientSessionKeyManager extends SessionKeyManager {
if (sess == null) return null;
long now = Clock.getInstance().now();
if (sess.getEstablishedDate() < now - SESSION_LIFETIME_MAX_MS) {
_log.info("Expiring old session key established on " + new Date(sess.getEstablishedDate()) + " with target " + target);
_log.info("Expiring old session key established on " + new Date(sess.getEstablishedDate())
+ " with target " + target);
return null;
} else {
return sess.getCurrentKey();
@@ -153,9 +157,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
*/
public int getAvailableTags(PublicKey target, SessionKey key) {
OutboundSession sess = getSession(target);
if (sess == null) {
return 0;
}
if (sess == null) { return 0; }
if (sess.getCurrentKey().equals(key)) {
return sess.availableTags();
} else {
@@ -163,16 +165,13 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
}
/**
* Determine how long the available tags will be available for before expiring, in
* milliseconds
*/
public long getAvailableTimeLeft(PublicKey target, SessionKey key) {
OutboundSession sess = getSession(target);
if (sess == null) {
return 0;
}
if (sess == null) { return 0; }
if (sess.getCurrentKey().equals(key)) {
return (sess.getLastExpirationDate() + SESSION_TAG_DURATION_MS) - Clock.getInstance().now();
} else {
@@ -208,7 +207,6 @@ class TransientSessionKeyManager extends SessionKeyManager {
removeSession(target);
}
/**
* Accept the given tags and associate them with the given key for decryption
*
@@ -230,8 +228,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
}
if (sessionTags.size() <= 0)
_log.debug("Received 0 tags for key " + key);
if (sessionTags.size() <= 0) _log.debug("Received 0 tags for key " + key);
}
/**
@@ -304,8 +301,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
PublicKey key = (PublicKey) iter.next();
OutboundSession sess = (OutboundSession) _outboundSessions.get(key);
removed += sess.expireTags();
if (sess.getTagSets().size() <= 0)
sessionsToDrop.add(key);
if (sess.getTagSets().size() <= 0) sessionsToDrop.add(key);
}
for (Iterator iter = sessionsToDrop.iterator(); iter.hasNext();)
_outboundSessions.remove(iter.next());
@@ -321,8 +317,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
Map inboundSets = new HashMap(inbound.size());
for (Iterator iter = inbound.iterator(); iter.hasNext();) {
TagSet ts = (TagSet) iter.next();
if (!inboundSets.containsKey(ts.getAssociatedKey()))
inboundSets.put(ts.getAssociatedKey(), new HashSet());
if (!inboundSets.containsKey(ts.getAssociatedKey())) inboundSets.put(ts.getAssociatedKey(), new HashSet());
Set sets = (Set) inboundSets.get(ts.getAssociatedKey());
sets.add(ts);
}
@@ -334,7 +329,8 @@ class TransientSessionKeyManager extends SessionKeyManager {
buf.append("<tr><td colspan=\"2\"><ul>");
for (Iterator siter = sets.iterator(); siter.hasNext();) {
TagSet ts = (TagSet) siter.next();
buf.append("<li><b>Received on:</b> ").append(new Date(ts.getDate())).append(" with ").append(ts.getTags().size()).append(" tags remaining</li>");
buf.append("<li><b>Received on:</b> ").append(new Date(ts.getDate())).append(" with ")
.append(ts.getTags().size()).append(" tags remaining</li>");
}
buf.append("</ul></td></tr>");
}
@@ -354,7 +350,10 @@ class TransientSessionKeyManager extends SessionKeyManager {
buf.append("<tr><td><ul>");
for (Iterator siter = sess.getTagSets().iterator(); siter.hasNext();) {
TagSet ts = (TagSet) siter.next();
buf.append("<li><b>Sent on:</b> ").append(new Date(ts.getDate())).append(" with ").append(ts.getTags().size()).append(" tags remaining</li>");
buf.append("<li><b>Sent on:</b> ").append(new Date(ts.getDate())).append(" with ").append(
ts.getTags()
.size())
.append(" tags remaining</li>");
}
buf.append("</ul></td></tr>");
}
@@ -389,8 +388,14 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
}
public PublicKey getTarget() { return _target; }
public SessionKey getCurrentKey() { return _currentKey; }
public PublicKey getTarget() {
return _target;
}
public SessionKey getCurrentKey() {
return _currentKey;
}
public void setCurrentKey(SessionKey key) {
if (_currentKey != null) {
if (!_currentKey.equals(key)) {
@@ -407,8 +412,15 @@ class TransientSessionKeyManager extends SessionKeyManager {
_currentKey = key;
}
public long getEstablishedDate() { return _established; }
public long getLastUsedDate() { return _lastUsed; }
public long getEstablishedDate() {
return _established;
}
public long getLastUsedDate() {
return _lastUsed;
}
/**
* Expire old tags, returning the number of tag sets removed
*/
@@ -426,6 +438,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
return toRemove.size();
}
public SessionTag consumeNext() {
long now = Clock.getInstance().now();
synchronized (_tagSets) {
@@ -442,6 +455,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
return null;
}
public int availableTags() {
int tags = 0;
synchronized (_tagSets) {
@@ -452,6 +466,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
}
return tags;
}
/**
* Get the furthest away tag set expiration date - after which all of the
* tags will have expired
@@ -462,12 +477,12 @@ class TransientSessionKeyManager extends SessionKeyManager {
synchronized (_tagSets) {
for (Iterator iter = _tagSets.iterator(); iter.hasNext();) {
TagSet set = (TagSet) iter.next();
if (set.getDate() > last)
last = set.getDate();
if (set.getDate() > last) last = set.getDate();
}
}
return last + SESSION_TAG_DURATION_MS;
}
public void addTags(TagSet set) {
synchronized (_tagSets) {
_tagSets.add(set);
@@ -479,25 +494,41 @@ class TransientSessionKeyManager extends SessionKeyManager {
private Set _sessionTags;
private SessionKey _key;
private long _date;
public TagSet(Set tags, SessionKey key) {
if (key == null)
throw new IllegalArgumentException("Missing key");
if (tags == null)
throw new IllegalArgumentException("Missing tags");
if (key == null) throw new IllegalArgumentException("Missing key");
if (tags == null) throw new IllegalArgumentException("Missing tags");
_sessionTags = tags;
_key = key;
_date = Clock.getInstance().now();
}
public long getDate() { return _date; }
void setDate(long when) { _date = when; }
public Set getTags() { return _sessionTags; }
public SessionKey getAssociatedKey() { return _key; }
public boolean contains(SessionTag tag) { return _sessionTags.contains(tag); }
public long getDate() {
return _date;
}
void setDate(long when) {
_date = when;
}
public Set getTags() {
return _sessionTags;
}
public SessionKey getAssociatedKey() {
return _key;
}
public boolean contains(SessionTag tag) {
return _sessionTags.contains(tag);
}
public void consume(SessionTag tag) {
if (contains(tag)) {
_sessionTags.remove(tag);
}
}
public SessionTag consumeNext() {
if (_sessionTags.size() <= 0) {
return null;
@@ -507,21 +538,20 @@ class TransientSessionKeyManager extends SessionKeyManager {
return first;
}
}
public int hashCode() {
long rv = 0;
if (_key != null)
rv = rv*7 + _key.hashCode();
if (_key != null) rv = rv * 7 + _key.hashCode();
rv = rv * 7 + _date;
if (_sessionTags != null)
rv = rv*7 + DataHelper.hashCode(_sessionTags);
if (_sessionTags != null) rv = rv * 7 + DataHelper.hashCode(_sessionTags);
return (int) rv;
}
public boolean equals(Object o) {
if ((o == null) || !(o instanceof TagSet)) return false;
TagSet ts = (TagSet) o;
return DataHelper.eq(ts.getAssociatedKey(), getAssociatedKey()) &&
DataHelper.eq(ts.getTags(), getTags()) &&
ts.getDate() == getDate();
return DataHelper.eq(ts.getAssociatedKey(), getAssociatedKey()) && DataHelper.eq(ts.getTags(), getTags())
&& ts.getDate() == getDate();
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.crypto;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -13,8 +14,8 @@ import java.util.ArrayList;
import java.util.List;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
import net.i2p.util.NativeBigInteger;
import net.i2p.util.RandomSource;
@@ -77,7 +78,9 @@ class YKGenerator {
CALC_DELAY = val;
}
if (_log.shouldLog(Log.DEBUG)) _log.debug("ElGamal YK Precalc (minimum: " + MIN_NUM_BUILDERS + " max: " + MAX_NUM_BUILDERS + ", delay: " + CALC_DELAY + ")");
if (_log.shouldLog(Log.DEBUG))
_log.debug("ElGamal YK Precalc (minimum: " + MIN_NUM_BUILDERS + " max: " + MAX_NUM_BUILDERS + ", delay: "
+ CALC_DELAY + ")");
_precalcThread = new I2PThread(new YKPrecalcRunner(MIN_NUM_BUILDERS, MAX_NUM_BUILDERS));
_precalcThread.setName("YK Precalc");
@@ -86,7 +89,12 @@ class YKGenerator {
_precalcThread.start();
}
private static final int getSize() { synchronized (_values) { return _values.size(); } }
private static final int getSize() {
synchronized (_values) {
return _values.size();
}
}
private static final int addValues(BigInteger yk[]) {
int sz = 0;
synchronized (_values) {
@@ -100,7 +108,8 @@ class YKGenerator {
if (true) {
synchronized (_values) {
if (_values.size() > 0) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Sufficient precalculated YK values - fetch the existing");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Sufficient precalculated YK values - fetch the existing");
return (BigInteger[]) _values.remove(0);
}
}
@@ -125,8 +134,7 @@ class YKGenerator {
continue;
}
BigInteger kPlus2 = k.add(_two);
if (kPlus2.compareTo(CryptoConstants.elgp) > 0)
k = null;
if (kPlus2.compareTo(CryptoConstants.elgp) > 0) k = null;
}
long t2 = Clock.getInstance().now();
y = CryptoConstants.elgg.modPow(k, CryptoConstants.elgp);
@@ -143,10 +151,12 @@ class YKGenerator {
return yk;
}
public static void main(String args[]) {
RandomSource.getInstance().nextBoolean(); // warm it up
try { Thread.sleep(20*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException ie) {
}
_log.debug("\n\n\n\nBegin test\n");
long negTime = 0;
for (int i = 0; i < 5; i++) {
@@ -155,17 +165,21 @@ class YKGenerator {
long endNeg = Clock.getInstance().now();
}
_log.debug("YK fetch time for 5 runs: " + negTime + " @ " + negTime / 5l + "ms each");
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) {
}
}
private static class YKPrecalcRunner implements Runnable {
private int _minSize;
private int _maxSize;
private YKPrecalcRunner(int minSize, int maxSize) {
_minSize = minSize;
_maxSize = maxSize;
}
public void run() {
while (true) {
int curSize = 0;
@@ -179,15 +193,24 @@ class YKGenerator {
long end = Clock.getInstance().now();
if (_log.shouldLog(Log.DEBUG)) _log.debug("Precalculated YK value in " + (end - begin) + "ms");
// for some relief...
try { Thread.sleep(CALC_DELAY); } catch (InterruptedException ie) {}
try {
Thread.sleep(CALC_DELAY);
} catch (InterruptedException ie) {
}
}
}
long end = Clock.getInstance().now();
int numCalc = curSize - startSize;
if (numCalc > 0) {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Precalced " + numCalc + " to " + curSize + " in " + (end-start-CALC_DELAY*numCalc) + "ms (not counting " + (CALC_DELAY*numCalc) + "ms relief). now sleeping");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Precalced " + numCalc + " to " + curSize + " in "
+ (end - start - CALC_DELAY * numCalc) + "ms (not counting "
+ (CALC_DELAY * numCalc) + "ms relief). now sleeping");
}
try {
Thread.sleep(CHECK_DELAY);
} catch (InterruptedException ie) {
}
try { Thread.sleep(CHECK_DELAY); } catch (InterruptedException ie) {}
}
}
}

View File

@@ -36,45 +36,42 @@ import java.io.OutputStream;
* @author rob@iharder.net
* @version 1.3.4
*/
public class Base64
{
public static String encode(byte[] source) { return safeEncode(source); }
public static byte[] decode(String s) { return safeDecode(s); }
public class Base64 {
public static String encode(byte[] source) {
return safeEncode(source);
}
public static byte[] decode(String s) {
return safeDecode(s);
}
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte) '\n';
/** The 64 valid Base64 values. */
private final static byte[] ALPHABET =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
private final static byte[] ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R',
(byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X',
(byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
(byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v',
(byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1',
(byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) '+', (byte) '/'};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
private final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
@@ -111,12 +108,11 @@ public class Base64
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/** Defeats instantiation. */
private Base64(){}
private Base64() {
}
public static void main(String[] args)
{
public static void main(String[] args) {
if (args.length == 0) {
help();
return;
@@ -147,14 +143,12 @@ public class Base64
}
}
private static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
byte buf[] = new byte[4096];
while (true) {
int read = in.read(buf);
if (read < 0)
break;
if (read < 0) break;
baos.write(buf, 0, read);
}
return baos.toByteArray();
@@ -180,7 +174,6 @@ public class Base64
System.out.println("or : Base64 test");
}
private static void test() {
String orig = "you smell";
String encoded = Base64.encode(orig.getBytes());
@@ -203,10 +196,8 @@ public class Base64
throw new RuntimeException("D(E([all bytes])) != [all bytes]!!!");
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
@@ -215,12 +206,10 @@ public class Base64
* @return four byte array in Base64 notation.
* @since 1.3
*/
private static byte[] encode3to4( byte[] threeBytes )
{ return encode3to4( threeBytes, 3 );
private static byte[] encode3to4(byte[] threeBytes) {
return encode3to4(threeBytes, 3);
} // end encodeToBytes
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
@@ -234,14 +223,12 @@ public class Base64
* @return four byte array in Base64 notation.
* @since 1.3
*/
private static byte[] encode3to4( byte[] threeBytes, int numSigBytes )
{ byte[] dest = new byte[4];
private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) {
byte[] dest = new byte[4];
encode3to4(threeBytes, 0, numSigBytes, dest, 0);
return dest;
}
/**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
@@ -263,10 +250,7 @@ public class Base64
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset )
{
private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
@@ -282,8 +266,7 @@ public class Base64
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch( numSigBytes )
{
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
@@ -318,8 +301,7 @@ public class Base64
* @param source The data to convert
* @since 1.4
*/
private static String encodeBytes( byte[] source )
{
private static String encodeBytes(byte[] source) {
return encodeBytes(source, false); // don't add newlines
} // end encodeBytes
@@ -334,7 +316,6 @@ public class Base64
return encoded;
}
/**
* Same as decode, except from a filesystem / URL friendly set of characters,
* replacing / with ~, and + with -
@@ -354,12 +335,10 @@ public class Base64
* @param breakLines Break lines at 80 characters or less.
* @since 1.4
*/
private static String encodeBytes( byte[] source, boolean breakLines )
{
private static String encodeBytes(byte[] source, boolean breakLines) {
return encodeBytes(source, 0, source.length, breakLines);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
*
@@ -368,12 +347,10 @@ public class Base64
* @param len Length of data to convert
* @since 1.4
*/
private static String encodeBytes( byte[] source, int off, int len )
{
private static String encodeBytes(byte[] source, int off, int len) {
return encodeBytes(source, off, len, true);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
*
@@ -383,8 +360,7 @@ public class Base64
* @param breakLines Break lines at 80 characters or less.
* @since 1.4
*/
private static String encodeBytes( byte[] source, int off, int len, boolean breakLines )
{
private static String encodeBytes(byte[] source, int off, int len, boolean breakLines) {
int len43 = len * 4 / 3;
byte[] outBuff = new byte[(len43) // Main 4:3
+ ((len % 3) > 0 ? 4 : 0) // Account for padding
@@ -393,21 +369,18 @@ public class Base64
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e);
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
if (breakLines && lineLength == MAX_LINE_LENGTH) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
} // end if: some padding needed
@@ -415,7 +388,6 @@ public class Base64
return new String(outBuff, 0, e);
} // end encodeBytes
/**
* Encodes a string in Base64 notation with line breaks
* after every 75 Base64 characters.
@@ -424,8 +396,7 @@ public class Base64
* @return the encoded string
* @since 1.3
*/
private static String encodeString( String s )
{
private static String encodeString(String s) {
return encodeString(s, true);
} // end encodeString
@@ -438,17 +409,12 @@ public class Base64
* @return the encoded string
* @since 1.3
*/
private static String encodeString( String s, boolean breakLines )
{
private static String encodeString(String s, boolean breakLines) {
return encodeBytes(s.getBytes(), breakLines);
} // end encodeString
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes the first four bytes of array <var>fourBytes</var>
* and returns an array up to three bytes long with the
@@ -458,8 +424,7 @@ public class Base64
* @return array with decoded values
* @since 1.3
*/
private static byte[] decode4to3( byte[] fourBytes )
{
private static byte[] decode4to3(byte[] fourBytes) {
byte[] outBuff1 = new byte[3];
int count = decode4to3(fourBytes, 0, outBuff1, 0);
byte[] outBuff2 = new byte[count];
@@ -470,9 +435,6 @@ public class Base64
return outBuff2;
}
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
@@ -495,11 +457,9 @@ public class Base64
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
{
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) {
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
@@ -511,8 +471,7 @@ public class Base64
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
@@ -527,8 +486,7 @@ public class Base64
}
// Example: DkLE
else
{
else {
try {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
@@ -540,7 +498,6 @@ public class Base64
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
| ((DECODABET[source[srcOffset + 3]] & 0xFF));
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
@@ -563,13 +520,11 @@ public class Base64
* @return the decoded data
* @since 1.4
*/
private static byte[] standardDecode( String s )
{
private static byte[] standardDecode(String s) {
byte[] bytes = s.getBytes();
return decode(bytes, 0, bytes.length);
} // end decode
/**
* Decodes data from Base64 notation and
* returns it as a string.
@@ -580,8 +535,8 @@ public class Base64
* @return The data as a string
* @since 1.4
*/
private static String decodeToString( String s )
{ return new String( decode( s ) );
private static String decodeToString(String s) {
return new String(decode(s));
} // end decodeToString
/**
@@ -594,8 +549,7 @@ public class Base64
* @return decoded data
* @since 1.3
*/
private static byte[] decode( byte[] source, int off, int len )
{
private static byte[] decode(byte[] source, int off, int len) {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0;
@@ -605,31 +559,26 @@ public class Base64
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for( i = 0; i < len; i++ )
{
for (i = 0; i < len; i++) {
sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better
{
if( sbiDecode >= EQUALS_SIGN_ENC )
{
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = sbiCrop;
if( b4Posn > 3 )
{
if (b4Posn > 3) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN )
break;
if (sbiCrop == EQUALS_SIGN) break;
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else
{
else {
System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
return null;
} // end else:

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -18,10 +19,22 @@ import java.io.Serializable;
*/
public class ByteArray implements Serializable {
private byte[] _data;
public ByteArray() { this(null); }
public ByteArray(byte[] data) { _data = data; }
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public ByteArray() {
this(null);
}
public ByteArray(byte[] data) {
_data = data;
}
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public boolean equals(Object o) {
if (o == null) return false;
@@ -41,6 +54,11 @@ public class ByteArray implements Serializable {
return DataHelper.eq(lhs, rhs);
}
public int hashCode() { return DataHelper.hashCode(getData()); }
public String toString() { return DataHelper.toString(getData(), 32); }
public int hashCode() {
return DataHelper.hashCode(getData());
}
public String toString() {
return DataHelper.toString(getData(), 32);
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -45,11 +46,21 @@ public class Certificate extends DataStructureImpl {
}
/** */
public int getCertificateType() { return _type; }
public void setCertificateType(int type) { _type = type; }
public int getCertificateType() {
return _type;
}
public byte[] getPayload() { return _payload; }
public void setPayload(byte[] payload) { _payload = payload; }
public void setCertificateType(int type) {
_type = type;
}
public byte[] getPayload() {
return _payload;
}
public void setPayload(byte[] payload) {
_payload = payload;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_type = (int) DataHelper.readLong(in, 1);
@@ -58,15 +69,14 @@ public class Certificate extends DataStructureImpl {
_payload = new byte[length];
int read = read(in, _payload);
if (read != length)
throw new DataFormatException("Not enough bytes for the payload (read: " + read + " length: " + length + ")");
throw new DataFormatException("Not enough bytes for the payload (read: " + read + " length: " + length
+ ")");
}
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_type < 0)
throw new DataFormatException("Invalid certificate type: " + _type);
if ( (_type != 0) && (_payload == null) )
throw new DataFormatException("Payload is required for non null type");
if (_type < 0) throw new DataFormatException("Invalid certificate type: " + _type);
if ((_type != 0) && (_payload == null)) throw new DataFormatException("Payload is required for non null type");
DataHelper.writeLong(out, 1, (long) _type);
if (_payload != null) {
@@ -78,11 +88,9 @@ public class Certificate extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof Certificate) )
return false;
if ((object == null) || !(object instanceof Certificate)) return false;
Certificate cert = (Certificate) object;
return getCertificateType() == cert.getCertificateType() &&
DataHelper.eq(getPayload(), cert.getPayload());
return getCertificateType() == cert.getCertificateType() && DataHelper.eq(getPayload(), cert.getPayload());
}
public int hashCode() {
@@ -104,8 +112,7 @@ public class Certificate extends DataStructureImpl {
} else {
buf.append(" payload size: ").append(_payload.length);
int len = 32;
if (len > _payload.length)
len = _payload.length;
if (len > _payload.length) len = _payload.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_payload, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,8 +9,8 @@ package net.i2p.data;
*
*/
import net.i2p.util.Log;
import net.i2p.I2PException;
import net.i2p.util.Log;
/**
* Thrown when the data was not available to read or write a DataStructure
@@ -22,6 +23,7 @@ public class DataFormatException extends I2PException {
public DataFormatException(String msg, Throwable t) {
super(msg, t);
}
public DataFormatException(String msg) {
super(msg);
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -60,8 +61,7 @@ public class DataHelper {
long size = readLong(rawStream, 2);
byte data[] = new byte[(int) size];
int read = read(rawStream, data);
if (read != size)
throw new DataFormatException("Not enough data to read the properties");
if (read != size) throw new DataFormatException("Not enough data to read the properties");
ByteArrayInputStream in = new ByteArrayInputStream(data);
byte eqBuf[] = _equal.getBytes();
byte semiBuf[] = _semicolon.getBytes();
@@ -96,10 +96,10 @@ public class DataHelper {
* @throws DataFormatException if there is not enough valid data to write out
* @throws IOException if there is an IO error writing out the data
*/
public static void writeProperties(OutputStream rawStream, Properties props) throws DataFormatException, IOException {
public static void writeProperties(OutputStream rawStream, Properties props) throws DataFormatException,
IOException {
OrderedProperties p = new OrderedProperties();
if (props != null)
p.putAll(props);
if (props != null) p.putAll(props);
ByteArrayOutputStream baos = new ByteArrayOutputStream(32);
for (Iterator iter = p.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
@@ -146,8 +146,7 @@ public class DataHelper {
for (Iterator iter = col.iterator(); iter.hasNext();) {
Object o = iter.next();
buf.append("[").append(o).append("]");
if (iter.hasNext())
buf.append(", ");
if (iter.hasNext()) buf.append(", ");
}
} else {
buf.append("null");
@@ -155,10 +154,11 @@ public class DataHelper {
return buf.toString();
}
public static String toString(byte buf[]) {
if (buf == null) return "";
else return toString(buf, buf.length);
if (buf == null)
return "";
else
return toString(buf, buf.length);
}
public static String toString(byte buf[], int len) {
@@ -178,6 +178,7 @@ public class DataHelper {
}
return out.toString();
}
public static String toDecimalString(byte buf[], int len) {
if (buf == null) buf = "".getBytes();
BigInteger val = new BigInteger(1, buf);
@@ -205,7 +206,8 @@ public class DataHelper {
*/
public static long readLong(InputStream rawStream, int numBytes) throws DataFormatException, IOException {
if (numBytes > 8)
throw new DataFormatException("readLong doesn't currently support reading numbers > 8 bytes [as thats bigger than java's long]");
throw new DataFormatException(
"readLong doesn't currently support reading numbers > 8 bytes [as thats bigger than java's long]");
byte data[] = new byte[numBytes];
int num = read(rawStream, data);
if (num != numBytes)
@@ -223,7 +225,8 @@ public class DataHelper {
* @throws DataFormatException if the stream doesn't contain a validly formatted number of that many bytes
* @throws IOException if there is an IO error writing to the stream
*/
public static void writeLong(OutputStream rawStream, int numBytes, long value) throws DataFormatException, IOException {
public static void writeLong(OutputStream rawStream, int numBytes, long value) throws DataFormatException,
IOException {
UnsignedInteger i = new UnsignedInteger(value);
rawStream.write(i.getBytes(numBytes));
}
@@ -270,10 +273,10 @@ public class DataHelper {
int size = (int) readLong(in, 1);
byte raw[] = new byte[size];
int read = read(in, raw);
if (read != size)
throw new DataFormatException("Not enough bytes to read the string");
if (read != size) throw new DataFormatException("Not enough bytes to read the string");
return new String(raw);
}
/** Write out a string to the stream as specified by the I2P data structure spec. Note that the max
* size for a string allowed by the spec is 255 bytes.
*
@@ -288,7 +291,8 @@ public class DataHelper {
writeLong(out, 1, 0);
} else {
if (string.length() > 255)
throw new DataFormatException("The I2P data spec limits strings to 255 bytes or less, but this is " + string.length() + " [" + string + "]");
throw new DataFormatException("The I2P data spec limits strings to 255 bytes or less, but this is "
+ string.length() + " [" + string + "]");
byte raw[] = string.getBytes();
writeLong(out, 1, raw.length);
out.write(raw);
@@ -312,9 +316,11 @@ public class DataHelper {
case 2:
return null;
default:
throw new DataFormatException("Uhhh.. readBoolean read a value that isn't a known ternary val (0,1,2): " + val);
throw new DataFormatException("Uhhh.. readBoolean read a value that isn't a known ternary val (0,1,2): "
+ val);
}
}
/** Write out a boolean as specified by the I2P data structure spec.
* A boolean is 1 byte that is either 0 (false), 1 (true), or 2 (null)
* @param out stream to write to
@@ -336,7 +342,6 @@ public class DataHelper {
// functions for objects based on their value, not JVM memory address
//
/**
* Helper util to compare two objects, including null handling.
* <p />
@@ -345,14 +350,14 @@ public class DataHelper {
*/
public final static boolean eq(Object lhs, Object rhs) {
try {
boolean eq = ( ( (lhs == null) && (rhs == null) ) ||
( (lhs != null) && (lhs.equals(rhs))) );
boolean eq = (((lhs == null) && (rhs == null)) || ((lhs != null) && (lhs.equals(rhs))));
return eq;
} catch (ClassCastException cce) {
_log.warn("Error comparing [" + lhs + "] with [" + rhs + "]", cce);
return false;
}
}
/**
* Run a deep comparison across the two collections.
* <p />
@@ -372,8 +377,7 @@ public class DataHelper {
Iterator liter = lhs.iterator();
Iterator riter = rhs.iterator();
while ((liter.hasNext()) && (riter.hasNext()))
if (!(eq(liter.next(), riter.next())))
return false;
if (!(eq(liter.next(), riter.next()))) return false;
return true;
}
@@ -385,22 +389,30 @@ public class DataHelper {
*
*/
public final static boolean eq(byte lhs[], byte rhs[]) {
boolean eq = ( ( (lhs == null) && (rhs == null) ) ||
( (lhs != null) && (rhs != null) && (Arrays.equals(lhs, rhs)) ) );
boolean eq = (((lhs == null) && (rhs == null)) || ((lhs != null) && (rhs != null) && (Arrays.equals(lhs, rhs))));
return eq;
}
/**
* Compare two integers, really just for consistency.
*/
public final static boolean eq(int lhs, int rhs) { return lhs == rhs; }
public final static boolean eq(int lhs, int rhs) {
return lhs == rhs;
}
/**
* Compare two longs, really just for consistency.
*/
public final static boolean eq(long lhs, long rhs) { return lhs == rhs; }
public final static boolean eq(long lhs, long rhs) {
return lhs == rhs;
}
/**
* Compare two bytes, really just for consistency.
*/
public final static boolean eq(byte lhs, byte rhs) { return lhs == rhs; }
public final static boolean eq(byte lhs, byte rhs) {
return lhs == rhs;
}
public final static int compareTo(byte lhs[], byte rhs[]) {
if ((rhs == null) && (lhs == null)) return 0;
@@ -409,7 +421,8 @@ public class DataHelper {
if (rhs.length < lhs.length) return 1;
if (rhs.length > lhs.length) return -1;
for (int i = 0; i < rhs.length; i++) {
if (rhs[i] > lhs[i]) return -1;
if (rhs[i] > lhs[i])
return -1;
else if (rhs[i] < lhs[i]) return 1;
}
return 0;
@@ -423,7 +436,6 @@ public class DataHelper {
return diff;
}
//
// The following hashcode helpers make it simpler to write consistently hashing
// functions for objects based on their value, not JVM memory address
@@ -434,17 +446,23 @@ public class DataHelper {
*
*/
public static int hashCode(Object obj) {
if (obj == null) return 0;
else return obj.hashCode();
if (obj == null)
return 0;
else
return obj.hashCode();
}
/**
* Calculate the hashcode of the date, using 0 for null
*
*/
public static int hashCode(Date obj) {
if (obj == null) return 0;
else return (int)obj.getTime();
if (obj == null)
return 0;
else
return (int) obj.getTime();
}
/**
* Calculate the hashcode of the byte array, using 0 for null
*
@@ -485,7 +503,6 @@ public class DataHelper {
return cur;
}
public static List sortStructures(Collection dataStructures) {
if (dataStructures == null) return new ArrayList();
ArrayList rv = new ArrayList(dataStructures.size());
@@ -526,7 +543,8 @@ public class DataHelper {
out.flush();
byte rv[] = baos.toByteArray();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Compression of " + orig.length + " into " + rv.length + " (or " + 100.0d*(((double)orig.length) / ((double)rv.length)) + "% savings)");
_log.debug("Compression of " + orig.length + " into " + rv.length + " (or " + 100.0d
* (((double) orig.length) / ((double) rv.length)) + "% savings)");
return rv;
} catch (IOException ioe) {
_log.error("Error compressing?!", ioe);
@@ -543,13 +561,13 @@ public class DataHelper {
byte buf[] = new byte[4 * 1024];
while (true) {
int read = in.read(buf);
if (read == -1)
break;
if (read == -1) break;
baos.write(buf, 0, read);
}
byte rv[] = baos.toByteArray();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Decompression of " + orig.length + " into " + rv.length + " (or " + 100.0d*(((double)rv.length) / ((double)orig.length)) + "% savings)");
_log.debug("Decompression of " + orig.length + " into " + rv.length + " (or " + 100.0d
* (((double) rv.length) / ((double) orig.length)) + "% savings)");
return rv;
} catch (IOException ioe) {
_log.error("Error decompressing?", ioe);

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.Serializable;
/**
@@ -53,6 +54,7 @@ public interface DataStructure extends Serializable {
public void fromBase64(String data) throws DataFormatException;
public byte[] toByteArray();
public void fromByteArray(byte data[]) throws DataFormatException;
/**

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -26,21 +27,21 @@ public abstract class DataStructureImpl implements DataStructure {
public String toBase64() {
byte data[] = toByteArray();
if (data == null) return null;
else return Base64.encode(data);
if (data == null)
return null;
else
return Base64.encode(data);
}
public void fromBase64(String data) throws DataFormatException {
if (data == null)
throw new DataFormatException("Null data passed in");
if (data == null) throw new DataFormatException("Null data passed in");
byte bytes[] = Base64.decode(data);
fromByteArray(bytes);
}
public Hash calculateHash() {
byte data[] = toByteArray();
if (data != null)
return SHA256Generator.getInstance().calculateHash(data);
if (data != null) return SHA256Generator.getInstance().calculateHash(data);
return null;
}
@@ -59,8 +60,7 @@ public abstract class DataStructureImpl implements DataStructure {
}
public void fromByteArray(byte data[]) throws DataFormatException {
if (data == null)
throw new DataFormatException("Null data passed in");
if (data == null) throw new DataFormatException("Null data passed in");
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
readBytes(bais);

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -34,17 +35,28 @@ public class Destination extends DataStructureImpl {
__calculatedHash = null;
}
public Certificate getCertificate() { return _certificate; }
public Certificate getCertificate() {
return _certificate;
}
public void setCertificate(Certificate cert) {
_certificate = cert;
__calculatedHash = null;
}
public PublicKey getPublicKey() { return _publicKey; }
public PublicKey getPublicKey() {
return _publicKey;
}
public void setPublicKey(PublicKey key) {
_publicKey = key;
__calculatedHash = null;
}
public SigningPublicKey getSigningPublicKey() { return _signingKey; }
public SigningPublicKey getSigningPublicKey() {
return _signingKey;
}
public void setSigningPublicKey(SigningPublicKey key) {
_signingKey = key;
__calculatedHash = null;
@@ -69,18 +81,16 @@ public class Destination extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof Destination))
return false;
if ((object == null) || !(object instanceof Destination)) return false;
Destination dst = (Destination) object;
return DataHelper.eq(getCertificate(), dst.getCertificate()) &&
DataHelper.eq(getSigningPublicKey(), dst.getSigningPublicKey()) &&
DataHelper.eq(getPublicKey(), dst.getPublicKey());
return DataHelper.eq(getCertificate(), dst.getCertificate())
&& DataHelper.eq(getSigningPublicKey(), dst.getSigningPublicKey())
&& DataHelper.eq(getPublicKey(), dst.getPublicKey());
}
public int hashCode() {
return DataHelper.hashCode(getCertificate()) +
DataHelper.hashCode(getSigningPublicKey()) +
DataHelper.hashCode(getPublicKey());
return DataHelper.hashCode(getCertificate()) + DataHelper.hashCode(getSigningPublicKey())
+ DataHelper.hashCode(getPublicKey());
}
public String toString() {
@@ -95,8 +105,7 @@ public class Destination extends DataStructureImpl {
}
public Hash calculateHash() {
if (__calculatedHash == null)
__calculatedHash = super.calculateHash();
if (__calculatedHash == null) __calculatedHash = super.calculateHash();
return __calculatedHash;
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -28,10 +29,18 @@ public class Hash extends DataStructureImpl {
public final static int HASH_LENGTH = 32;
public final static Hash FAKE_HASH = new Hash(new byte[HASH_LENGTH]);
public Hash() { setData(null); }
public Hash(byte data[]) { setData(data); }
public Hash() {
setData(null);
}
public Hash(byte data[]) {
setData(data);
}
public byte[] getData() {
return _data;
}
public byte[] getData() { return _data; }
public void setData(byte[] data) {
_data = data;
_stringified = null;
@@ -41,27 +50,24 @@ public class Hash extends DataStructureImpl {
_data = new byte[HASH_LENGTH];
_stringified = null;
int read = read(in, _data);
if (read != HASH_LENGTH)
throw new DataFormatException("Not enough bytes to read the hash");
if (read != HASH_LENGTH) throw new DataFormatException("Not enough bytes to read the hash");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the hash to write out");
if (_data.length != HASH_LENGTH)
throw new DataFormatException("Invalid size of data in the private key");
if (_data == null) throw new DataFormatException("No data in the hash to write out");
if (_data.length != HASH_LENGTH) throw new DataFormatException("Invalid size of data in the private key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof Hash))
return false;
if ((obj == null) || !(obj instanceof Hash)) return false;
return DataHelper.eq(_data, ((Hash) obj)._data);
}
public int hashCode() {
return DataHelper.hashCode(_data);
}
public String toString() {
if (_stringified == null) {
StringBuffer buf = new StringBuffer(64);

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -13,8 +14,8 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Defines the proof that a particular router / tunnel is allowed to receive
@@ -41,40 +42,70 @@ public class Lease extends DataStructureImpl {
/** Retrieve the router at which the destination can be contacted
* @return identity of the router acting as a gateway
*/
public RouterIdentity getRouterIdentity() { return _routerIdentity; }
public RouterIdentity getRouterIdentity() {
return _routerIdentity;
}
/** Configure the router at which the destination can be contacted
* @param ident router acting as the gateway
*/
public void setRouterIdentity(RouterIdentity ident) { _routerIdentity = ident; }
public void setRouterIdentity(RouterIdentity ident) {
_routerIdentity = ident;
}
/** Tunnel on the gateway to communicate with
* @return tunnel ID
*/
public TunnelId getTunnelId() { return _tunnelId; }
public TunnelId getTunnelId() {
return _tunnelId;
}
/** Configure the tunnel on the gateway to communicate with
* @param id tunnel ID
*/
public void setTunnelId(TunnelId id) { _tunnelId = id; }
public Date getEndDate() { return _end; }
public void setEndDate(Date date) { _end = date; }
public void setTunnelId(TunnelId id) {
_tunnelId = id;
}
public Date getEndDate() {
return _end;
}
public void setEndDate(Date date) {
_end = date;
}
/**
* Transient attribute of the lease, used to note how many times messages sent
* to the destination through the current lease were successful.
*
*/
public int getNumSuccess() { return _numSuccess; }
public void setNumSuccess(int num) { _numSuccess = num; }
public int getNumSuccess() {
return _numSuccess;
}
public void setNumSuccess(int num) {
_numSuccess = num;
}
/**
* Transient attribute of the lease, used to note how many times messages sent
* to the destination through the current lease failed.
*
*/
public int getNumFailure() { return _numFailure; }
public void setNumFailure(int num) { _numFailure = num; }
public int getNumFailure() {
return _numFailure;
}
public void setNumFailure(int num) {
_numFailure = num;
}
/** has this lease already expired? */
public boolean isExpired() { return isExpired(0); }
public boolean isExpired() {
return isExpired(0);
}
/** has this lease already expired (giving allowing up the fudgeFactor milliseconds for clock skew)? */
public boolean isExpired(long fudgeFactor) {
if (_end == null) return true;
@@ -99,18 +130,16 @@ public class Lease extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof Lease) )
return false;
if ((object == null) || !(object instanceof Lease)) return false;
Lease lse = (Lease) object;
return DataHelper.eq(getEndDate(), lse.getEndDate()) &&
DataHelper.eq(getRouterIdentity(), lse.getRouterIdentity());
return DataHelper.eq(getEndDate(), lse.getEndDate())
&& DataHelper.eq(getRouterIdentity(), lse.getRouterIdentity());
}
public int hashCode() {
return DataHelper.hashCode(getEndDate()) +
DataHelper.hashCode(getRouterIdentity()) +
DataHelper.hashCode(getTunnelId());
return DataHelper.hashCode(getEndDate()) + DataHelper.hashCode(getRouterIdentity())
+ DataHelper.hashCode(getTunnelId());
}
public String toString() {

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -17,8 +18,8 @@ import java.util.Iterator;
import java.util.List;
import net.i2p.crypto.DSAEngine;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Defines the set of leases a destination currently has.
@@ -48,18 +49,53 @@ public class LeaseSet extends DataStructureImpl {
_routingKeyGenMod = null;
}
public Destination getDestination() { return _destination; }
public void setDestination(Destination dest) { _destination = dest; }
public PublicKey getEncryptionKey() { return _encryptionKey; }
public void setEncryptionKey(PublicKey encryptionKey) { _encryptionKey = encryptionKey; }
public SigningPublicKey getSigningKey() { return _signingKey; }
public void setSigningKey(SigningPublicKey key) { _signingKey = key; }
public void addLease(Lease lease) { _leases.add(lease); }
public void removeLease(Lease lease) { _leases.remove(lease); }
public int getLeaseCount() { return _leases.size(); }
public Lease getLease(int index) { return (Lease)_leases.get(index); }
public Signature getSignature() { return _signature; }
public void setSignature(Signature sig) { _signature = sig; }
public Destination getDestination() {
return _destination;
}
public void setDestination(Destination dest) {
_destination = dest;
}
public PublicKey getEncryptionKey() {
return _encryptionKey;
}
public void setEncryptionKey(PublicKey encryptionKey) {
_encryptionKey = encryptionKey;
}
public SigningPublicKey getSigningKey() {
return _signingKey;
}
public void setSigningKey(SigningPublicKey key) {
_signingKey = key;
}
public void addLease(Lease lease) {
_leases.add(lease);
}
public void removeLease(Lease lease) {
_leases.remove(lease);
}
public int getLeaseCount() {
return _leases.size();
}
public Lease getLease(int index) {
return (Lease) _leases.get(index);
}
public Signature getSignature() {
return _signature;
}
public void setSignature(Signature sig) {
_signature = sig;
}
/**
* Get the routing key for the structure using the current modifier in the RoutingKeyGenerator.
@@ -68,13 +104,17 @@ public class LeaseSet extends DataStructureImpl {
*/
public Hash getRoutingKey() {
RoutingKeyGenerator gen = RoutingKeyGenerator.getInstance();
if ( (gen.getModData() == null) || (_routingKeyGenMod == null) || (!DataHelper.eq(gen.getModData(), _routingKeyGenMod)) ) {
if ((gen.getModData() == null) || (_routingKeyGenMod == null)
|| (!DataHelper.eq(gen.getModData(), _routingKeyGenMod))) {
setRoutingKey(gen.getRoutingKey(getDestination().calculateHash()));
_routingKeyGenMod = gen.getModData();
}
return _currentRoutingKey;
}
public void setRoutingKey(Hash key) { _currentRoutingKey = key; }
public void setRoutingKey(Hash key) {
_currentRoutingKey = key;
}
public boolean validateRoutingKey() {
Hash destKey = getDestination().calculateHash();
@@ -98,8 +138,7 @@ public class LeaseSet extends DataStructureImpl {
for (int i = 0; i < getLeaseCount(); i++) {
Lease lse = (Lease) getLease(i);
if ((lse != null) && (lse.getEndDate() != null)) {
if ( (when <= 0) || (lse.getEndDate().getTime() < when) )
when = lse.getEndDate().getTime();
if ((when <= 0) || (lse.getEndDate().getTime() < when)) when = lse.getEndDate().getTime();
}
}
return when;
@@ -127,13 +166,15 @@ public class LeaseSet extends DataStructureImpl {
if (getDestination() == null) return false;
byte data[] = getBytes();
if (data == null) return false;
boolean signedByDest = DSAEngine.getInstance().verifySignature(getSignature(), data, getDestination().getSigningPublicKey());
boolean signedByDest = DSAEngine.getInstance().verifySignature(getSignature(), data,
getDestination().getSigningPublicKey());
boolean signedByRevoker = false;
if (!signedByDest) {
signedByRevoker = DSAEngine.getInstance().verifySignature(getSignature(), data, _signingKey);
}
return signedByDest || signedByRevoker;
}
/**
* Verify that the signature matches the lease set's destination's signing public key.
*
@@ -144,7 +185,8 @@ public class LeaseSet extends DataStructureImpl {
if (getDestination() == null) return false;
byte data[] = getBytes();
if (data == null) return false;
boolean signedByDest = DSAEngine.getInstance().verifySignature(getSignature(), data, getDestination().getSigningPublicKey());
boolean signedByDest = DSAEngine.getInstance().verifySignature(getSignature(), data,
getDestination().getSigningPublicKey());
boolean signedByRevoker = false;
if (!signedByDest) {
signedByRevoker = DSAEngine.getInstance().verifySignature(getSignature(), data, signingKey);
@@ -174,7 +216,8 @@ public class LeaseSet extends DataStructureImpl {
_log.debug("LeaseSet " + calculateHash() + " isn't exired: " + l);
return true;
} else if (l.getEndDate().getTime() > now - fudge) {
_log.debug("LeaseSet " + calculateHash() + " isn't quite expired, but its within the fudge factor so we'll let it slide: " + l);
_log.debug("LeaseSet " + calculateHash()
+ " isn't quite expired, but its within the fudge factor so we'll let it slide: " + l);
return true;
}
}
@@ -184,8 +227,7 @@ public class LeaseSet extends DataStructureImpl {
private byte[] getBytes() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
if ( (_destination == null) || (_encryptionKey == null) || (_signingKey == null) ||
(_leases == null) )
if ((_destination == null) || (_encryptionKey == null) || (_signingKey == null) || (_leases == null))
return null;
_destination.writeBytes(out);
@@ -225,9 +267,8 @@ public class LeaseSet extends DataStructureImpl {
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if ( (_destination == null) || (_encryptionKey == null) || (_signingKey == null) ||
(_leases == null) || (_signature == null) )
throw new DataFormatException("Not enough data to write out a LeaseSet");
if ((_destination == null) || (_encryptionKey == null) || (_signingKey == null) || (_leases == null)
|| (_signature == null)) throw new DataFormatException("Not enough data to write out a LeaseSet");
_destination.writeBytes(out);
_encryptionKey.writeBytes(out);
@@ -242,25 +283,21 @@ public class LeaseSet extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof LeaseSet) )
return false;
if ((object == null) || !(object instanceof LeaseSet)) return false;
LeaseSet ls = (LeaseSet) object;
return DataHelper.eq(getEncryptionKey(), ls.getEncryptionKey()) &&
//DataHelper.eq(getVersion(), ls.getVersion()) &&
DataHelper.eq(_leases, ls._leases) &&
DataHelper.eq(getSignature(), ls.getSignature()) &&
DataHelper.eq(getSigningKey(), ls.getSigningKey()) &&
DataHelper.eq(getDestination(), ls.getDestination());
DataHelper.eq(_leases, ls._leases) && DataHelper.eq(getSignature(), ls.getSignature())
&& DataHelper.eq(getSigningKey(), ls.getSigningKey())
&& DataHelper.eq(getDestination(), ls.getDestination());
}
public int hashCode() {
return DataHelper.hashCode(getEncryptionKey()) +
//(int)_version +
DataHelper.hashCode(_leases) +
DataHelper.hashCode(getSignature()) +
DataHelper.hashCode(getSigningKey()) +
DataHelper.hashCode(getDestination());
DataHelper.hashCode(_leases) + DataHelper.hashCode(getSignature())
+ DataHelper.hashCode(getSigningKey()) + DataHelper.hashCode(getDestination());
}
public String toString() {

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -39,14 +40,23 @@ public class Payload extends DataStructureImpl {
public byte[] getUnencryptedData() {
return _unencryptedData;
}
/**
* Populate the message body with data. This does not automatically encrypt
* yet.
*
*/
public void setUnencryptedData(byte[] data) { _unencryptedData = data; }
public byte[] getEncryptedData() { return _encryptedData; }
public void setEncryptedData(byte[] data) { _encryptedData = data; }
public void setUnencryptedData(byte[] data) {
_unencryptedData = data;
}
public byte[] getEncryptedData() {
return _encryptedData;
}
public void setEncryptedData(byte[] data) {
_encryptedData = data;
}
public int getSize() {
if (_unencryptedData != null)
@@ -61,26 +71,22 @@ public class Payload extends DataStructureImpl {
int size = (int) DataHelper.readLong(in, 4);
_encryptedData = new byte[size];
int read = read(in, _encryptedData);
if (read != size)
throw new DataFormatException("Incorrect number of bytes read in the payload structure");
if (read != size) throw new DataFormatException("Incorrect number of bytes read in the payload structure");
_log.debug("read payload: " + read + " bytes");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_encryptedData == null)
throw new DataFormatException("Not yet encrypted. Please set the encrypted data");
if (_encryptedData == null) throw new DataFormatException("Not yet encrypted. Please set the encrypted data");
DataHelper.writeLong(out, 4, _encryptedData.length);
out.write(_encryptedData);
_log.debug("wrote payload: " + _encryptedData.length);
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof Payload) )
return false;
if ((object == null) || !(object instanceof Payload)) return false;
Payload p = (Payload) object;
return DataHelper.eq(getUnencryptedData(), p.getUnencryptedData()) &&
DataHelper.eq(getEncryptedData(), p.getEncryptedData());
return DataHelper.eq(getUnencryptedData(), p.getUnencryptedData())
&& DataHelper.eq(getEncryptedData(), p.getEncryptedData());
}
public int hashCode() {

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -27,29 +28,33 @@ public class PrivateKey extends DataStructureImpl {
public final static int KEYSIZE_BYTES = 256;
public PrivateKey() { setData(null); }
public PrivateKey() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[KEYSIZE_BYTES];
int read = read(in, _data);
if (read != KEYSIZE_BYTES)
throw new DataFormatException("Not enough bytes to read the private key");
if (read != KEYSIZE_BYTES) throw new DataFormatException("Not enough bytes to read the private key");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the private key to write out");
if (_data == null) throw new DataFormatException("No data in the private key to write out");
if (_data.length != KEYSIZE_BYTES)
throw new DataFormatException("Invalid size of data in the private key [" + _data.length + "]");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof PrivateKey))
return false;
if ((obj == null) || !(obj instanceof PrivateKey)) return false;
return DataHelper.eq(_data, ((PrivateKey) obj)._data);
}
@@ -65,8 +70,7 @@ public class PrivateKey extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -27,35 +28,39 @@ public class PublicKey extends DataStructureImpl {
public final static int KEYSIZE_BYTES = 256;
public PublicKey() { setData(null); }
public PublicKey() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[KEYSIZE_BYTES];
int read = read(in, _data);
if (read != KEYSIZE_BYTES)
throw new DataFormatException("Not enough bytes to read the public key");
if (read != KEYSIZE_BYTES) throw new DataFormatException("Not enough bytes to read the public key");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the public key to write out");
if (_data.length != KEYSIZE_BYTES)
throw new DataFormatException("Invalid size of data in the public key");
if (_data == null) throw new DataFormatException("No data in the public key to write out");
if (_data.length != KEYSIZE_BYTES) throw new DataFormatException("Invalid size of data in the public key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof PublicKey))
return false;
if ((obj == null) || !(obj instanceof PublicKey)) return false;
return DataHelper.eq(_data, ((PublicKey) obj)._data);
}
public int hashCode() {
return DataHelper.hashCode(_data);
}
public String toString() {
StringBuffer buf = new StringBuffer(64);
buf.append("[PublicKey: ");
@@ -64,8 +69,7 @@ public class PublicKey extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,13 +9,12 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Iterator;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import net.i2p.util.Log;
@@ -43,44 +43,67 @@ public class RouterAddress extends DataStructureImpl {
* No value above 255 is allowed.
*
*/
public int getCost() { return _cost; }
public int getCost() {
return _cost;
}
/**
* Configure the weighted cost of using the address.
* No value above 255 is allowed.
*
*/
public void setCost(int cost) { _cost = cost; }
public void setCost(int cost) {
_cost = cost;
}
/**
* Retrieve the date after which the address should not be used. If this
* is null, then the address never expires.
*
*/
public Date getExpiration() { return _expiration; }
public Date getExpiration() {
return _expiration;
}
/**
* Configure the expiration date of the address (null for no expiration)
*
*/
public void setExpiration(Date expiration) { _expiration = expiration; }
public void setExpiration(Date expiration) {
_expiration = expiration;
}
/**
* Retrieve the type of transport that must be used to communicate on this address.
*
*/
public String getTransportStyle() { return _transportStyle; }
public String getTransportStyle() {
return _transportStyle;
}
/**
* Configure the type of transport that must be used to communicate on this address
*
*/
public void setTransportStyle(String transportStyle) { _transportStyle = transportStyle; }
public void setTransportStyle(String transportStyle) {
_transportStyle = transportStyle;
}
/**
* Retrieve the transport specific options necessary for communication
*
*/
public Properties getOptions() { return _options; }
public Properties getOptions() {
return _options;
}
/**
* Specify the transport specific options necessary for communication
*
*/
public void setOptions(Properties options) { _options = options; }
public void setOptions(Properties options) {
_options = options;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_cost = (int) DataHelper.readLong(in, 1);
@@ -99,20 +122,16 @@ public class RouterAddress extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof RouterAddress) )
return false;
if ((object == null) || !(object instanceof RouterAddress)) return false;
RouterAddress addr = (RouterAddress) object;
return DataHelper.eq(getCost(), addr.getCost()) &&
DataHelper.eq(getExpiration(), addr.getExpiration()) &&
DataHelper.eq(getOptions(), addr.getOptions()) &&
DataHelper.eq(getTransportStyle(), addr.getTransportStyle());
return DataHelper.eq(getCost(), addr.getCost()) && DataHelper.eq(getExpiration(), addr.getExpiration())
&& DataHelper.eq(getOptions(), addr.getOptions())
&& DataHelper.eq(getTransportStyle(), addr.getTransportStyle());
}
public int hashCode() {
return getCost() +
DataHelper.hashCode(getTransportStyle()) +
DataHelper.hashCode(getExpiration()) +
DataHelper.hashCode(getOptions());
return getCost() + DataHelper.hashCode(getTransportStyle()) + DataHelper.hashCode(getExpiration())
+ DataHelper.hashCode(getOptions());
}
public String toString() {

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,10 +9,10 @@ package net.i2p.data;
*
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.i2p.crypto.SHA256Generator;
import net.i2p.util.Log;
@@ -36,17 +37,28 @@ public class RouterIdentity extends DataStructureImpl {
__calculatedHash = null;
}
public Certificate getCertificate() { return _certificate; }
public Certificate getCertificate() {
return _certificate;
}
public void setCertificate(Certificate cert) {
_certificate = cert;
__calculatedHash = null;
}
public PublicKey getPublicKey() { return _publicKey; }
public PublicKey getPublicKey() {
return _publicKey;
}
public void setPublicKey(PublicKey key) {
_publicKey = key;
__calculatedHash = null;
}
public SigningPublicKey getSigningPublicKey() { return _signingKey; }
public SigningPublicKey getSigningPublicKey() {
return _signingKey;
}
public void setSigningPublicKey(SigningPublicKey key) {
_signingKey = key;
__calculatedHash = null;
@@ -71,19 +83,18 @@ public class RouterIdentity extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof RouterIdentity) )
return false;
if ((object == null) || !(object instanceof RouterIdentity)) return false;
RouterIdentity ident = (RouterIdentity) object;
return DataHelper.eq(getCertificate(), ident.getCertificate()) &&
DataHelper.eq(getSigningPublicKey(), ident.getSigningPublicKey()) &&
DataHelper.eq(getPublicKey(), ident.getPublicKey());
return DataHelper.eq(getCertificate(), ident.getCertificate())
&& DataHelper.eq(getSigningPublicKey(), ident.getSigningPublicKey())
&& DataHelper.eq(getPublicKey(), ident.getPublicKey());
}
public int hashCode() {
return DataHelper.hashCode(getCertificate()) +
DataHelper.hashCode(getSigningPublicKey()) +
DataHelper.hashCode(getPublicKey());
return DataHelper.hashCode(getCertificate()) + DataHelper.hashCode(getSigningPublicKey())
+ DataHelper.hashCode(getPublicKey());
}
public String toString() {
StringBuffer buf = new StringBuffer(64);
buf.append("[RouterIdentity: ");
@@ -95,13 +106,14 @@ public class RouterIdentity extends DataStructureImpl {
return buf.toString();
}
public Hash calculateHash() { return getHash(); }
public Hash calculateHash() {
return getHash();
}
public Hash getHash() {
if (__calculatedHash != null) {
//_log.info("Returning cached ident hash");
return __calculatedHash;
}
return __calculatedHash; }
byte identBytes[] = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,23 +9,22 @@ package net.i2p.data;
*
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Set;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.List;
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import net.i2p.util.Log;
import net.i2p.util.OrderedProperties;
import net.i2p.util.Clock;
import net.i2p.crypto.DSAEngine;
import net.i2p.crypto.SHA256Generator;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.OrderedProperties;
/**
* Defines the data that a router either publishes to the global routing table or
@@ -80,7 +80,10 @@ public class RouterInfo extends DataStructureImpl {
* Retrieve the identity of the router represented
*
*/
public RouterIdentity getIdentity() { return _identity; }
public RouterIdentity getIdentity() {
return _identity;
}
/**
* Configure the identity of the router represented
*
@@ -89,6 +92,7 @@ public class RouterInfo extends DataStructureImpl {
_identity = ident;
resetCache();
}
/**
* Retrieve the approximate date on which the info was published
* (essentially a version number for the routerInfo structure, except that
@@ -97,12 +101,18 @@ public class RouterInfo extends DataStructureImpl {
* old routerInfo structures
*
*/
public long getPublished() { return _published; }
public long getPublished() {
return _published;
}
/**
* Date on which it was published, in milliseconds since Midnight GMT on Jan 01, 1970
*
*/
public void setPublished(long published) { _published = published; }
public void setPublished(long published) {
_published = published;
}
/**
* Retrieve the set of RouterAddress structures at which this
* router can be contacted.
@@ -113,6 +123,7 @@ public class RouterInfo extends DataStructureImpl {
return new HashSet(_addresses);
}
}
/**
* Specify a set of RouterAddress structures at which this router
* can be contacted.
@@ -121,17 +132,20 @@ public class RouterInfo extends DataStructureImpl {
public void setAddresses(Set addresses) {
synchronized (_addresses) {
_addresses.clear();
if (addresses != null)
_addresses.addAll(addresses);
if (addresses != null) _addresses.addAll(addresses);
}
resetCache();
}
/**
* Retrieve a set of SHA-256 hashes of RouterIdentities from rotuers
* this router can be reached through.
*
*/
public Set getPeers() { return _peers; }
public Set getPeers() {
return _peers;
}
/**
* Specify a set of SHA-256 hashes of RouterIdentities from rotuers
* this router can be reached through.
@@ -140,11 +154,11 @@ public class RouterInfo extends DataStructureImpl {
public void setPeers(Set peers) {
synchronized (_peers) {
_peers.clear();
if (peers != null)
_peers.addAll(peers);
if (peers != null) _peers.addAll(peers);
}
resetCache();
}
/**
* Retrieve a set of options or statistics that the router can expose
*
@@ -155,6 +169,7 @@ public class RouterInfo extends DataStructureImpl {
return (Properties) _options.clone();
}
}
/**
* Configure a set of options or statistics that the router can expose
*
@@ -174,11 +189,15 @@ public class RouterInfo extends DataStructureImpl {
}
resetCache();
}
/**
* Retrieve the proof that the identity stands behind the info here
*
*/
public Signature getSignature() { return _signature; }
public Signature getSignature() {
return _signature;
}
/**
* Configure the proof that the entity stands behind the info here
*
@@ -246,8 +265,7 @@ public class RouterInfo extends DataStructureImpl {
*
*/
public synchronized boolean isValid() {
if (!_validated)
doValidate();
if (!_validated) doValidate();
return _isValid;
}
@@ -258,13 +276,17 @@ public class RouterInfo extends DataStructureImpl {
*/
public synchronized Hash getRoutingKey() {
RoutingKeyGenerator gen = RoutingKeyGenerator.getInstance();
if ( (gen.getModData() == null) || (_routingKeyGenMod == null) || (!DataHelper.eq(gen.getModData(), _routingKeyGenMod)) ) {
if ((gen.getModData() == null) || (_routingKeyGenMod == null)
|| (!DataHelper.eq(gen.getModData(), _routingKeyGenMod))) {
setRoutingKey(gen.getRoutingKey(getIdentity().getHash()));
_routingKeyGenMod = gen.getModData();
}
return _currentRoutingKey;
}
public void setRoutingKey(Hash key) { _currentRoutingKey = key; }
public void setRoutingKey(Hash key) {
_currentRoutingKey = key;
}
public boolean validateRoutingKey() {
Hash identKey = getIdentity().getHash();
@@ -275,7 +297,6 @@ public class RouterInfo extends DataStructureImpl {
return false;
}
/**
* Determine whether the router was published recently (within the given age milliseconds).
* The age should be large enough to take into consideration any clock fudge factor, so
@@ -318,7 +339,8 @@ public class RouterInfo extends DataStructureImpl {
}
_isValid = DSAEngine.getInstance().verifySignature(_signature, data, _identity.getSigningPublicKey());
if (!_isValid) {
_log.error("Invalid [" + SHA256Generator.getInstance().calculateHash(data).toBase64() + "] w/ signing key: " + _identity.getSigningPublicKey(), new Exception("Signature failed"));
_log.error("Invalid [" + SHA256Generator.getInstance().calculateHash(data).toBase64()
+ "] w/ signing key: " + _identity.getSigningPublicKey(), new Exception("Signature failed"));
_log.debug("Failed data: \n" + Base64.encode(data));
_log.debug("Signature: " + getSignature());
}
@@ -350,12 +372,9 @@ public class RouterInfo extends DataStructureImpl {
}
public synchronized void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_identity == null)
throw new DataFormatException("Missing identity");
if (_published <= 0)
throw new DataFormatException("Invalid published date: " + _published);
if (_signature == null)
throw new DataFormatException("Signature is null");
if (_identity == null) throw new DataFormatException("Missing identity");
if (_published <= 0) throw new DataFormatException("Invalid published date: " + _published);
if (_signature == null) throw new DataFormatException("Signature is null");
//if (!isValid())
// throw new DataFormatException("Data is not valid");
ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
@@ -380,29 +399,22 @@ public class RouterInfo extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof RouterInfo) )
return false;
if ((object == null) || !(object instanceof RouterInfo)) return false;
RouterInfo info = (RouterInfo) object;
return DataHelper.eq(getAddresses(), info.getAddresses()) &&
DataHelper.eq(getIdentity(), info.getIdentity()) &&
DataHelper.eq(getOptions(), info.getOptions()) &&
DataHelper.eq(getPeers(), info.getPeers()) &&
DataHelper.eq(getSignature(), info.getSignature()) &&
DataHelper.eq(getPublished(), info.getPublished());
return DataHelper.eq(getAddresses(), info.getAddresses()) && DataHelper.eq(getIdentity(), info.getIdentity())
&& DataHelper.eq(getOptions(), info.getOptions()) && DataHelper.eq(getPeers(), info.getPeers())
&& DataHelper.eq(getSignature(), info.getSignature())
&& DataHelper.eq(getPublished(), info.getPublished());
}
public int hashCode() {
return DataHelper.hashCode(getAddresses()) +
DataHelper.hashCode(getIdentity()) +
DataHelper.hashCode(getOptions()) +
DataHelper.hashCode(getPeers()) +
DataHelper.hashCode(getSignature()) +
(int)getPublished();
return DataHelper.hashCode(getAddresses()) + DataHelper.hashCode(getIdentity())
+ DataHelper.hashCode(getOptions()) + DataHelper.hashCode(getPeers())
+ DataHelper.hashCode(getSignature()) + (int) getPublished();
}
public String toString() {
if (_stringified != null)
return _stringified;
if (_stringified != null) return _stringified;
StringBuffer buf = new StringBuffer(128);
buf.append("[RouterInfo: ");
buf.append("\n\tIdentity: ").append(getIdentity());

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,17 +9,16 @@ package net.i2p.data;
*
*/
import net.i2p.crypto.SHA256Generator;
import net.i2p.util.Log;
import net.i2p.util.RandomSource;
import net.i2p.util.Clock;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Date;
import java.text.SimpleDateFormat;
import net.i2p.crypto.SHA256Generator;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.util.RandomSource;
/**
* Component to manage the munging of hashes into routing keys - given a hash,
@@ -41,14 +41,20 @@ import java.text.SimpleDateFormat;
*/
public class RoutingKeyGenerator {
private final static RoutingKeyGenerator _instance = new RoutingKeyGenerator();
public static RoutingKeyGenerator getInstance() { return _instance; }
public static RoutingKeyGenerator getInstance() {
return _instance;
}
private final static Log _log = new Log(RoutingKeyGenerator.class);
private byte _currentModData[];
private final static Calendar _cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
private final static SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd");
public byte[] getModData() { return _currentModData; }
public byte[] getModData() {
return _currentModData;
}
public void setModData(byte modData[]) {
_currentModData = modData;
}
@@ -86,8 +92,7 @@ public class RoutingKeyGenerator {
* @throws IllegalArgumentException if origKey is null
*/
public Hash getRoutingKey(Hash origKey) {
if (origKey == null)
throw new IllegalArgumentException("Original key is null");
if (origKey == null) throw new IllegalArgumentException("Original key is null");
if (_currentModData == null) generateDateBasedModData();
byte modVal[] = new byte[Hash.HASH_LENGTH + _currentModData.length];
System.arraycopy(origKey.getData(), 0, modVal, 0, Hash.HASH_LENGTH);
@@ -107,6 +112,9 @@ public class RoutingKeyGenerator {
System.out.println("MOD: " + new String(RoutingKeyGenerator.getInstance().getModData()));
System.out.println("K1M: " + k1m);
}
try { Thread.sleep(2000); } catch (Throwable t) {}
try {
Thread.sleep(2000);
} catch (Throwable t) {
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -26,29 +27,32 @@ public class SessionKey extends DataStructureImpl {
public final static int KEYSIZE_BYTES = 32;
public SessionKey() { setData(null); }
public SessionKey() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[KEYSIZE_BYTES];
int read = read(in, _data);
if (read != KEYSIZE_BYTES)
throw new DataFormatException("Not enough bytes to read the session key");
if (read != KEYSIZE_BYTES) throw new DataFormatException("Not enough bytes to read the session key");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the session key to write out");
if (_data.length != KEYSIZE_BYTES)
throw new DataFormatException("Invalid size of data in the private key");
if (_data == null) throw new DataFormatException("No data in the session key to write out");
if (_data.length != KEYSIZE_BYTES) throw new DataFormatException("Invalid size of data in the private key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof SessionKey))
return false;
if ((obj == null) || !(obj instanceof SessionKey)) return false;
return DataHelper.eq(_data, ((SessionKey) obj)._data);
}
@@ -64,8 +68,7 @@ public class SessionKey extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -12,7 +13,11 @@ import net.i2p.util.RandomSource;
public class SessionTag extends ByteArray {
public final static int BYTE_LENGTH = 32;
public SessionTag() { super(); }
public SessionTag() {
super();
}
public SessionTag(boolean create) {
super();
if (create) {
@@ -21,6 +26,7 @@ public class SessionTag extends ByteArray {
setData(buf);
}
}
public SessionTag(byte val[]) {
super();
setData(val);
@@ -28,7 +34,8 @@ public class SessionTag extends ByteArray {
public void setData(byte val[]) throws IllegalArgumentException {
if (val == null) super.setData(null);
if (val.length != BYTE_LENGTH) throw new IllegalArgumentException("SessionTags must be " + BYTE_LENGTH + " bytes");
if (val.length != BYTE_LENGTH)
throw new IllegalArgumentException("SessionTags must be " + BYTE_LENGTH + " bytes");
super.setData(val);
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -32,29 +33,32 @@ public class Signature extends DataStructureImpl {
FAKE_SIGNATURE[i] = 0x00;
}
public Signature() { setData(null); }
public Signature() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[SIGNATURE_BYTES];
int read = read(in, _data);
if (read != SIGNATURE_BYTES)
throw new DataFormatException("Not enough bytes to read the signature");
if (read != SIGNATURE_BYTES) throw new DataFormatException("Not enough bytes to read the signature");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the signature to write out");
if (_data.length != SIGNATURE_BYTES)
throw new DataFormatException("Invalid size of data in the private key");
if (_data == null) throw new DataFormatException("No data in the signature to write out");
if (_data.length != SIGNATURE_BYTES) throw new DataFormatException("Invalid size of data in the private key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof Signature))
return false;
if ((obj == null) || !(obj instanceof Signature)) return false;
return DataHelper.eq(_data, ((Signature) obj)._data);
}
@@ -70,8 +74,7 @@ public class Signature extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -28,29 +29,32 @@ public class SigningPrivateKey extends DataStructureImpl {
public final static int KEYSIZE_BYTES = 20;
public SigningPrivateKey() { setData(null); }
public SigningPrivateKey() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[KEYSIZE_BYTES];
int read = read(in, _data);
if (read != KEYSIZE_BYTES)
throw new DataFormatException("Not enough bytes to read the private key");
if (read != KEYSIZE_BYTES) throw new DataFormatException("Not enough bytes to read the private key");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the private key to write out");
if (_data.length != KEYSIZE_BYTES)
throw new DataFormatException("Invalid size of data in the private key");
if (_data == null) throw new DataFormatException("No data in the private key to write out");
if (_data.length != KEYSIZE_BYTES) throw new DataFormatException("Invalid size of data in the private key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof SigningPrivateKey))
return false;
if ((obj == null) || !(obj instanceof SigningPrivateKey)) return false;
return DataHelper.eq(_data, ((SigningPrivateKey) obj)._data);
}
@@ -66,8 +70,7 @@ public class SigningPrivateKey extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,9 +9,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
@@ -28,35 +29,39 @@ public class SigningPublicKey extends DataStructureImpl {
public final static int KEYSIZE_BYTES = 128;
public SigningPublicKey() { setData(null); }
public SigningPublicKey() {
setData(null);
}
public byte[] getData() { return _data; }
public void setData(byte[] data) { _data = data; }
public byte[] getData() {
return _data;
}
public void setData(byte[] data) {
_data = data;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_data = new byte[KEYSIZE_BYTES];
int read = read(in, _data);
if (read != KEYSIZE_BYTES)
throw new DataFormatException("Not enough bytes to read the public key");
if (read != KEYSIZE_BYTES) throw new DataFormatException("Not enough bytes to read the public key");
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
if (_data == null)
throw new DataFormatException("No data in the public key to write out");
if (_data.length != KEYSIZE_BYTES)
throw new DataFormatException("Invalid size of data in the public key");
if (_data == null) throw new DataFormatException("No data in the public key to write out");
if (_data.length != KEYSIZE_BYTES) throw new DataFormatException("Invalid size of data in the public key");
out.write(_data);
}
public boolean equals(Object obj) {
if ( (obj == null) || !(obj instanceof SigningPublicKey))
return false;
if ((obj == null) || !(obj instanceof SigningPublicKey)) return false;
return DataHelper.eq(_data, ((SigningPublicKey) obj)._data);
}
public int hashCode() {
return DataHelper.hashCode(_data);
}
public String toString() {
StringBuffer buf = new StringBuffer(64);
buf.append("[SigningPublicKey: ");
@@ -65,8 +70,7 @@ public class SigningPublicKey extends DataStructureImpl {
} else {
buf.append("size: ").append(_data.length);
int len = 32;
if (len > _data.length)
len = _data.length;
if (len > _data.length) len = _data.length;
buf.append(" first ").append(len).append(" bytes: ");
buf.append(DataHelper.toString(_data, len));
}

View File

@@ -8,9 +8,9 @@ package net.i2p.data;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;

View File

@@ -1,4 +1,5 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,10 +9,10 @@ package net.i2p.data;
*
*/
import net.i2p.util.Log;
import java.math.BigInteger;
import net.i2p.util.Log;
/**
* Manage an arbitrarily large unsigned integer, using the first bit and first byte
* as the most significant one. Also allows the exporting to byte arrays with whatever
@@ -71,9 +72,7 @@ public class UnsignedInteger {
if (data == null) {
_log.error("Null data to be calculating for", new Exception("Argh"));
return 0;
} else if (data.length == 0) {
return 0;
}
} else if (data.length == 0) { return 0; }
BigInteger bi = new BigInteger(1, data);
return bi.longValue();
}
@@ -106,7 +105,10 @@ public class UnsignedInteger {
* Get the unsigned bytes, most significant bit and bytes first, without any padding
*
*/
public byte[] getBytes() { return _data; }
public byte[] getBytes() {
return _data;
}
/**
* Get the unsigned bytes, most significant bit and bytes first, zero padded to the
* specified number of bytes
@@ -115,22 +117,34 @@ public class UnsignedInteger {
*/
public byte[] getBytes(int numBytes) throws IllegalArgumentException {
if ((_data == null) || (numBytes < _data.length))
throw new IllegalArgumentException("Value (" +_value+") is greater than the requested number of bytes ("+numBytes+")");
throw new IllegalArgumentException("Value (" + _value + ") is greater than the requested number of bytes ("
+ numBytes + ")");
byte[] data = new byte[numBytes];
System.arraycopy(_data, 0, data, numBytes - _data.length, _data.length);
return data;
}
public BigInteger getBigInteger() { return new BigInteger(1, _data); }
public long getLong() { return _value; }
public int getInt() { return (int)_value; }
public short getShort() { return (short)_value; }
public BigInteger getBigInteger() {
return new BigInteger(1, _data);
}
public long getLong() {
return _value;
}
public int getInt() {
return (int) _value;
}
public short getShort() {
return (short) _value;
}
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof UnsignedInteger)) {
return DataHelper.eq(_data, ((UnsignedInteger)obj)._data) &&
DataHelper.eq(_value, ((UnsignedInteger)obj)._value);
return DataHelper.eq(_data, ((UnsignedInteger) obj)._data)
&& DataHelper.eq(_value, ((UnsignedInteger) obj)._value);
} else {
return false;
}
@@ -159,16 +173,21 @@ public class UnsignedInteger {
testNum(1024 * 1024 * 1024 * 4L + 1L);
_log.debug("Testing MaxLong");
testNum(Long.MAX_VALUE);
try { Thread.sleep(1000); } catch (Throwable t) {}
try {
Thread.sleep(1000);
} catch (Throwable t) {
}
}
private static void testNum(long num) {
UnsignedInteger i = new UnsignedInteger(num);
_log.debug(num + " turned into an unsigned integer: " + i + " (" + i.getLong() + "/" + toString(i.getBytes()) + ")");
_log.debug(num + " turned into an unsigned integer: " + i + " (" + i.getLong() + "/" + toString(i.getBytes())
+ ")");
_log.debug(num + " turned into an BigInteger: " + i.getBigInteger());
byte[] val = i.getBytes();
UnsignedInteger val2 = new UnsignedInteger(val);
_log.debug(num + " turned into a byte array and back again: " + val2 + " (" + val2.getLong() + "/" + toString(val2.getBytes()) + ")");
_log.debug(num + " turned into a byte array and back again: " + val2 + " (" + val2.getLong() + "/"
+ toString(val2.getBytes()) + ")");
_log.debug(num + " As an 8 byte array: " + toString(val2.getBytes(8)));
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,15 +9,14 @@ package net.i2p.data.i2cp;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.DataStructureImpl;
import net.i2p.data.DataFormatException;
import net.i2p.util.Log;
/**
* Defines the structure for why abuse was reported either by the client to
@@ -28,10 +28,17 @@ public class AbuseReason extends DataStructureImpl {
private final static Log _log = new Log(AbuseReason.class);
private String _reason;
public AbuseReason() { setReason(null); }
public AbuseReason() {
setReason(null);
}
public String getReason() { return _reason; }
public void setReason(String reason) { _reason = reason; }
public String getReason() {
return _reason;
}
public void setReason(String reason) {
_reason = reason;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_reason = DataHelper.readString(in);
@@ -43,12 +50,13 @@ public class AbuseReason extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof AbuseReason) )
return false;
if ((object == null) || !(object instanceof AbuseReason)) return false;
return DataHelper.eq(getReason(), ((AbuseReason) object).getReason());
}
public int hashCode() { return DataHelper.hashCode(getReason()); }
public int hashCode() {
return DataHelper.hashCode(getReason());
}
public String toString() {
return "[AbuseReason: " + getReason() + "]";

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,15 +9,14 @@ package net.i2p.data.i2cp;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.DataStructureImpl;
import net.i2p.data.DataFormatException;
import net.i2p.util.Log;
/**
* Provides a severity level (larger numbers are more severe) in association with
@@ -29,10 +29,17 @@ public class AbuseSeverity extends DataStructureImpl {
private final static Log _log = new Log(AbuseSeverity.class);
private int _severityId;
public AbuseSeverity() { setSeverity(-1); }
public AbuseSeverity() {
setSeverity(-1);
}
public int getSeverity() { return _severityId; }
public void setSeverity(int id) { _severityId = id; }
public int getSeverity() {
return _severityId;
}
public void setSeverity(int id) {
_severityId = id;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_severityId = (int) DataHelper.readLong(in, 1);
@@ -44,12 +51,13 @@ public class AbuseSeverity extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof AbuseSeverity) )
return false;
if ((object == null) || !(object instanceof AbuseSeverity)) return false;
return DataHelper.eq(getSeverity(), ((AbuseSeverity) object).getSeverity());
}
public int hashCode() { return getSeverity(); }
public int hashCode() {
return getSeverity();
}
public String toString() {
return "[AbuseSeverity: " + getSeverity() + "]";

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -40,14 +41,37 @@ public class CreateLeaseSetMessage extends I2CPMessageImpl {
setPrivateKey(null);
}
public SessionId getSessionId() { return _sessionId; }
public void setSessionId(SessionId id) { _sessionId = id; }
public SigningPrivateKey getSigningPrivateKey() { return _signingPrivateKey; }
public void setSigningPrivateKey(SigningPrivateKey key) { _signingPrivateKey = key; }
public PrivateKey getPrivateKey() { return _privateKey; }
public void setPrivateKey(PrivateKey privateKey) { _privateKey = privateKey; }
public LeaseSet getLeaseSet() { return _leaseSet; }
public void setLeaseSet(LeaseSet leaseSet) { _leaseSet = leaseSet; }
public SessionId getSessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
public SigningPrivateKey getSigningPrivateKey() {
return _signingPrivateKey;
}
public void setSigningPrivateKey(SigningPrivateKey key) {
_signingPrivateKey = key;
}
public PrivateKey getPrivateKey() {
return _privateKey;
}
public void setPrivateKey(PrivateKey privateKey) {
_privateKey = privateKey;
}
public LeaseSet getLeaseSet() {
return _leaseSet;
}
public void setLeaseSet(LeaseSet leaseSet) {
_leaseSet = leaseSet;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
try {
@@ -79,15 +103,17 @@ public class CreateLeaseSetMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof CreateLeaseSetMessage)) {
CreateLeaseSetMessage msg = (CreateLeaseSetMessage) object;
return DataHelper.eq(getSessionId(),msg.getSessionId()) &&
DataHelper.eq(getSigningPrivateKey(),msg.getSigningPrivateKey()) &&
DataHelper.eq(getPrivateKey(), msg.getPrivateKey()) &&
DataHelper.eq(getLeaseSet(),msg.getLeaseSet());
return DataHelper.eq(getSessionId(), msg.getSessionId())
&& DataHelper.eq(getSigningPrivateKey(), msg.getSigningPrivateKey())
&& DataHelper.eq(getPrivateKey(), msg.getPrivateKey())
&& DataHelper.eq(getLeaseSet(), msg.getLeaseSet());
} else {
return false;
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -27,11 +28,21 @@ public class CreateSessionMessage extends I2CPMessageImpl {
public final static int MESSAGE_TYPE = 1;
private SessionConfig _sessionConfig;
public CreateSessionMessage(SessionConfig config) { setSessionConfig(config); }
public CreateSessionMessage() { setSessionConfig(new SessionConfig()); }
public CreateSessionMessage(SessionConfig config) {
setSessionConfig(config);
}
public SessionConfig getSessionConfig() { return _sessionConfig; }
public void setSessionConfig(SessionConfig config) { _sessionConfig = config; }
public CreateSessionMessage() {
setSessionConfig(new SessionConfig());
}
public SessionConfig getSessionConfig() {
return _sessionConfig;
}
public void setSessionConfig(SessionConfig config) {
_sessionConfig = config;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
SessionConfig config = new SessionConfig();
@@ -55,7 +66,9 @@ public class CreateSessionMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof CreateSessionMessage)) {

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -31,8 +32,13 @@ public class DestroySessionMessage extends I2CPMessageImpl {
setSessionId(null);
}
public SessionId getSessionId() { return _sessionId; }
public void setSessionId(SessionId id) { _sessionId = id; }
public SessionId getSessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
SessionId id = new SessionId();
@@ -56,7 +62,9 @@ public class DestroySessionMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof DestroySessionMessage)) {

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -31,8 +32,13 @@ public class DisconnectMessage extends I2CPMessageImpl {
setReason(null);
}
public String getReason() { return _reason; }
public void setReason(String reason) { _reason = reason; }
public String getReason() {
return _reason;
}
public void setReason(String reason) {
_reason = reason;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
try {
@@ -52,7 +58,9 @@ public class DisconnectMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof DisconnectMessage)) {

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -34,7 +35,9 @@ public class GetDateMessage extends I2CPMessageImpl {
return rv;
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof GetDateMessage)) {

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -34,6 +35,7 @@ public interface I2CPMessage extends DataStructure {
* @throws IOException if there is a problem reading from the stream
*/
public void readMessage(InputStream in, int size, int type) throws I2CPMessageException, IOException;
/**
* Read the contents from the input stream into the current class's format.
* The stream should be the message header and body as defined by the I2CP

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -22,6 +23,7 @@ public class I2CPMessageException extends I2PException {
public I2CPMessageException(String message, Throwable parent) {
super(message, parent);
}
public I2CPMessageException(String message) {
super(message);
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,13 +9,12 @@ package net.i2p.data.i2cp;
*
*/
import java.io.InputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import net.i2p.data.DataHelper;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.util.Log;
/**
@@ -48,7 +48,8 @@ public class I2CPMessageHandler {
* Yes, this is fairly ugly, but its the only place it ever happens.
*
*/
private static I2CPMessage createMessage(InputStream in, int length, int type) throws IOException, I2CPMessageException {
private static I2CPMessage createMessage(InputStream in, int length, int type) throws IOException,
I2CPMessageException {
switch (type) {
case CreateLeaseSetMessage.MESSAGE_TYPE:
return new CreateLeaseSetMessage();

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -25,7 +26,9 @@ import net.i2p.util.Log;
*/
public abstract class I2CPMessageImpl extends DataStructureImpl implements I2CPMessage {
private final static Log _log = new Log(I2CPMessageImpl.class);
public I2CPMessageImpl() {}
public I2CPMessageImpl() {
}
/**
* Validate the type and size of the message, and then read the message into the data structures. <p />
@@ -53,7 +56,9 @@ public abstract class I2CPMessageImpl extends DataStructureImpl implements I2CPM
*
*/
public void readMessage(InputStream in, int length, int type) throws I2CPMessageException, IOException {
if (type != getType()) throw new I2CPMessageException("Invalid message type (found: " + type + " supported: " + getType() + " class: " + getClass().getName()+ ")");
if (type != getType())
throw new I2CPMessageException("Invalid message type (found: " + type + " supported: " + getType()
+ " class: " + getClass().getName() + ")");
if (length < 0) throw new IOException("Negative payload size");
byte buf[] = new byte[length];
@@ -72,6 +77,7 @@ public abstract class I2CPMessageImpl extends DataStructureImpl implements I2CPM
*
*/
protected abstract void doReadMessage(InputStream buf, int size) throws I2CPMessageException, IOException;
/**
* Write out the payload part of the message (not including the 4 byte size and
* 1 byte type)
@@ -102,6 +108,7 @@ public abstract class I2CPMessageImpl extends DataStructureImpl implements I2CPM
throw new DataFormatException("Error reading the message", ime);
}
}
public void writeBytes(OutputStream out) throws DataFormatException, IOException {
try {
writeMessage(out);

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -39,29 +40,45 @@ public class I2CPMessageReader {
_readerThread.setName("I2CP Reader");
}
public void setListener(I2CPMessageEventListener lsnr) { _listener = lsnr; }
public I2CPMessageEventListener getListener() { return _listener; }
public void setListener(I2CPMessageEventListener lsnr) {
_listener = lsnr;
}
public I2CPMessageEventListener getListener() {
return _listener;
}
/**
* Instruct the reader to begin reading messages off the stream
*
*/
public void startReading() { _readerThread.start(); }
public void startReading() {
_readerThread.start();
}
/**
* Have the already started reader pause its reading indefinitely
*
*/
public void pauseReading() { _reader.pauseRunner(); }
public void pauseReading() {
_reader.pauseRunner();
}
/**
* Resume reading after a pause
*
*/
public void resumeReading() { _reader.resumeRunner(); }
public void resumeReading() {
_reader.resumeRunner();
}
/**
* Cancel reading.
*
*/
public void stopReading() { _reader.cancelRunner(); }
public void stopReading() {
_reader.cancelRunner();
}
/**
* Defines the different events the reader produces while reading the stream
@@ -74,12 +91,14 @@ public class I2CPMessageReader {
*
*/
public void messageReceived(I2CPMessageReader reader, I2CPMessage message);
/**
* Notify the listener that an exception was thrown while reading from the given
* reader
*
*/
public void readError(I2CPMessageReader reader, Exception error);
/**
* Notify the listener that the stream the given reader was running off
* closed
@@ -91,12 +110,20 @@ public class I2CPMessageReader {
private class I2CPMessageReaderRunner implements Runnable {
private boolean _doRun;
private boolean _stayAlive;
public I2CPMessageReaderRunner() {
_doRun = true;
_stayAlive = true;
}
public void pauseRunner() { _doRun = false; }
public void resumeRunner() { _doRun = true; }
public void pauseRunner() {
_doRun = false;
}
public void resumeRunner() {
_doRun = true;
}
public void cancelRunner() {
_doRun = false;
_stayAlive = false;
@@ -109,6 +136,7 @@ public class I2CPMessageReader {
}
_stream = null;
}
public void run() {
while (_stayAlive) {
while (_doRun) {
@@ -136,7 +164,10 @@ public class I2CPMessageReader {
}
if (!_doRun) {
// pause .5 secs when we're paused
try { Thread.sleep(500); } catch (InterruptedException ie) {}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
// boom bye bye bad bwoy

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,15 +9,14 @@ package net.i2p.data.i2cp;
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.util.Log;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.DataStructureImpl;
import net.i2p.data.DataFormatException;
import net.i2p.util.Log;
/**
* Defines the message ID of a message delivered between a router and a client
@@ -28,10 +28,17 @@ public class MessageId extends DataStructureImpl {
private final static Log _log = new Log(MessageId.class);
private int _messageId;
public MessageId() { setMessageId(-1); }
public MessageId() {
setMessageId(-1);
}
public int getMessageId() { return _messageId; }
public void setMessageId(int id) { _messageId = id; }
public int getMessageId() {
return _messageId;
}
public void setMessageId(int id) {
_messageId = id;
}
public void readBytes(InputStream in) throws DataFormatException, IOException {
_messageId = (int) DataHelper.readLong(in, 4);
@@ -43,12 +50,13 @@ public class MessageId extends DataStructureImpl {
}
public boolean equals(Object object) {
if ( (object == null) || !(object instanceof MessageId) )
return false;
if ((object == null) || !(object instanceof MessageId)) return false;
return DataHelper.eq(getMessageId(), ((MessageId) object).getMessageId());
}
public int hashCode() { return getMessageId(); }
public int hashCode() {
return getMessageId();
}
public String toString() {
return "[MessageId: " + getMessageId() + "]";

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -36,12 +37,29 @@ public class MessagePayloadMessage extends I2CPMessageImpl {
setPayload(null);
}
public SessionId getSessionId() { return _sessionId; }
public void setSessionId(SessionId id) { _sessionId = id; }
public MessageId getMessageId() { return _messageId; }
public void setMessageId(MessageId id) { _messageId = id; }
public Payload getPayload() { return _payload; }
public void setPayload(Payload payload) { _payload = payload; }
public SessionId getSessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
public MessageId getMessageId() {
return _messageId;
}
public void setMessageId(MessageId id) {
_messageId = id;
}
public Payload getPayload() {
return _payload;
}
public void setPayload(Payload payload) {
_payload = payload;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
try {
@@ -75,14 +93,16 @@ public class MessagePayloadMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof MessagePayloadMessage)) {
MessagePayloadMessage msg = (MessagePayloadMessage) object;
return DataHelper.eq(getSessionId(),msg.getSessionId()) &&
DataHelper.eq(getMessageId(),msg.getMessageId()) &&
DataHelper.eq(getPayload(),msg.getPayload());
return DataHelper.eq(getSessionId(), msg.getSessionId())
&& DataHelper.eq(getMessageId(), msg.getMessageId())
&& DataHelper.eq(getPayload(), msg.getPayload());
} else {
return false;
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -46,26 +47,62 @@ public class MessageStatusMessage extends I2CPMessageImpl {
setNonce(-1);
}
public SessionId getSessionId() { return _sessionId; }
public void setSessionId(SessionId id) { _sessionId = id; }
public int getStatus() { return _status; }
public void setStatus(int status) { _status = status; }
public MessageId getMessageId() { return _messageId; }
public void setMessageId(MessageId id) { _messageId = id; }
public long getSize() { return _size; }
public void setSize(long size) { _size = size; }
public long getNonce() { return _nonce; }
public void setNonce(long nonce) { _nonce = nonce; }
public SessionId getSessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
public int getStatus() {
return _status;
}
public void setStatus(int status) {
_status = status;
}
public MessageId getMessageId() {
return _messageId;
}
public void setMessageId(MessageId id) {
_messageId = id;
}
public long getSize() {
return _size;
}
public void setSize(long size) {
_size = size;
}
public long getNonce() {
return _nonce;
}
public void setNonce(long nonce) {
_nonce = nonce;
}
public static final String getStatusString(int status) {
switch (status) {
case STATUS_AVAILABLE: return "AVAILABLE ";
case STATUS_SEND_ACCEPTED: return "SEND ACCEPTED ";
case STATUS_SEND_BEST_EFFORT_SUCCESS: return "BEST EFFORT SUCCESS";
case STATUS_SEND_BEST_EFFORT_FAILURE: return "BEST EFFORT FAILURE";
case STATUS_SEND_GUARANTEED_SUCCESS: return "GUARANTEED SUCCESS ";
case STATUS_SEND_GUARANTEED_FAILURE: return "GUARANTEED FAILURE ";
default: return "***INVALID STATUS: " + status;
case STATUS_AVAILABLE:
return "AVAILABLE ";
case STATUS_SEND_ACCEPTED:
return "SEND ACCEPTED ";
case STATUS_SEND_BEST_EFFORT_SUCCESS:
return "BEST EFFORT SUCCESS";
case STATUS_SEND_BEST_EFFORT_FAILURE:
return "BEST EFFORT FAILURE";
case STATUS_SEND_GUARANTEED_SUCCESS:
return "GUARANTEED SUCCESS ";
case STATUS_SEND_GUARANTEED_FAILURE:
return "GUARANTEED FAILURE ";
default:
return "***INVALID STATUS: " + status;
}
}
@@ -99,16 +136,16 @@ public class MessageStatusMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof MessageStatusMessage)) {
MessageStatusMessage msg = (MessageStatusMessage) object;
return DataHelper.eq(getSessionId(),msg.getSessionId()) &&
DataHelper.eq(getMessageId(),msg.getMessageId()) &&
(getNonce() == msg.getNonce()) &&
DataHelper.eq(getSize(),msg.getSize()) &&
DataHelper.eq(getStatus(),msg.getStatus());
return DataHelper.eq(getSessionId(), msg.getSessionId())
&& DataHelper.eq(getMessageId(), msg.getMessageId()) && (getNonce() == msg.getNonce())
&& DataHelper.eq(getSize(), msg.getSize()) && DataHelper.eq(getStatus(), msg.getStatus());
} else {
return false;
}

View File

@@ -1,4 +1,5 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -33,10 +34,21 @@ public class ReceiveMessageBeginMessage extends I2CPMessageImpl {
setMessageId(null);
}
public SessionId getSessionId() { return _sessionId; }
public void setSessionId(SessionId id) { _sessionId = id; }
public MessageId getMessageId() { return _messageId; }
public void setMessageId(MessageId id) { _messageId = id; }
public SessionId getSessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
public MessageId getMessageId() {
return _messageId;
}
public void setMessageId(MessageId id) {
_messageId = id;
}
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
try {
@@ -62,13 +74,15 @@ public class ReceiveMessageBeginMessage extends I2CPMessageImpl {
return os.toByteArray();
}
public int getType() { return MESSAGE_TYPE; }
public int getType() {
return MESSAGE_TYPE;
}
public boolean equals(Object object) {
if ((object != null) && (object instanceof ReceiveMessageBeginMessage)) {
ReceiveMessageBeginMessage msg = (ReceiveMessageBeginMessage) object;
return DataHelper.eq(getSessionId(),msg.getSessionId()) &&
DataHelper.eq(getMessageId(),msg.getMessageId());
return DataHelper.eq(getSessionId(), msg.getSessionId())
&& DataHelper.eq(getMessageId(), msg.getMessageId());
} else {
return false;
}

Some files were not shown because too many files have changed in this diff Show More