2005-03-23 Comwiz
* Phase 1 of the unit test bounty completed. (The router build script was modified not to build the router tests because of a broken dependancy on the core tests. This should be fixed in phase 3 of the unit test bounty.)
This commit is contained in:
20
build.xml
20
build.xml
@ -89,6 +89,7 @@
|
||||
<pathelement location="apps/jetty/jettylib/org.mortbay.jetty.jar" />
|
||||
<pathelement location="apps/systray/java/lib/systray4j.jar" />
|
||||
<pathelement location="installer/lib/wrapper/win32/wrapper.jar" />
|
||||
<pathelement location="core/lib/junit.jar" />
|
||||
</classpath>
|
||||
</javadoc>
|
||||
</target>
|
||||
@ -300,4 +301,23 @@
|
||||
</jar>
|
||||
<izpack input="${basedir}/installer/install.xml" output="${basedir}/install.jar" installerType="standard" basedir="${basedir}" />
|
||||
</target>
|
||||
<target name="test">
|
||||
<ant dir="core/java/" target="test" />
|
||||
</target>
|
||||
<target name="junit.report">
|
||||
<ant dir="core/java/" target="junit.report" />
|
||||
</target>
|
||||
<target name="clover.report">
|
||||
<ant dir="core/java/" target="clover.report" />
|
||||
</target>
|
||||
<target name="test.report" depends="junit.report, clover.report"/>
|
||||
<target name="useclover">
|
||||
<taskdef resource="clovertasks"/>
|
||||
<mkdir dir="reports/core/clover" />
|
||||
<mkdir dir="reports/core/clover" />
|
||||
<clover-setup initString="reports/core/clover/coverage.db"/>
|
||||
</target>
|
||||
<target name="fulltest">
|
||||
<ant dir="core/java/" target="fulltest" />
|
||||
</target>
|
||||
</project>
|
||||
|
@ -8,7 +8,7 @@
|
||||
<target name="compile">
|
||||
<mkdir dir="./build" />
|
||||
<mkdir dir="./build/obj" />
|
||||
<javac srcdir="./src:./test" debug="true" source="1.3" target="1.3" deprecation="on" destdir="./build/obj" />
|
||||
<javac srcdir="./src:./test" debug="true" source="1.3" target="1.3" deprecation="on" destdir="./build/obj" classpath="lib/junit.jar" />
|
||||
</target>
|
||||
<target name="jar" depends="compile">
|
||||
<jar destfile="./build/i2p.jar" basedir="./build/obj" includes="**/*.class" />
|
||||
@ -18,6 +18,71 @@
|
||||
<mkdir dir="./build/javadoc" />
|
||||
<javadoc sourcepath="./src:./test" destdir="./build/javadoc" packagenames="*" use="true" splitindex="true" windowtitle="I2P SDK" />
|
||||
</target>
|
||||
<target name="test" depends="clean, jar">
|
||||
<junit printsummary="on" fork="yes">
|
||||
<classpath>
|
||||
<pathelement path="${classpath}" />
|
||||
<pathelement location="./build/i2p.jar" />
|
||||
<pathelement location="./lib/junit.jar" />
|
||||
<pathelement path="${ant.home}/lib/clover.jar"/>
|
||||
</classpath>
|
||||
<batchtest>
|
||||
<fileset dir="./test/">
|
||||
<include name="**/*Test.java" />
|
||||
<exclude name="**/ElGamalAESEngineTest.java" />
|
||||
<exclude name="**/StructureTest.java" />
|
||||
</fileset>
|
||||
</batchtest>
|
||||
<formatter type="xml"/>
|
||||
</junit>
|
||||
<mkdir dir="../../reports/" />
|
||||
<mkdir dir="../../reports/core/" />
|
||||
<mkdir dir="../../reports/core/junit/" />
|
||||
<delete>
|
||||
<fileset dir="../../reports/core/junit">
|
||||
<include name="TEST-*.xml"/>
|
||||
</fileset>
|
||||
</delete>
|
||||
<copy todir="../../reports/core/junit">
|
||||
<fileset dir=".">
|
||||
<include name="TEST-*.xml"/>
|
||||
</fileset>
|
||||
</copy>
|
||||
<delete>
|
||||
<fileset dir=".">
|
||||
<include name="TEST-*.xml"/>
|
||||
</fileset>
|
||||
</delete>
|
||||
</target>
|
||||
<target name="junit.report">
|
||||
<junitreport todir="../../reports/core/junit">
|
||||
<fileset dir="../../reports/core/junit">
|
||||
<include name="TEST-*.xml"/>
|
||||
</fileset>
|
||||
<report format="frames" todir="../../reports/core/html/junit"/>
|
||||
</junitreport>
|
||||
</target>
|
||||
<target name="clover.report">
|
||||
<taskdef resource="clovertasks"/>
|
||||
<mkdir dir="../../reports/" />
|
||||
<mkdir dir="../../reports/core" />
|
||||
<mkdir dir="../../reports/core/clover" />
|
||||
<clover-setup initString="../../reports/core/clover/coverage.db"/>
|
||||
<clover-report>
|
||||
<current outfile="../../reports/core/html/clover">
|
||||
<format type="html"/>
|
||||
</current>
|
||||
</clover-report>
|
||||
</target>
|
||||
<target name="test.report" depends="junit.report, clover.report"/>
|
||||
<target name="useclover">
|
||||
<taskdef resource="clovertasks"/>
|
||||
<mkdir dir="../../reports/" />
|
||||
<mkdir dir="../../reports/core/" />
|
||||
<mkdir dir="../../reports/core/clover" />
|
||||
<clover-setup initString="../../reports/core/clover/coverage.db"/>
|
||||
</target>
|
||||
<target name="fulltest" depends="useclover, test, test.report" />
|
||||
<target name="clean">
|
||||
<delete dir="./build" />
|
||||
</target>
|
||||
|
@ -129,7 +129,7 @@ public class RequestLeaseSetMessage extends I2CPMessageImpl {
|
||||
RequestLeaseSetMessage msg = (RequestLeaseSetMessage) object;
|
||||
if (getEndpoints() != msg.getEndpoints()) return false;
|
||||
for (int i = 0; i < getEndpoints(); i++) {
|
||||
if (!DataHelper.eq(getRouter(i), msg.getRouter(i)) || DataHelper.eq(getTunnelId(i), msg.getTunnelId(i)))
|
||||
if (!DataHelper.eq(getRouter(i), msg.getRouter(i)) || !DataHelper.eq(getTunnelId(i), msg.getTunnelId(i)))
|
||||
return false;
|
||||
}
|
||||
return DataHelper.eq(getSessionId(), msg.getSessionId()) && DataHelper.eq(getEndDate(), msg.getEndDate());
|
||||
|
30
core/java/test/net/i2p/AllCoreTests.java
Normal file
30
core/java/test/net/i2p/AllCoreTests.java
Normal file
@ -0,0 +1,30 @@
|
||||
package net.i2p;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class AllCoreTests {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("net.i2p.AllCoreTests");
|
||||
|
||||
suite.addTest(net.i2p.client.I2PClientTestSuite.suite());
|
||||
suite.addTest(net.i2p.crypto.CryptoTestSuite.suite());
|
||||
suite.addTest(net.i2p.data.DataTestSuite.suite());
|
||||
suite.addTest(net.i2p.stat.StatTestSuite.suite());
|
||||
suite.addTest(net.i2p.util.UtilTestSuite.suite());
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
37
core/java/test/net/i2p/client/I2PClientTest.java
Normal file
37
core/java/test/net/i2p/client/I2PClientTest.java
Normal file
@ -0,0 +1,37 @@
|
||||
package net.i2p.client;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import net.i2p.client.I2PClientFactory;
|
||||
import net.i2p.client.I2PClient;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Comwiz
|
||||
*
|
||||
*/
|
||||
public class I2PClientTest extends TestCase {
|
||||
private I2PClient _client;
|
||||
|
||||
public void setUp(){
|
||||
_client = I2PClientFactory.createClient();
|
||||
}
|
||||
|
||||
public void testI2PClient() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
_client.createDestination(out);
|
||||
_client.createSession(new ByteArrayInputStream(out.toByteArray()), null);
|
||||
}
|
||||
}
|
30
core/java/test/net/i2p/client/I2PClientTestSuite.java
Normal file
30
core/java/test/net/i2p/client/I2PClientTestSuite.java
Normal file
@ -0,0 +1,30 @@
|
||||
package net.i2p.client;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.client.datagram.DatagramTest;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class I2PClientTestSuite {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("net.i2p.client.I2PClientTestSuite");
|
||||
|
||||
suite.addTestSuite(I2PClientTest.class);
|
||||
suite.addTestSuite(I2PSessionTest.class);
|
||||
suite.addTestSuite(DatagramTest.class);
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
98
core/java/test/net/i2p/client/I2PSessionTest.java
Normal file
98
core/java/test/net/i2p/client/I2PSessionTest.java
Normal file
@ -0,0 +1,98 @@
|
||||
package net.i2p.client;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import net.i2p.client.I2PSession;
|
||||
import net.i2p.client.I2PSessionImpl;
|
||||
import net.i2p.client.I2PSessionImpl2;
|
||||
import net.i2p.client.I2PSessionException;
|
||||
import net.i2p.client.I2PClient;
|
||||
import net.i2p.client.I2PClientFactory;
|
||||
import net.i2p.client.I2PSessionListener;
|
||||
import net.i2p.data.Destination;
|
||||
import net.i2p.I2PAppContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Comwiz
|
||||
*
|
||||
*/
|
||||
public class I2PSessionTest extends TestCase implements I2PSessionListener{
|
||||
private Set _s;
|
||||
|
||||
|
||||
public void setUp(){
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
System.gc();
|
||||
}
|
||||
|
||||
public void testSendClosedMessage() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
Destination d = I2PClientFactory.createClient().createDestination(out);
|
||||
I2PSession session = new I2PSessionImpl2(I2PAppContext.getGlobalContext(), new ByteArrayInputStream(out.toByteArray()), null);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
session.sendMessage(d, out.toByteArray());
|
||||
}catch(I2PSessionException i2pse){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testSendAndRecieve() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
Destination d = I2PClientFactory.createClient().createDestination(out);
|
||||
I2PSession session = new I2PSessionImpl2(I2PAppContext.getGlobalContext(), new ByteArrayInputStream(out.toByteArray()), null);
|
||||
session.connect();
|
||||
|
||||
session.setSessionListener(this);
|
||||
|
||||
_s = new HashSet();
|
||||
_s.add("a");
|
||||
_s.add("b");
|
||||
_s.add("c");
|
||||
_s.add("d");
|
||||
|
||||
session.sendMessage(d, "a".getBytes());
|
||||
session.sendMessage(d, "b".getBytes());
|
||||
session.sendMessage(d, "c".getBytes());
|
||||
session.sendMessage(d, "d".getBytes());
|
||||
|
||||
for(int i = 0; (i < 20)&&(!_s.isEmpty()); i++){
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
assertTrue(_s.isEmpty());
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void disconnected(I2PSession session){}
|
||||
public void errorOccurred(I2PSession session, java.lang.String message, java.lang.Throwable error){}
|
||||
public void messageAvailable(I2PSession session, int msgId, long size){
|
||||
try{
|
||||
String x = new String(session.receiveMessage(msgId));
|
||||
if(_s.contains(x))
|
||||
_s.remove(x);
|
||||
}catch(Exception e){
|
||||
fail();
|
||||
}
|
||||
}
|
||||
public void reportAbuse(I2PSession session, int severity){}
|
||||
}
|
118
core/java/test/net/i2p/client/datagram/DatagramTest.java
Normal file
118
core/java/test/net/i2p/client/datagram/DatagramTest.java
Normal file
@ -0,0 +1,118 @@
|
||||
package net.i2p.client.datagram;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import net.i2p.client.datagram.I2PDatagramMaker;
|
||||
import net.i2p.client.datagram.I2PDatagramDissector;
|
||||
import net.i2p.client.datagram.I2PInvalidDatagramException;
|
||||
import net.i2p.client.I2PClientFactory;
|
||||
import net.i2p.client.I2PClient;
|
||||
import net.i2p.client.I2PSession;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.Hash;
|
||||
import net.i2p.data.Destination;
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.crypto.DSAEngine;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Comwiz
|
||||
*
|
||||
*/
|
||||
public class DatagramTest extends TestCase {
|
||||
private I2PClient _client;
|
||||
|
||||
public void setUp(){
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
System.gc();
|
||||
}
|
||||
|
||||
public void testDatagram() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
I2PClient client = I2PClientFactory.createClient();
|
||||
Destination d = client.createDestination(out);
|
||||
I2PSession session = client.createSession(new ByteArrayInputStream(out.toByteArray()), null);
|
||||
|
||||
I2PDatagramMaker dm = new I2PDatagramMaker(session);
|
||||
byte[] dg = dm.makeI2PDatagram("What's the deal with 42?".getBytes());
|
||||
|
||||
I2PDatagramDissector dd = new I2PDatagramDissector();
|
||||
dd.loadI2PDatagram(dg);
|
||||
byte[] x = dd.getPayload();
|
||||
assertTrue(DataHelper.eq(x, "What's the deal with 42?".getBytes()));
|
||||
|
||||
x = dd.extractPayload();
|
||||
assertTrue(DataHelper.eq(x, "What's the deal with 42?".getBytes()));
|
||||
|
||||
assertEquals(d, dd.getSender());
|
||||
assertEquals(d, dd.extractSender());
|
||||
|
||||
}
|
||||
|
||||
/*public void testMakeNullDatagram() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
I2PClient client = I2PClientFactory.createClient();
|
||||
Destination d = client.createDestination(out);
|
||||
I2PSession session = client.createSession(new ByteArrayInputStream(out.toByteArray()), null);
|
||||
I2PDatagramMaker dm = new I2PDatagramMaker(session);
|
||||
|
||||
byte[] dg = dm.makeI2PDatagram(null);
|
||||
assertNull(dg);
|
||||
}*/
|
||||
|
||||
/*public void testExtractNullDatagram() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
I2PClient client = I2PClientFactory.createClient();
|
||||
Destination d = client.createDestination(out);
|
||||
I2PSession session = client.createSession(new ByteArrayInputStream(out.toByteArray()), null);
|
||||
|
||||
I2PDatagramDissector dd = new I2PDatagramDissector();
|
||||
dd.loadI2PDatagram(null);
|
||||
}*/
|
||||
|
||||
public void testBadagram() throws Exception{
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
I2PClient client = I2PClientFactory.createClient();
|
||||
Destination d = client.createDestination(out);
|
||||
I2PSession session = client.createSession(new ByteArrayInputStream(out.toByteArray()), null);
|
||||
DSAEngine dsaEng = DSAEngine.getInstance();
|
||||
|
||||
ByteArrayOutputStream dout = new ByteArrayOutputStream();
|
||||
d.writeBytes(dout);
|
||||
dsaEng.sign(Hash.FAKE_HASH.toByteArray(), session.getPrivateKey()).writeBytes(dout);
|
||||
dout.write("blah".getBytes());
|
||||
|
||||
byte[] data = dout.toByteArray();
|
||||
I2PDatagramDissector dd = new I2PDatagramDissector();
|
||||
dd.loadI2PDatagram(data);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
dd.getPayload();
|
||||
}catch(I2PInvalidDatagramException i2pide){
|
||||
error = true;
|
||||
}
|
||||
|
||||
error = false;
|
||||
try{
|
||||
dd.getSender();
|
||||
}catch(I2PInvalidDatagramException i2pide){
|
||||
error = true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
77
core/java/test/net/i2p/crypto/AES256Test.java
Normal file
77
core/java/test/net/i2p/crypto/AES256Test.java
Normal file
@ -0,0 +1,77 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.util.RandomSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class AES256Test extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
private byte[] iv;
|
||||
|
||||
protected void setUp() {
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
public void testMultiple(){
|
||||
for(int i = 0; i < 100; i++){
|
||||
|
||||
SessionKey key = _context.keyGenerator().generateSessionKey();
|
||||
|
||||
byte[] iv = new byte[16];
|
||||
_context.random().nextBytes(iv);
|
||||
|
||||
byte[] plain = new byte[256];
|
||||
_context.random().nextBytes(plain);
|
||||
|
||||
byte[] e = new byte[plain.length];
|
||||
_context.aes().encrypt(plain, 0, e, 0, key, iv, plain.length);
|
||||
byte[] d = new byte[e.length];
|
||||
_context.aes().decrypt(e, 0, d, 0, key, iv, d.length);
|
||||
boolean same = true;
|
||||
assertTrue(DataHelper.eq(plain, d));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLong(){
|
||||
I2PAppContext ctx = new I2PAppContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
RandomSource.getInstance().nextBytes(iv);
|
||||
|
||||
|
||||
byte lbuf[] = new byte[1024];
|
||||
RandomSource.getInstance().nextBytes(lbuf);
|
||||
byte le[] = ctx.aes().safeEncrypt(lbuf, key, iv, 2048);
|
||||
byte ld[] = ctx.aes().safeDecrypt(le, key, iv);
|
||||
assertTrue(DataHelper.eq(ld, lbuf));
|
||||
}
|
||||
|
||||
public void testShort(){
|
||||
I2PAppContext ctx = new I2PAppContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
RandomSource.getInstance().nextBytes(iv);
|
||||
|
||||
byte sbuf[] = new byte[16];
|
||||
RandomSource.getInstance().nextBytes(sbuf);
|
||||
byte se[] = new byte[16];
|
||||
ctx.aes().encrypt(sbuf, 0, se, 0, key, iv, sbuf.length);
|
||||
byte sd[] = new byte[16];
|
||||
ctx.aes().decrypt(se, 0, sd, 0, key, iv, se.length);
|
||||
assertTrue(DataHelper.eq(sd, sbuf));
|
||||
}
|
||||
}
|
111
core/java/test/net/i2p/crypto/AESInputStreamTest.java
Normal file
111
core/java/test/net/i2p/crypto/AESInputStreamTest.java
Normal file
@ -0,0 +1,111 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.Base64;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.Hash;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.util.Clock;
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.util.RandomSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class AESInputStreamTest extends TestCase {
|
||||
public void testMultiple() throws Exception{
|
||||
SessionKey key = KeyGenerator.getInstance().generateSessionKey();
|
||||
byte iv[] = "there once was a".getBytes();
|
||||
|
||||
int[] sizes = {1024 * 32, 20, 3, 0};
|
||||
|
||||
for(int j = 0; j < sizes.length; j++){
|
||||
byte orig[] = new byte[sizes[j]];
|
||||
for (int i = 0; i < 20; i++) {
|
||||
RandomSource.getInstance().nextBytes(orig);
|
||||
runTest(orig, key, iv);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void runTest(byte orig[], SessionKey key, byte[] iv) throws Exception{
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
|
||||
ByteArrayOutputStream origStream = new ByteArrayOutputStream(512);
|
||||
AESOutputStream out = new AESOutputStream(ctx, origStream, key, iv);
|
||||
out.write(orig);
|
||||
out.close();
|
||||
|
||||
byte encrypted[] = origStream.toByteArray();
|
||||
|
||||
ByteArrayInputStream encryptedStream = new ByteArrayInputStream(encrypted);
|
||||
AESInputStream sin = new AESInputStream(ctx, encryptedStream, key, iv);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
|
||||
byte buf[] = new byte[1024 * 32];
|
||||
int read = DataHelper.read(sin, buf);
|
||||
if (read > 0) baos.write(buf, 0, read);
|
||||
sin.close();
|
||||
byte fin[] = baos.toByteArray();
|
||||
|
||||
Hash origHash = SHA256Generator.getInstance().calculateHash(orig);
|
||||
Hash newHash = SHA256Generator.getInstance().calculateHash(fin);
|
||||
|
||||
assertEquals(origHash, newHash);
|
||||
assertTrue(DataHelper.eq(orig, fin));
|
||||
}
|
||||
|
||||
public static void testOffset() throws Exception{
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
|
||||
byte[] orig = new byte[32];
|
||||
RandomSource.getInstance().nextBytes(orig);
|
||||
|
||||
SessionKey key = KeyGenerator.getInstance().generateSessionKey();
|
||||
byte iv[] = "there once was a".getBytes();
|
||||
|
||||
ByteArrayOutputStream origStream = new ByteArrayOutputStream(512);
|
||||
AESOutputStream out = new AESOutputStream(ctx, origStream, key, iv);
|
||||
out.write(orig);
|
||||
out.close();
|
||||
|
||||
byte encrypted[] = origStream.toByteArray();
|
||||
|
||||
byte encryptedSegment[] = new byte[40];
|
||||
System.arraycopy(encrypted, 0, encryptedSegment, 0, 40);
|
||||
|
||||
ByteArrayInputStream encryptedStream = new ByteArrayInputStream(encryptedSegment);
|
||||
AESInputStream sin = new AESInputStream(ctx, encryptedStream, key, iv);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
|
||||
byte buf[] = new byte[1024 * 32];
|
||||
int read = DataHelper.read(sin, buf);
|
||||
int remaining = sin.remainingBytes();
|
||||
int readyBytes = sin.readyBytes();
|
||||
|
||||
if (read > 0)
|
||||
baos.write(buf, 0, read);
|
||||
sin.close();
|
||||
byte fin[] = baos.toByteArray();
|
||||
|
||||
Hash origHash = SHA256Generator.getInstance().calculateHash(orig);
|
||||
Hash newHash = SHA256Generator.getInstance().calculateHash(fin);
|
||||
|
||||
assertFalse(origHash.equals(newHash));
|
||||
assertFalse(DataHelper.eq(orig, fin));
|
||||
}
|
||||
}
|
118
core/java/test/net/i2p/crypto/CryptixAESEngineTest.java
Normal file
118
core/java/test/net/i2p/crypto/CryptixAESEngineTest.java
Normal file
@ -0,0 +1,118 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.ByteArray;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.util.ByteCache;
|
||||
import net.i2p.crypto.CryptixAESEngine;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class CryptixAESEngineTest extends TestCase{
|
||||
public void testED() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[128];
|
||||
byte encrypted[] = new byte[128];
|
||||
byte decrypted[] = new byte[128];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encrypt(orig, 0, encrypted, 0, key, iv, orig.length);
|
||||
aes.decrypt(encrypted, 0, decrypted, 0, key, iv, encrypted.length);
|
||||
assertTrue(DataHelper.eq(decrypted,orig));
|
||||
}
|
||||
|
||||
public static void testED2() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[128];
|
||||
byte data[] = new byte[128];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encrypt(orig, 0, data, 0, key, iv, data.length);
|
||||
aes.decrypt(data, 0, data, 0, key, iv, data.length);
|
||||
assertTrue(DataHelper.eq(data,orig));
|
||||
}
|
||||
|
||||
public static void testFake() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
SessionKey wrongKey = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[128];
|
||||
byte encrypted[] = new byte[128];
|
||||
byte decrypted[] = new byte[128];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encrypt(orig, 0, encrypted, 0, key, iv, orig.length);
|
||||
aes.decrypt(encrypted, 0, decrypted, 0, wrongKey, iv, encrypted.length);
|
||||
assertFalse(DataHelper.eq(decrypted,orig));
|
||||
}
|
||||
|
||||
public static void testNull() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
SessionKey wrongKey = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[128];
|
||||
byte encrypted[] = new byte[128];
|
||||
byte decrypted[] = new byte[128];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encrypt(orig, 0, encrypted, 0, key, iv, orig.length);
|
||||
|
||||
boolean error = false;
|
||||
try {
|
||||
aes.decrypt(null, 0, null, 0, wrongKey, iv, encrypted.length);
|
||||
} catch (IllegalArgumentException iae) {
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public static void testEDBlock() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[16];
|
||||
byte encrypted[] = new byte[16];
|
||||
byte decrypted[] = new byte[16];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encryptBlock(orig, 0, key, encrypted, 0);
|
||||
aes.decryptBlock(encrypted, 0, key, decrypted, 0);
|
||||
assertTrue(DataHelper.eq(decrypted,orig));
|
||||
}
|
||||
|
||||
public static void testEDBlock2() {
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
SessionKey key = ctx.keyGenerator().generateSessionKey();
|
||||
byte iv[] = new byte[16];
|
||||
byte orig[] = new byte[16];
|
||||
byte data[] = new byte[16];
|
||||
ctx.random().nextBytes(iv);
|
||||
ctx.random().nextBytes(orig);
|
||||
CryptixAESEngine aes = new CryptixAESEngine(ctx);
|
||||
aes.encryptBlock(orig, 0, key, data, 0);
|
||||
aes.decryptBlock(data, 0, key, data, 0);
|
||||
assertTrue(DataHelper.eq(data,orig));
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package net.i2p.crypto;
|
||||
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class CryptixRijndael_AlgorithmTest extends TestCase {
|
||||
public void testCRA() throws Exception{
|
||||
int[] sizes = {16,24,32};
|
||||
for(int j = 0; j < sizes.length; j++){
|
||||
|
||||
byte[] kb = new byte[sizes[j]];
|
||||
byte[] pt = new byte[16];
|
||||
int i;
|
||||
|
||||
for (i = 0; i < sizes[j]; i++)
|
||||
kb[i] = (byte) i;
|
||||
for (i = 0; i < 16; i++)
|
||||
pt[i] = (byte) i;
|
||||
|
||||
|
||||
Object key = CryptixRijndael_Algorithm.makeKey(kb, 16);
|
||||
|
||||
byte[] ct = new byte[16];
|
||||
CryptixRijndael_Algorithm.blockEncrypt(pt, ct, 0, 0, key, 16);
|
||||
|
||||
byte[] cpt = new byte[16];
|
||||
CryptixRijndael_Algorithm.blockDecrypt(ct, cpt, 0, 0, key, 16);
|
||||
|
||||
assertTrue(DataHelper.eq(pt, cpt));
|
||||
}
|
||||
}
|
||||
}
|
38
core/java/test/net/i2p/crypto/CryptoTestSuite.java
Normal file
38
core/java/test/net/i2p/crypto/CryptoTestSuite.java
Normal file
@ -0,0 +1,38 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* @author comwiz
|
||||
*/
|
||||
public class CryptoTestSuite {
|
||||
|
||||
public static Test suite() {
|
||||
|
||||
TestSuite suite = new TestSuite("net.i2p.crypto.CryptoTestSuite");
|
||||
|
||||
suite.addTestSuite(AES256Test.class);
|
||||
suite.addTestSuite(AESInputStreamTest.class);
|
||||
suite.addTestSuite(CryptixAESEngineTest.class);
|
||||
suite.addTestSuite(CryptixRijndael_AlgorithmTest.class);
|
||||
suite.addTestSuite(DHSessionKeyBuilderTest.class);
|
||||
suite.addTestSuite(DSATest.class);
|
||||
suite.addTestSuite(ElGamalTest.class);
|
||||
suite.addTestSuite(HMACSHA256Test.class);
|
||||
suite.addTestSuite(KeyGeneratorTest.class);
|
||||
suite.addTestSuite(SessionEncryptionTest.class);
|
||||
suite.addTestSuite(SHA1HashTest.class);
|
||||
suite.addTestSuite(SHA256Test.class);
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
47
core/java/test/net/i2p/crypto/DHSessionKeyBuilderTest.java
Normal file
47
core/java/test/net/i2p/crypto/DHSessionKeyBuilderTest.java
Normal file
@ -0,0 +1,47 @@
|
||||
package net.i2p.crypto;
|
||||
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.util.RandomSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class DHSessionKeyBuilderTest extends TestCase {
|
||||
public void testDHSessionKeyBuilder(){
|
||||
I2PAppContext ctx = new I2PAppContext();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
DHSessionKeyBuilder builder1 = new DHSessionKeyBuilder();
|
||||
DHSessionKeyBuilder builder2 = new DHSessionKeyBuilder();
|
||||
BigInteger pub1 = builder1.getMyPublicValue();
|
||||
builder2.setPeerPublicValue(pub1);
|
||||
BigInteger pub2 = builder2.getMyPublicValue();
|
||||
builder1.setPeerPublicValue(pub2);
|
||||
SessionKey key1 = builder1.getSessionKey();
|
||||
SessionKey key2 = builder2.getSessionKey();
|
||||
|
||||
assertEquals(key1, key2);
|
||||
|
||||
byte iv[] = new byte[16];
|
||||
RandomSource.getInstance().nextBytes(iv);
|
||||
String origVal = "1234567890123456"; // 16 bytes max using AESEngine
|
||||
byte enc[] = new byte[16];
|
||||
byte dec[] = new byte[16];
|
||||
ctx.aes().encrypt(origVal.getBytes(), 0, enc, 0, key1, iv, 16);
|
||||
ctx.aes().decrypt(enc, 0, dec, 0, key2, iv, 16);
|
||||
String tranVal = new String(dec);
|
||||
assertEquals(origVal, tranVal);
|
||||
}
|
||||
}
|
||||
}
|
44
core/java/test/net/i2p/crypto/DSATest.java
Normal file
44
core/java/test/net/i2p/crypto/DSATest.java
Normal file
@ -0,0 +1,44 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import net.i2p.data.Signature;
|
||||
import net.i2p.data.SigningPrivateKey;
|
||||
import net.i2p.data.SigningPublicKey;
|
||||
import net.i2p.I2PAppContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class DSATest extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
|
||||
protected void setUp() {
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
public void testMultiple(){
|
||||
for(int i = 0; i < 100; i++){
|
||||
byte[] message = new byte[256];
|
||||
_context.random().nextBytes(message);
|
||||
|
||||
Object[] keys = KeyGenerator.getInstance().generateSigningKeypair();
|
||||
SigningPublicKey pubkey = (SigningPublicKey)keys[0];
|
||||
SigningPrivateKey privkey = (SigningPrivateKey)keys[1];
|
||||
|
||||
Signature s = DSAEngine.getInstance().sign(message, privkey);
|
||||
Signature s1 = DSAEngine.getInstance().sign(new ByteArrayInputStream(message), privkey);
|
||||
|
||||
assertTrue(DSAEngine.getInstance().verifySignature(s, message, pubkey));
|
||||
assertTrue(DSAEngine.getInstance().verifySignature(s1, new ByteArrayInputStream(message), pubkey));
|
||||
assertTrue(DSAEngine.getInstance().verifySignature(s1, message, pubkey));
|
||||
assertTrue(DSAEngine.getInstance().verifySignature(s, new ByteArrayInputStream(message), pubkey));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,243 +0,0 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.Hash;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.data.PublicKey;
|
||||
import net.i2p.data.PrivateKey;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.RandomSource;
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.util.Clock;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.HashSet;
|
||||
|
||||
class ElGamalAESEngineTest {
|
||||
private final static Log _log = new Log(ElGamalAESEngineTest.class);
|
||||
private I2PAppContext _context;
|
||||
public ElGamalAESEngineTest(I2PAppContext ctx) {
|
||||
_context = ctx;
|
||||
}
|
||||
public void runRoundtripTest() {
|
||||
try {
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
|
||||
String msg = "Hello world";
|
||||
Set toBeDelivered = new HashSet();
|
||||
SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
if (key == null)
|
||||
key = _context.sessionKeyManager().createSession(pubKey);
|
||||
byte[] encrypted = _context.elGamalAESEngine().encrypt(msg.getBytes(), pubKey, key, 64);
|
||||
byte[] decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey);
|
||||
if (decrypted == null)
|
||||
throw new Exception("Failed to decrypt");
|
||||
String read = new String(decrypted);
|
||||
_log.debug("read: " + read);
|
||||
_log.debug("Match? " + msg.equals(read));
|
||||
} catch (Exception e) {
|
||||
_log.error("Error", e);
|
||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void runLoopTest(int runs) {
|
||||
try {
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
|
||||
long e0 = 0;
|
||||
long d0 = 0;
|
||||
long eTot = 0;
|
||||
long dTot = 0;
|
||||
for (int i = 0; i < runs; i++) {
|
||||
long times[] = runMessage(pubKey, privKey);
|
||||
_log.debug("E[" + i + "] time: " + times[0] + "ms");
|
||||
_log.debug("D["+i+"] time: " + times[1] + "ms");
|
||||
if (i == 0) {
|
||||
e0 = times[0];
|
||||
d0 = times[1];
|
||||
}
|
||||
eTot += times[0];
|
||||
dTot += times[1];
|
||||
}
|
||||
_log.debug("E average time: " + eTot/runs + "ms");
|
||||
_log.debug("D average time: " + dTot/runs + "ms");
|
||||
_log.debug("Total time to send and receive " + (runs) + "Kb: " + (eTot+dTot)+"ms");
|
||||
|
||||
} catch (Exception e) {
|
||||
_log.error("Error", e);
|
||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
private long[] runMessage(PublicKey pubKey, PrivateKey privKey) throws Exception {
|
||||
byte[] msg = new byte[400];
|
||||
RandomSource.getInstance().nextBytes(msg);
|
||||
SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
if (key == null)
|
||||
key = _context.sessionKeyManager().createSession(pubKey);
|
||||
|
||||
long beforeE = Clock.getInstance().now();
|
||||
byte[] encrypted = _context.elGamalAESEngine().encrypt(msg, pubKey, key, 1024);
|
||||
long afterE = Clock.getInstance().now();
|
||||
byte[] decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey);
|
||||
long afterD = Clock.getInstance().now();
|
||||
if (!DataHelper.eq(msg, decrypted)) {
|
||||
_log.error("WTF, D(E(val)) != val");
|
||||
return null;
|
||||
}
|
||||
|
||||
long rv[] = new long[2];
|
||||
rv[0] = afterE - beforeE;
|
||||
rv[1] = afterD - afterE;
|
||||
return rv;
|
||||
}
|
||||
|
||||
public void runAESTest() {
|
||||
try {
|
||||
SessionKey sessionKey = KeyGenerator.getInstance().generateSessionKey();
|
||||
Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
|
||||
byte iv[] = new byte[16];
|
||||
System.arraycopy(h.getData(), 0, iv, 0, 16);
|
||||
|
||||
String msg = "Hello world";
|
||||
|
||||
byte encrypted[] = _context.elGamalAESEngine().encryptAESBlock(msg.getBytes(), sessionKey, iv, null, null, 64);
|
||||
_log.debug("** Encryption complete. Beginning decryption");
|
||||
Set foundTags = new HashSet();
|
||||
SessionKey foundKey = new SessionKey();
|
||||
byte decrypted[] = _context.elGamalAESEngine().decryptAESBlock(encrypted, 0, encrypted.length, sessionKey, iv, null, foundTags, foundKey);
|
||||
if (decrypted == null) throw new Exception("Decryption failed");
|
||||
String read = new String(decrypted);
|
||||
_log.debug("read: " + read);
|
||||
_log.debug("Match? " + msg.equals(read));
|
||||
} catch (Exception e) {
|
||||
_log.error("Error", e);
|
||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void runBasicAESTest() {
|
||||
try {
|
||||
SessionKey sessionKey = KeyGenerator.getInstance().generateSessionKey();
|
||||
Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
|
||||
byte iv[] = new byte[16];
|
||||
System.arraycopy(h.getData(), 0, iv, 0, 16);
|
||||
|
||||
String msg = "Hello world01234012345678901234501234567890123450123456789012345";
|
||||
h = SHA256Generator.getInstance().calculateHash(msg.getBytes());
|
||||
_log.debug("Hash of entire aes block before encryption: \n" + DataHelper.toString(h.getData(), 32));
|
||||
byte aesEncr[] = new byte[msg.getBytes().length];
|
||||
byte aesDecr[] = new byte[aesEncr.length];
|
||||
_context.aes().encrypt(msg.getBytes(), 0, aesEncr, 0, sessionKey, iv, aesEncr.length);
|
||||
_context.aes().decrypt(aesEncr, 0, aesDecr, 0, sessionKey, iv, aesEncr.length);
|
||||
h = SHA256Generator.getInstance().calculateHash(aesDecr);
|
||||
_log.debug("Hash of entire aes block after decryption: \n" + DataHelper.toString(h.getData(), 32));
|
||||
if (msg.equals(new String(aesDecr))) {
|
||||
_log.debug("**AES Basic test passed!\n\n");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
_log.error("Error", e);
|
||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void runElGamalTest(int numLoops) {
|
||||
|
||||
for (int i = 0; i < numLoops; i++) {
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
SessionKey key = KeyGenerator.getInstance().generateSessionKey();
|
||||
|
||||
runBasicElGamalTest(key, pubKey, privKey);
|
||||
}
|
||||
}
|
||||
|
||||
public void runBasicElGamalTest(SessionKey key, PublicKey pubKey, PrivateKey privKey) {
|
||||
try {
|
||||
ByteArrayOutputStream elgSrc = new ByteArrayOutputStream(256);
|
||||
key.writeBytes(elgSrc);
|
||||
byte preIV[] = new byte[32];
|
||||
RandomSource.getInstance().nextBytes(preIV);
|
||||
elgSrc.write(preIV);
|
||||
// byte rnd[] = new byte[191];
|
||||
// RandomSource.getInstance().nextBytes(rnd);
|
||||
// elgSrc.write(rnd);
|
||||
elgSrc.flush();
|
||||
|
||||
byte elgEncr[] = _context.elGamalEngine().encrypt(elgSrc.toByteArray(), pubKey);
|
||||
byte elgDecr[] = _context.elGamalEngine().decrypt(elgEncr, privKey);
|
||||
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(elgDecr);
|
||||
SessionKey nk = new SessionKey();
|
||||
|
||||
nk.readBytes(bais);
|
||||
byte postpreIV[] = new byte[32];
|
||||
int read = bais.read(postpreIV);
|
||||
if (read != postpreIV.length) {
|
||||
// hmm, this can't really happen...
|
||||
throw new Exception("Somehow ElGamal broke and 256 bytes is less than 32 bytes...");
|
||||
}
|
||||
// ignore the next 192 bytes
|
||||
boolean eq = (DataHelper.eq(preIV, postpreIV) && DataHelper.eq(key, nk));
|
||||
if (!eq) {
|
||||
_log.error("elgEncr.length: " + elgEncr.length + " elgDecr.length: " + elgDecr.length);
|
||||
_log.error("Pre IV.................: " + DataHelper.toString(preIV, 32));
|
||||
_log.error("Pre IV after decryption: " + DataHelper.toString(postpreIV, 32));
|
||||
_log.error("SessionKey.................: " + DataHelper.toString(key.getData(), 32));
|
||||
_log.error("SessionKey after decryption: " + DataHelper.toString(nk.getData(), 32));
|
||||
_log.error("PublicKey: " + DataHelper.toDecimalString(pubKey.getData(), pubKey.getData().length));
|
||||
_log.error("PrivateKey: " + DataHelper.toDecimalString(privKey.getData(), privKey.getData().length));
|
||||
|
||||
throw new Exception("Not equal!");
|
||||
} else {
|
||||
_log.debug("Basic ElG D(E(val)) == val");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
_log.error("Error", e);
|
||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
I2PAppContext context = new I2PAppContext();
|
||||
ElGamalAESEngineTest tst = new ElGamalAESEngineTest(context);
|
||||
Object o = YKGenerator.class;
|
||||
try { Thread.sleep(120*1000); } catch (InterruptedException ie) {}
|
||||
|
||||
tst.runBasicAESTest();
|
||||
tst.runAESTest();
|
||||
tst.runRoundtripTest();
|
||||
tst.runElGamalTest(2);
|
||||
// test bug
|
||||
for (int i = 0; i < 3; i++)
|
||||
tst.runLoopTest(1);
|
||||
// test throughput
|
||||
tst.runLoopTest(5);
|
||||
|
||||
net.i2p.stat.SimpleStatDumper.dumpStats(context, Log.CRIT);
|
||||
try { Thread.sleep(5*1000); } catch (InterruptedException ie) {}
|
||||
}
|
||||
}
|
||||
|
383
core/java/test/net/i2p/crypto/ElGamalTest.java
Normal file
383
core/java/test/net/i2p/crypto/ElGamalTest.java
Normal file
@ -0,0 +1,383 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.Hash;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.data.Base64;
|
||||
import net.i2p.data.PublicKey;
|
||||
import net.i2p.data.PrivateKey;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.SessionTag;
|
||||
import net.i2p.util.RandomSource;
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.util.Clock;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.HashSet;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class ElGamalTest extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
|
||||
// Following 4 String arrays for use with the testVerify* methods
|
||||
|
||||
private static final String UNENCRYPTED[] = new String[] {
|
||||
"",
|
||||
"hello world",
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"123456789012",
|
||||
"\0x00",
|
||||
"\0x00\0x00\0x00",
|
||||
"\0x00\0x01\0x02\0x00",
|
||||
};
|
||||
private static final String PUBLIC_KEY = new String(
|
||||
"pOvBUMrSUUeN5awynzbPbCAwe3MqWprhSpp3OR7pvdfm9PhWaNbPoKRLeEmDoUwyNDoHE0" +
|
||||
"E6mcZSG8qPQ8XUZFlczpilOl0MJBvsI9u9SMyi~bEqzSgzh9FNfS-NcGji3q2wI~Ux~q5B" +
|
||||
"KOjGlyMLgd1nxl5R5wIYL4uHKZNaYuArsRYmtV~MgMQPGvDtIbdGTV6aL6UbOYryzQSUMY" +
|
||||
"OuO3S~YoBjA6Nmi0SeJM3tyTxlI6U1EYjR6oQcI4SOFUW4L~8pfYWijcncCODAqpXVN6ZI" +
|
||||
"AJ3a6vjxGu56IDp4xCcKlOEHgdXvqmEC67dR5qf2btH6dtWoB3-Z6QPsS6tPTQ=="
|
||||
);
|
||||
private static final String PRIVATE_KEY = new String(
|
||||
"gMlIhURVXU8uPube20Xr8E1K11g-3qZxOj1riThHqt-rBx72MPq5ivT1rr28cE9mzOmsXi" +
|
||||
"bbsuBuQKYDvF7hGICRB3ROSPePYhcupV3j7XiXUIYjWNw9hvylHXK~nTT7jkpIBazBJZfr" +
|
||||
"LJPcDZTDB0YnCOHOL-KFn4N1R5B22g0iYRABN~O10AUjQmf1epklAXPqYlzmOYeJSfTPBI" +
|
||||
"E44nEccWJp0M0KynhKVbDI0v9VYm6sPFK7WrzRyWwHL~r735wiRkwywuMmKJtA7-PuJjcW" +
|
||||
"NLkJwx6WScH2msMzhzYPi8JSZJBl~PosX934l-L0T-KNV4jg1Ih6yoCnm1748A=="
|
||||
);
|
||||
private static final String ENCRYPTED[] = new String[] {
|
||||
"AMfISa8KvTpaC7KXZzSvC2axyiSk0xPexBAf29yU~IKq21DzaU19wQcGJg-ktpG4hjGSg7" +
|
||||
"u-mJ07b61yo-EGmVGZsv3nYuQYW-GjvsZQa9nm98VljlMtWrxu7TsRXw~SQlWQxMvthqJB" +
|
||||
"1A7Y7Qa~C7-UlRytkD-cpVdgUfM-esuMWmjGs6Vc33N5U-tce5Fywa-9y7PSn3ukBO8KGR" +
|
||||
"wm7T12~H2gvhgxrVeK2roOzsV7f5dGkvBQRZJ309Vg3j0kjaxWutgI3vli0pzDbSK9d5NR" +
|
||||
"-GUDtdOb6IIfLiOckBegcv6I-wlSXjYJe8mIoaK45Ok3rEpHwWKVKS2MeuI7AmsAWgkQmW" +
|
||||
"f8irmZaKc9X910VWSO5GYu6006hSc~r2TL3O7vwtW-Z9Oq~sAam9av1PPVJzAx8A4g~m~1" +
|
||||
"avtNnncwlChsGo6mZHXqz-QMdMJXXP57f4bx36ZomkvpM-ZLlFAn-a~42KQJAApo4LfEyk" +
|
||||
"7DPY2aTXL9ArOCNQIQB4f8QLyjvAvu6M3jzCoGo0wVX6oePfdiokGflriYOcD8rL4NbnCP" +
|
||||
"~MSnVzC8LKyRzQVN1tDYj8~njuFqekls6En8KFJ-qgtL4PiYxbnBQDUPoW6y61m-S9r9e9" +
|
||||
"y8qWd6~YtdAHAxVlw287~HEp9r7kqI-cjdo1337b7~5dm83KK45g5Nfw==",
|
||||
|
||||
"AIrd65mG1FJ~9J-DDSyhryVejJBSIjYOqV3GYmHDWgwLchTwq-bJS7dub3ENk9MZ-C6FIN" +
|
||||
"gjUFRaLBtfwJnySmNf8pIf1srmgdfqGV2h77ufG5Gs0jggKPmPV~7Z1kTcgsqpL8MyrfXr" +
|
||||
"Gi86X5ey-T0SZSFc0X1EhaE-47WlyWaGf-~xth6VOR~KG7clOxaOBpks-7WKZNQf7mpQRE" +
|
||||
"4IsPJyj5p1Rf-MeDbVKbK~52IfXSuUZQ8uZr34KMoy4chjn6e-jBhM4XuaQWhsM~a3Q-zE" +
|
||||
"pV-ea6t0bQTYfsbG9ch7pJuDPHM64o5mF9FS5-JGr7MOtfP7KDNHiYM2~-uC6BIAbiqBN8" +
|
||||
"WSLX1mrHVuhiM-hiJ7U4oq~HYB6N~U980sCIW0dgFBbhalzzQhJQSrC1DFDqGfL5-L25mj" +
|
||||
"ArP8dtvN0JY3LSnbcsm-pT9ttFHCPGomLfaAuP7ohknBoXK0j9e6~splg5sUA9TfLeBfqc" +
|
||||
"Lr0Sf8b3l~PvmrVkbVcaE8yUqSS6JFdt3pavjyyAQSmSlb2jVNKGPlrov5QLzlbH7G~AUv" +
|
||||
"IehsbGQX5ptRROtSojN~iYx3WQTOa-JLEC-AL7RbRu6B62p9I0pD0JgbUfCc4C4l9E9W~s" +
|
||||
"MuaJLAXxh0b2miF7C5bzZHxbt~MtZ7Ho5qpZMitXyoE3icb43B6Y1sbA==",
|
||||
|
||||
"ACjb0FkTIQbnEzCZlYXGxekznfJad5uW~F5Mbu~0wtsI1O2veqdr7Mb0N754xdIz7929Ti" +
|
||||
"1Kz-CxVEAkb3RBbVNcYHLfjy23oQ4BCioDKQaJcdkJqXa~Orm7Ta2tbkhM1Mx05MDrQaVF" +
|
||||
"gCVXtwTsPSLVK8VwScjPIFLXgQqqZ5osq~WhaMcYe2I2RCQLOx2VzaKbT21MMbtF70a-nK" +
|
||||
"WovkRUNfJEPeJosFwF2duAD0BHHrPiryK9BPDhyOiyN82ahOi2uim1Nt5yhlP3xo7cLV2p" +
|
||||
"6kTlR1BNC5pYjtsvetZf6wk-solNUrJWIzcuc18uRDNH5K90GTL6FXPMSulM~E4ATRQfhZ" +
|
||||
"fkW9xCrBIaIQM49ms2wONsp7fvI07b1r0rt7ZwCFOFit1HSAKl8UpsAYu-EsIO1qAK7vvO" +
|
||||
"UV~0OuBXkMZEyJT-uIVfbE~xrwPE0zPYE~parSVQgi~yNQBxukUM1smAM5xXVvJu8GjmE-" +
|
||||
"kJZw1cxaYLGsJjDHDk4HfEsyQVVPZ0V3bQvhB1tg5cCsTH~VNjts4taDTPWfDZmjtVaxxr" +
|
||||
"PRII4NEDKqEzg3JBevM~yft-RDfMc8RVlm-gCGANrRQORFii7uD3o9~y~4P2tLnO7Fy3m5" +
|
||||
"rdjRsOsWnCQZzw37mcBoT9rEZPrVpD8pjebJ1~HNc764xIpXDWVt8CbA==",
|
||||
|
||||
"AHDZBKiWeaIYQS9R1l70IlRnoplwKTkLP2dLlXmVh1gB33kx65uX8OMb3hdZEO0Bbzxkkx" +
|
||||
"quqlNn5w166nJO4nPbpEzVfgtY4ClUuv~W4H4CXBr0FcZM1COAkd6rtp6~lUp7cZ8FAkpH" +
|
||||
"spl95IxlFM-F1HwiPcbmTjRO1AwCal4sH8S5WmJCvBU6jH6pBPo~9B9vAtP7vX1EwsG2Jf" +
|
||||
"CQXkVkfvbWpSicbsWn77aECedS3HkIMrXrxojp7gAiPgQhX4NR387rcUPFsMHGeUraTUPZ" +
|
||||
"D7ctk5tpUuYYwRQc5cRKHa4zOq~AQyljx5w5~FByLda--6yCe7qDcILyTygudJ4AHRs1pJ" +
|
||||
"RU3uuRTHZx0XJQo~cPsoQ2piAOohITX9~yMCimCgv2EIhY3Z-mAgo8qQ4iMbItoE1cl93I" +
|
||||
"u2YV2n4wMq9laBx0shuKOJqO3rjRnszzCbqMuFAXfc3KgGDEaCpI7049s3i2yIcv4vT9uU" +
|
||||
"AlrM-dsrdw0JgJiFYl0JXh~TO0IyrcVcLpgZYgRhEvTAdkDNwTs-2GK4tzdPEd34os4a2c" +
|
||||
"DPL8joh3jhp~eGoRzrpcdRekxENdzheL4w3wD1fJ9W2-leil1FH6EPc3FSL6e~nqbw69gN" +
|
||||
"bsuXAMQ6CobukJdJEy37uKmEw4v6WPyfYMUUacchv1JoNfkHLpnAWifQ==",
|
||||
|
||||
"AGwvKAMJcPAliP-n7F0Rrj0JMRaFGjww~zvBjyzc~SPJrBF831cMqZFRmMHotgA7S5BrH2" +
|
||||
"6CL8okI2N-7as0F2l7OPx50dFEwSVSjqBjVV6SGRFC8oS-ii1FURMz2SCHSaj6kazAYq4s" +
|
||||
"DwyqR7vnUrOtPnZujHSU~a02jinyn-QOaHkxRiUp-Oo0jlZiU5xomXgLdkhtuz6725WUDj" +
|
||||
"3uVlMtIYfeKQsTdasujHe1oQhUmp58jfg5vgZ8g87cY8rn4p9DRwDBBuo6vi5on7T13sGx" +
|
||||
"tY9wz6HTpwzDhEqpNrj~h4JibElfi0Jo8ZllmNTO1ZCNpUQgASoTtyFLD5rk6cIAMK0R7A" +
|
||||
"7hjB0aelKM-V7AHkj-Fhrcm8xIgWhKaLn2wKbVNpAkllkiLALyfWJ9dhJ804RWQTMPE-GD" +
|
||||
"kBMIFOOJ9MhpEN533OBQDwUKcoxMjl0zOMNCLx8IdCE6cLtUDKJXLB0atnDpLkBer6FwXP" +
|
||||
"81EvKDYhtp1GsbiKvZDt8LSPJQnm2EdA3Pr9fpAisJ5Ocaxlfa6~uQCuqGA9nJ9n6w03u-" +
|
||||
"ZpSMhSh4zm2s1MqijmaJRc-QNKmN~u1hh3R2hwWNi7FoStMA87sutEBXMdFI8un7StHNSE" +
|
||||
"iCYwmmW2Nu3djkM-X8gGjSsdrphTU7uOXbwazmguobFGxI0JujYruM5Q==",
|
||||
|
||||
"ALFYtPSwEEW3eTO4hLw6PZNlBKoSIseQNBi034gq6FwYEZsJOAo-1VXcvMviKw2MCP9ZkH" +
|
||||
"lTNBfzc79ms2TU8kXxc7zwUc-l2HJLWh6dj2tIQLR8bbWM7U0iUx4XB1B-FEvdhbjz7dsu" +
|
||||
"6SBXVhxo2ulrk7Q7vX3kPrePhZZldcNZcS0t65DHYYwL~E~ROjQwOO4Cb~8FgiIUjb8CCN" +
|
||||
"w5zxJpBaEt7UvZffkVwj-EWTzFy3DIjWIRizxnsI~mUI-VspPE~xlmFX~TwPS9UbwJDpm8" +
|
||||
"-WzINFcehSzF3y9rzSMX-KbU8m4YZj07itZOiIbWgLeulTUB-UgwEkfJBG0xiSUAspZf2~" +
|
||||
"t~NthBlpcdrBLADXTJ7Jmkk4MIfysV~JpDB7IVg0v4WcUUwF3sYMmBCdPCwyYf0hTrl2Yb" +
|
||||
"L6kmm4u97WgQqf0TyzXtVZYwjct4LzZlyH591y6O6AQ4Fydqos9ABInzu-SbXq6S1Hi6vr" +
|
||||
"aNWU3mcy2myie32EEXtkX7P8eXWY35GCv9ThPEYHG5g1qKOk95ZCTYYwlpgeyaMKsnN3C~" +
|
||||
"x9TJA8K8T44v7vE6--Nw4Z4zjepwkIOht9iQsA6D6wRUQpeYX8bjIyYDPC7GUHq0WhXR6E" +
|
||||
"6Ojc9k8V5uh0SZ-rCQX6sccdk3JbyRhjGP4rSKr6MmvxVVsqBjcbpxsg=="
|
||||
};
|
||||
|
||||
protected void setUp() {
|
||||
_context = new I2PAppContext();
|
||||
Object o = YKGenerator.class;
|
||||
}
|
||||
|
||||
public void testBasicAES(){
|
||||
SessionKey sessionKey = KeyGenerator.getInstance().generateSessionKey();
|
||||
Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
|
||||
byte iv[] = new byte[16];
|
||||
System.arraycopy(h.getData(), 0, iv, 0, 16);
|
||||
|
||||
String msg = "Hello world01234012345678901234501234567890123450123456789012345";
|
||||
h = SHA256Generator.getInstance().calculateHash(msg.getBytes());
|
||||
|
||||
byte aesEncr[] = new byte[msg.getBytes().length];
|
||||
byte aesDecr[] = new byte[aesEncr.length];
|
||||
_context.aes().encrypt(msg.getBytes(), 0, aesEncr, 0, sessionKey, iv, aesEncr.length);
|
||||
_context.aes().decrypt(aesEncr, 0, aesDecr, 0, sessionKey, iv, aesEncr.length);
|
||||
h = SHA256Generator.getInstance().calculateHash(aesDecr);
|
||||
|
||||
assertEquals(msg, new String(aesDecr));
|
||||
}
|
||||
|
||||
public void testAES(){
|
||||
SessionKey sessionKey = KeyGenerator.getInstance().generateSessionKey();
|
||||
Hash h = SHA256Generator.getInstance().calculateHash(sessionKey.getData());
|
||||
byte iv[] = new byte[16];
|
||||
System.arraycopy(h.getData(), 0, iv, 0, 16);
|
||||
|
||||
String msg = "Hello world";
|
||||
|
||||
byte encrypted[] = _context.elGamalAESEngine().encryptAESBlock(msg.getBytes(), sessionKey, iv, null, null, 64);
|
||||
Set foundTags = new HashSet();
|
||||
SessionKey foundKey = new SessionKey();
|
||||
byte decrypted[] = null;
|
||||
try{
|
||||
decrypted = _context.elGamalAESEngine().decryptAESBlock(encrypted, 0, encrypted.length, sessionKey, iv, null, foundTags, foundKey);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
assertNotNull(decrypted);
|
||||
String read = new String(decrypted);
|
||||
assertEquals(msg, read);
|
||||
}
|
||||
|
||||
public void testRoundTrip(){
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
|
||||
String msg = "Hello world";
|
||||
Set toBeDelivered = new HashSet();
|
||||
SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
if (key == null)
|
||||
key = _context.sessionKeyManager().createSession(pubKey);
|
||||
byte[] encrypted = _context.elGamalAESEngine().encrypt(msg.getBytes(), pubKey, key, 64);
|
||||
byte[] decrypted = null;
|
||||
try{
|
||||
decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
assertNotNull(decrypted);
|
||||
String read = new String(decrypted);
|
||||
assertEquals(msg, read);
|
||||
}
|
||||
|
||||
public void testElGamal(){
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
SessionKey key = KeyGenerator.getInstance().generateSessionKey();
|
||||
|
||||
ByteArrayOutputStream elgSrc = new ByteArrayOutputStream(256);
|
||||
try{
|
||||
key.writeBytes(elgSrc);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}catch(IOException ioe){
|
||||
ioe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
|
||||
byte preIV[] = new byte[32];
|
||||
RandomSource.getInstance().nextBytes(preIV);
|
||||
try{
|
||||
elgSrc.write(preIV);
|
||||
elgSrc.flush();
|
||||
}catch(IOException ioe){
|
||||
ioe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
|
||||
|
||||
byte elgEncr[] = _context.elGamalEngine().encrypt(elgSrc.toByteArray(), pubKey);
|
||||
byte elgDecr[] = _context.elGamalEngine().decrypt(elgEncr, privKey);
|
||||
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(elgDecr);
|
||||
SessionKey nk = new SessionKey();
|
||||
|
||||
try{
|
||||
nk.readBytes(bais);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}catch(IOException ioe){
|
||||
ioe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
byte postpreIV[] = new byte[32];
|
||||
|
||||
int read = 0;
|
||||
try{
|
||||
read = bais.read(postpreIV);
|
||||
}catch(IOException ioe){
|
||||
ioe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
|
||||
assertEquals(read, postpreIV.length);
|
||||
|
||||
|
||||
assertTrue(DataHelper.eq(preIV, postpreIV));
|
||||
assertEquals(key, nk);
|
||||
}
|
||||
}
|
||||
|
||||
public void testLoop(){
|
||||
for(int i = 0; i < 5; i++){
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
|
||||
byte[] msg = new byte[400];
|
||||
RandomSource.getInstance().nextBytes(msg);
|
||||
SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
if (key == null)
|
||||
key = _context.sessionKeyManager().createSession(pubKey);
|
||||
|
||||
byte[] encrypted = _context.elGamalAESEngine().encrypt(msg, pubKey, key, 1024);
|
||||
byte[] decrypted = null;
|
||||
try{
|
||||
decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
|
||||
assertTrue(DataHelper.eq(msg, decrypted));
|
||||
}
|
||||
}
|
||||
|
||||
public void testVerifySelf(){
|
||||
Object keypair[] = _context.keyGenerator().generatePKIKeypair();
|
||||
PublicKey pub = (PublicKey)keypair[0];
|
||||
PrivateKey priv = (PrivateKey)keypair[1];
|
||||
|
||||
for (int i = 0; i < UNENCRYPTED.length; i++) {
|
||||
byte orig[] = UNENCRYPTED[i].getBytes();
|
||||
|
||||
byte encrypted[] = _context.elGamalEngine().encrypt(orig, pub);
|
||||
byte decrypted[] = _context.elGamalEngine().decrypt(encrypted, priv);
|
||||
|
||||
assertTrue(DataHelper.eq(decrypted, orig));
|
||||
}
|
||||
}
|
||||
|
||||
public void testVerifyCompatability(){
|
||||
PublicKey pub = new PublicKey();
|
||||
PrivateKey priv = new PrivateKey();
|
||||
try{
|
||||
pub.fromBase64(PUBLIC_KEY);
|
||||
priv.fromBase64(PRIVATE_KEY);
|
||||
}catch(DataFormatException dfe){
|
||||
dfe.printStackTrace();
|
||||
fail();
|
||||
}
|
||||
|
||||
for (int i = 0; i < ENCRYPTED.length; i++) {
|
||||
byte enc[] = Base64.decode(ENCRYPTED[i]);
|
||||
byte decrypted[] = _context.elGamalEngine().decrypt(enc, priv);
|
||||
|
||||
assertTrue(DataHelper.eq(decrypted, UNENCRYPTED[i].getBytes()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testMultiple(){
|
||||
Object[] keys = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
byte[] message = new byte[222];
|
||||
for (int x = 0; x < 25; x++) {
|
||||
_context.random().nextBytes(message);
|
||||
keys = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubkey = (PublicKey)keys[0];
|
||||
PrivateKey privkey = (PrivateKey)keys[1];
|
||||
|
||||
byte[] e = _context.elGamalEngine().encrypt(message, pubkey);
|
||||
byte[] d = _context.elGamalEngine().decrypt(e, privkey);
|
||||
|
||||
assertTrue(DataHelper.eq(d, message));
|
||||
}
|
||||
}
|
||||
|
||||
public void testElGamalAESEngine() throws Exception{
|
||||
I2PAppContext ctx = new I2PAppContext();
|
||||
ElGamalAESEngine e = new ElGamalAESEngine(ctx);
|
||||
Object kp[] = ctx.keyGenerator().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)kp[0];
|
||||
PrivateKey privKey = (PrivateKey)kp[1];
|
||||
SessionKey sessionKey = ctx.keyGenerator().generateSessionKey();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Set tags = new HashSet(5);
|
||||
if (i == 0) {
|
||||
for (int j = 0; j < 5; j++)
|
||||
tags.add(new SessionTag(true));
|
||||
}
|
||||
byte encrypted[] = e.encrypt("blah".getBytes(), pubKey, sessionKey, tags, 1024);
|
||||
byte decrypted[] = e.decrypt(encrypted, privKey);
|
||||
assertEquals("blah", new String(decrypted));
|
||||
|
||||
ctx.sessionKeyManager().tagsDelivered(pubKey, sessionKey, tags);
|
||||
}
|
||||
}
|
||||
|
||||
public void testElGamalEngine(){
|
||||
int numRuns = 100;
|
||||
RandomSource.getInstance().nextBoolean();
|
||||
I2PAppContext context = new I2PAppContext();
|
||||
|
||||
for (int i = 0; i < numRuns; i++) {
|
||||
Object pair[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
|
||||
PublicKey pubkey = (PublicKey) pair[0];
|
||||
PrivateKey privkey = (PrivateKey) pair[1];
|
||||
byte buf[] = new byte[128];
|
||||
RandomSource.getInstance().nextBytes(buf);
|
||||
byte encr[] = context.elGamalEngine().encrypt(buf, pubkey);
|
||||
byte decr[] = context.elGamalEngine().decrypt(encr, privkey);
|
||||
|
||||
assertTrue(DataHelper.eq(decr, buf));
|
||||
}
|
||||
}
|
||||
|
||||
public void testYKGen(){
|
||||
RandomSource.getInstance().nextBoolean();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
YKGenerator.getNextYK();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,206 +0,0 @@
|
||||
package net.i2p.crypto;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.Base64;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.PrivateKey;
|
||||
import net.i2p.data.PublicKey;
|
||||
|
||||
/**
|
||||
* Unit test verifying the ElGamal encryption/decryption with some test
|
||||
* data. The keys generated & data stored were generated by jrandom on
|
||||
* a pentium4 w/ an optimized jbigi installed and verified with pure java.
|
||||
*
|
||||
*/
|
||||
public class ElGamalVerify {
|
||||
private I2PAppContext _context;
|
||||
|
||||
private static final String UNENCRYPTED[] = new String[] {
|
||||
"",
|
||||
"hello world",
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890" +
|
||||
"123456789012",
|
||||
"\0x00",
|
||||
"\0x00\0x00\0x00",
|
||||
"\0x00\0x01\0x02\0x00",
|
||||
};
|
||||
private static final String PUBLIC_KEY = new String(
|
||||
"pOvBUMrSUUeN5awynzbPbCAwe3MqWprhSpp3OR7pvdfm9PhWaNbPoKRLeEmDoUwyNDoHE0" +
|
||||
"E6mcZSG8qPQ8XUZFlczpilOl0MJBvsI9u9SMyi~bEqzSgzh9FNfS-NcGji3q2wI~Ux~q5B" +
|
||||
"KOjGlyMLgd1nxl5R5wIYL4uHKZNaYuArsRYmtV~MgMQPGvDtIbdGTV6aL6UbOYryzQSUMY" +
|
||||
"OuO3S~YoBjA6Nmi0SeJM3tyTxlI6U1EYjR6oQcI4SOFUW4L~8pfYWijcncCODAqpXVN6ZI" +
|
||||
"AJ3a6vjxGu56IDp4xCcKlOEHgdXvqmEC67dR5qf2btH6dtWoB3-Z6QPsS6tPTQ=="
|
||||
);
|
||||
private static final String PRIVATE_KEY = new String(
|
||||
"gMlIhURVXU8uPube20Xr8E1K11g-3qZxOj1riThHqt-rBx72MPq5ivT1rr28cE9mzOmsXi" +
|
||||
"bbsuBuQKYDvF7hGICRB3ROSPePYhcupV3j7XiXUIYjWNw9hvylHXK~nTT7jkpIBazBJZfr" +
|
||||
"LJPcDZTDB0YnCOHOL-KFn4N1R5B22g0iYRABN~O10AUjQmf1epklAXPqYlzmOYeJSfTPBI" +
|
||||
"E44nEccWJp0M0KynhKVbDI0v9VYm6sPFK7WrzRyWwHL~r735wiRkwywuMmKJtA7-PuJjcW" +
|
||||
"NLkJwx6WScH2msMzhzYPi8JSZJBl~PosX934l-L0T-KNV4jg1Ih6yoCnm1748A=="
|
||||
);
|
||||
private static final String ENCRYPTED[] = new String[] {
|
||||
"AMfISa8KvTpaC7KXZzSvC2axyiSk0xPexBAf29yU~IKq21DzaU19wQcGJg-ktpG4hjGSg7" +
|
||||
"u-mJ07b61yo-EGmVGZsv3nYuQYW-GjvsZQa9nm98VljlMtWrxu7TsRXw~SQlWQxMvthqJB" +
|
||||
"1A7Y7Qa~C7-UlRytkD-cpVdgUfM-esuMWmjGs6Vc33N5U-tce5Fywa-9y7PSn3ukBO8KGR" +
|
||||
"wm7T12~H2gvhgxrVeK2roOzsV7f5dGkvBQRZJ309Vg3j0kjaxWutgI3vli0pzDbSK9d5NR" +
|
||||
"-GUDtdOb6IIfLiOckBegcv6I-wlSXjYJe8mIoaK45Ok3rEpHwWKVKS2MeuI7AmsAWgkQmW" +
|
||||
"f8irmZaKc9X910VWSO5GYu6006hSc~r2TL3O7vwtW-Z9Oq~sAam9av1PPVJzAx8A4g~m~1" +
|
||||
"avtNnncwlChsGo6mZHXqz-QMdMJXXP57f4bx36ZomkvpM-ZLlFAn-a~42KQJAApo4LfEyk" +
|
||||
"7DPY2aTXL9ArOCNQIQB4f8QLyjvAvu6M3jzCoGo0wVX6oePfdiokGflriYOcD8rL4NbnCP" +
|
||||
"~MSnVzC8LKyRzQVN1tDYj8~njuFqekls6En8KFJ-qgtL4PiYxbnBQDUPoW6y61m-S9r9e9" +
|
||||
"y8qWd6~YtdAHAxVlw287~HEp9r7kqI-cjdo1337b7~5dm83KK45g5Nfw==",
|
||||
|
||||
"AIrd65mG1FJ~9J-DDSyhryVejJBSIjYOqV3GYmHDWgwLchTwq-bJS7dub3ENk9MZ-C6FIN" +
|
||||
"gjUFRaLBtfwJnySmNf8pIf1srmgdfqGV2h77ufG5Gs0jggKPmPV~7Z1kTcgsqpL8MyrfXr" +
|
||||
"Gi86X5ey-T0SZSFc0X1EhaE-47WlyWaGf-~xth6VOR~KG7clOxaOBpks-7WKZNQf7mpQRE" +
|
||||
"4IsPJyj5p1Rf-MeDbVKbK~52IfXSuUZQ8uZr34KMoy4chjn6e-jBhM4XuaQWhsM~a3Q-zE" +
|
||||
"pV-ea6t0bQTYfsbG9ch7pJuDPHM64o5mF9FS5-JGr7MOtfP7KDNHiYM2~-uC6BIAbiqBN8" +
|
||||
"WSLX1mrHVuhiM-hiJ7U4oq~HYB6N~U980sCIW0dgFBbhalzzQhJQSrC1DFDqGfL5-L25mj" +
|
||||
"ArP8dtvN0JY3LSnbcsm-pT9ttFHCPGomLfaAuP7ohknBoXK0j9e6~splg5sUA9TfLeBfqc" +
|
||||
"Lr0Sf8b3l~PvmrVkbVcaE8yUqSS6JFdt3pavjyyAQSmSlb2jVNKGPlrov5QLzlbH7G~AUv" +
|
||||
"IehsbGQX5ptRROtSojN~iYx3WQTOa-JLEC-AL7RbRu6B62p9I0pD0JgbUfCc4C4l9E9W~s" +
|
||||
"MuaJLAXxh0b2miF7C5bzZHxbt~MtZ7Ho5qpZMitXyoE3icb43B6Y1sbA==",
|
||||
|
||||
"ACjb0FkTIQbnEzCZlYXGxekznfJad5uW~F5Mbu~0wtsI1O2veqdr7Mb0N754xdIz7929Ti" +
|
||||
"1Kz-CxVEAkb3RBbVNcYHLfjy23oQ4BCioDKQaJcdkJqXa~Orm7Ta2tbkhM1Mx05MDrQaVF" +
|
||||
"gCVXtwTsPSLVK8VwScjPIFLXgQqqZ5osq~WhaMcYe2I2RCQLOx2VzaKbT21MMbtF70a-nK" +
|
||||
"WovkRUNfJEPeJosFwF2duAD0BHHrPiryK9BPDhyOiyN82ahOi2uim1Nt5yhlP3xo7cLV2p" +
|
||||
"6kTlR1BNC5pYjtsvetZf6wk-solNUrJWIzcuc18uRDNH5K90GTL6FXPMSulM~E4ATRQfhZ" +
|
||||
"fkW9xCrBIaIQM49ms2wONsp7fvI07b1r0rt7ZwCFOFit1HSAKl8UpsAYu-EsIO1qAK7vvO" +
|
||||
"UV~0OuBXkMZEyJT-uIVfbE~xrwPE0zPYE~parSVQgi~yNQBxukUM1smAM5xXVvJu8GjmE-" +
|
||||
"kJZw1cxaYLGsJjDHDk4HfEsyQVVPZ0V3bQvhB1tg5cCsTH~VNjts4taDTPWfDZmjtVaxxr" +
|
||||
"PRII4NEDKqEzg3JBevM~yft-RDfMc8RVlm-gCGANrRQORFii7uD3o9~y~4P2tLnO7Fy3m5" +
|
||||
"rdjRsOsWnCQZzw37mcBoT9rEZPrVpD8pjebJ1~HNc764xIpXDWVt8CbA==",
|
||||
|
||||
"AHDZBKiWeaIYQS9R1l70IlRnoplwKTkLP2dLlXmVh1gB33kx65uX8OMb3hdZEO0Bbzxkkx" +
|
||||
"quqlNn5w166nJO4nPbpEzVfgtY4ClUuv~W4H4CXBr0FcZM1COAkd6rtp6~lUp7cZ8FAkpH" +
|
||||
"spl95IxlFM-F1HwiPcbmTjRO1AwCal4sH8S5WmJCvBU6jH6pBPo~9B9vAtP7vX1EwsG2Jf" +
|
||||
"CQXkVkfvbWpSicbsWn77aECedS3HkIMrXrxojp7gAiPgQhX4NR387rcUPFsMHGeUraTUPZ" +
|
||||
"D7ctk5tpUuYYwRQc5cRKHa4zOq~AQyljx5w5~FByLda--6yCe7qDcILyTygudJ4AHRs1pJ" +
|
||||
"RU3uuRTHZx0XJQo~cPsoQ2piAOohITX9~yMCimCgv2EIhY3Z-mAgo8qQ4iMbItoE1cl93I" +
|
||||
"u2YV2n4wMq9laBx0shuKOJqO3rjRnszzCbqMuFAXfc3KgGDEaCpI7049s3i2yIcv4vT9uU" +
|
||||
"AlrM-dsrdw0JgJiFYl0JXh~TO0IyrcVcLpgZYgRhEvTAdkDNwTs-2GK4tzdPEd34os4a2c" +
|
||||
"DPL8joh3jhp~eGoRzrpcdRekxENdzheL4w3wD1fJ9W2-leil1FH6EPc3FSL6e~nqbw69gN" +
|
||||
"bsuXAMQ6CobukJdJEy37uKmEw4v6WPyfYMUUacchv1JoNfkHLpnAWifQ==",
|
||||
|
||||
"AGwvKAMJcPAliP-n7F0Rrj0JMRaFGjww~zvBjyzc~SPJrBF831cMqZFRmMHotgA7S5BrH2" +
|
||||
"6CL8okI2N-7as0F2l7OPx50dFEwSVSjqBjVV6SGRFC8oS-ii1FURMz2SCHSaj6kazAYq4s" +
|
||||
"DwyqR7vnUrOtPnZujHSU~a02jinyn-QOaHkxRiUp-Oo0jlZiU5xomXgLdkhtuz6725WUDj" +
|
||||
"3uVlMtIYfeKQsTdasujHe1oQhUmp58jfg5vgZ8g87cY8rn4p9DRwDBBuo6vi5on7T13sGx" +
|
||||
"tY9wz6HTpwzDhEqpNrj~h4JibElfi0Jo8ZllmNTO1ZCNpUQgASoTtyFLD5rk6cIAMK0R7A" +
|
||||
"7hjB0aelKM-V7AHkj-Fhrcm8xIgWhKaLn2wKbVNpAkllkiLALyfWJ9dhJ804RWQTMPE-GD" +
|
||||
"kBMIFOOJ9MhpEN533OBQDwUKcoxMjl0zOMNCLx8IdCE6cLtUDKJXLB0atnDpLkBer6FwXP" +
|
||||
"81EvKDYhtp1GsbiKvZDt8LSPJQnm2EdA3Pr9fpAisJ5Ocaxlfa6~uQCuqGA9nJ9n6w03u-" +
|
||||
"ZpSMhSh4zm2s1MqijmaJRc-QNKmN~u1hh3R2hwWNi7FoStMA87sutEBXMdFI8un7StHNSE" +
|
||||
"iCYwmmW2Nu3djkM-X8gGjSsdrphTU7uOXbwazmguobFGxI0JujYruM5Q==",
|
||||
|
||||
"ALFYtPSwEEW3eTO4hLw6PZNlBKoSIseQNBi034gq6FwYEZsJOAo-1VXcvMviKw2MCP9ZkH" +
|
||||
"lTNBfzc79ms2TU8kXxc7zwUc-l2HJLWh6dj2tIQLR8bbWM7U0iUx4XB1B-FEvdhbjz7dsu" +
|
||||
"6SBXVhxo2ulrk7Q7vX3kPrePhZZldcNZcS0t65DHYYwL~E~ROjQwOO4Cb~8FgiIUjb8CCN" +
|
||||
"w5zxJpBaEt7UvZffkVwj-EWTzFy3DIjWIRizxnsI~mUI-VspPE~xlmFX~TwPS9UbwJDpm8" +
|
||||
"-WzINFcehSzF3y9rzSMX-KbU8m4YZj07itZOiIbWgLeulTUB-UgwEkfJBG0xiSUAspZf2~" +
|
||||
"t~NthBlpcdrBLADXTJ7Jmkk4MIfysV~JpDB7IVg0v4WcUUwF3sYMmBCdPCwyYf0hTrl2Yb" +
|
||||
"L6kmm4u97WgQqf0TyzXtVZYwjct4LzZlyH591y6O6AQ4Fydqos9ABInzu-SbXq6S1Hi6vr" +
|
||||
"aNWU3mcy2myie32EEXtkX7P8eXWY35GCv9ThPEYHG5g1qKOk95ZCTYYwlpgeyaMKsnN3C~" +
|
||||
"x9TJA8K8T44v7vE6--Nw4Z4zjepwkIOht9iQsA6D6wRUQpeYX8bjIyYDPC7GUHq0WhXR6E" +
|
||||
"6Ojc9k8V5uh0SZ-rCQX6sccdk3JbyRhjGP4rSKr6MmvxVVsqBjcbpxsg=="
|
||||
};
|
||||
|
||||
public static void main(String args[]) {
|
||||
ElGamalVerify verify = new ElGamalVerify();
|
||||
verify.verifySelf();
|
||||
verify.verifyCompatability();
|
||||
if (args.length > 0)
|
||||
verify.generateEncrypted();
|
||||
}
|
||||
|
||||
public ElGamalVerify() {
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
/** verify that we can decrypt what we encrypt */
|
||||
private void verifySelf() {
|
||||
try {
|
||||
Object keypair[] = _context.keyGenerator().generatePKIKeypair();
|
||||
PublicKey pub = (PublicKey)keypair[0];
|
||||
PrivateKey priv = (PrivateKey)keypair[1];
|
||||
|
||||
for (int i = 0; i < UNENCRYPTED.length; i++) {
|
||||
byte orig[] = UNENCRYPTED[i].getBytes();
|
||||
|
||||
byte encrypted[] = _context.elGamalEngine().encrypt(orig, pub);
|
||||
byte decrypted[] = _context.elGamalEngine().decrypt(encrypted, priv);
|
||||
|
||||
if (DataHelper.eq(decrypted, orig))
|
||||
log("OK : verifySelf[" + i + "] passed");
|
||||
else
|
||||
log("ERROR: verifySelf[" + i + "] failed");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log("ERROR: verifySelf blew up: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/** verify that we can decrypt what other people encrypt */
|
||||
private void verifyCompatability() {
|
||||
verifyDecrypt();
|
||||
}
|
||||
|
||||
private void verifyDecrypt() {
|
||||
try {
|
||||
PublicKey pub = new PublicKey();
|
||||
PrivateKey priv = new PrivateKey();
|
||||
pub.fromBase64(PUBLIC_KEY);
|
||||
priv.fromBase64(PRIVATE_KEY);
|
||||
|
||||
for (int i = 0; i < ENCRYPTED.length; i++) {
|
||||
byte enc[] = Base64.decode(ENCRYPTED[i]);
|
||||
byte decrypted[] = _context.elGamalEngine().decrypt(enc, priv);
|
||||
|
||||
if (DataHelper.eq(decrypted, UNENCRYPTED[i].getBytes()))
|
||||
log("OK : verifyDecrypt[" + i + "] passed");
|
||||
else
|
||||
log("ERROR: verifyDecrypt[" + i + "] failed");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log("ERROR: generateEncrypted blew up: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
private void generateEncrypted() {
|
||||
try {
|
||||
Object keypair[] = _context.keyGenerator().generatePKIKeypair();
|
||||
PublicKey pub = (PublicKey)keypair[0];
|
||||
PrivateKey priv = (PrivateKey)keypair[1];
|
||||
|
||||
log("PUBLIC : " + pub.toBase64());
|
||||
log("PRIVATE: " + priv.toBase64());
|
||||
|
||||
for (int i = 0; i < UNENCRYPTED.length; i++) {
|
||||
byte orig[] = UNENCRYPTED[i].getBytes();
|
||||
|
||||
byte encrypted[] = _context.elGamalEngine().encrypt(orig, pub);
|
||||
|
||||
System.out.println("Encrypted [" + i + "]: ");
|
||||
String enc = Base64.encode(encrypted);
|
||||
for (int j = 0; j < enc.length(); j++) {
|
||||
int remaining = enc.length() - j*70;
|
||||
if (remaining > 0) {
|
||||
String cur = enc.substring(j * 70, remaining > 70 ? (j+1)*70 : enc.length());
|
||||
System.out.println(cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log("ERROR: generateEncrypted blew up: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void log(String msg) {
|
||||
System.out.println(msg);
|
||||
}
|
||||
}
|
||||
|
35
core/java/test/net/i2p/crypto/HMACSHA256Test.java
Normal file
35
core/java/test/net/i2p/crypto/HMACSHA256Test.java
Normal file
@ -0,0 +1,35 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.SessionKey;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class HMACSHA256Test extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
|
||||
protected void setUp() {
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
public void testMultiple(){
|
||||
int size = 1;
|
||||
for(int i = 0; i < 24; i++){
|
||||
SessionKey key = _context.keyGenerator().generateSessionKey();
|
||||
|
||||
byte[] message = new byte[size];
|
||||
size*=2;
|
||||
_context.random().nextBytes(message);
|
||||
|
||||
_context.hmac().calculate(key, message);
|
||||
}
|
||||
}
|
||||
}
|
50
core/java/test/net/i2p/crypto/KeyGeneratorTest.java
Normal file
50
core/java/test/net/i2p/crypto/KeyGeneratorTest.java
Normal file
@ -0,0 +1,50 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.util.RandomSource;
|
||||
import net.i2p.data.SigningPrivateKey;
|
||||
import net.i2p.data.SigningPublicKey;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.Signature;
|
||||
import net.i2p.data.PublicKey;
|
||||
import net.i2p.data.PrivateKey;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class KeyGeneratorTest extends TestCase{
|
||||
public void testKeyGen(){
|
||||
RandomSource.getInstance().nextBoolean();
|
||||
byte src[] = new byte[200];
|
||||
RandomSource.getInstance().nextBytes(src);
|
||||
|
||||
I2PAppContext ctx = new I2PAppContext();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
byte ctext[] = ctx.elGamalEngine().encrypt(src, (PublicKey) keys[0]);
|
||||
byte ptext[] = ctx.elGamalEngine().decrypt(ctext, (PrivateKey) keys[1]);
|
||||
assertTrue(DataHelper.eq(ptext, src));
|
||||
}
|
||||
|
||||
Object obj[] = KeyGenerator.getInstance().generateSigningKeypair();
|
||||
SigningPublicKey fake = (SigningPublicKey) obj[0];
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Object keys[] = KeyGenerator.getInstance().generateSigningKeypair();
|
||||
|
||||
Signature sig = DSAEngine.getInstance().sign(src, (SigningPrivateKey) keys[1]);
|
||||
assertTrue(DSAEngine.getInstance().verifySignature(sig, src, (SigningPublicKey) keys[0]));
|
||||
assertFalse(DSAEngine.getInstance().verifySignature(sig, src, fake));
|
||||
}
|
||||
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
KeyGenerator.getInstance().generateSessionKey();
|
||||
}
|
||||
}
|
||||
}
|
146
core/java/test/net/i2p/crypto/SHA1HashTest.java
Normal file
146
core/java/test/net/i2p/crypto/SHA1HashTest.java
Normal file
@ -0,0 +1,146 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
/* @(#)SHA1Test.java 1.10 2004-04-24
|
||||
* This file was freely contributed to the LimeWire project and is covered
|
||||
* by its existing GPL licence, but it may be used individually as a public
|
||||
* domain implementation of a published algorithm (see below for references).
|
||||
* It was also freely contributed to the Bitzi public domain sources.
|
||||
* @author Philippe Verdy
|
||||
*/
|
||||
|
||||
/* Sun may wish to change the following package name, if integrating this
|
||||
* class in the Sun JCE Security Provider for Java 1.5 (code-named Tiger).
|
||||
*/
|
||||
//package com.bitzi.util;
|
||||
|
||||
import java.security.*;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class SHA1HashTest extends TestCase{
|
||||
|
||||
private final SHA1 hash = new SHA1();
|
||||
|
||||
public void testSHA1() throws Exception{
|
||||
tst(1, 1,"abc","A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D");
|
||||
|
||||
tst(1, 2,"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
|
||||
"84983E44 1C3BD26e BAAE4AA1 F95129E5 E54670F1");
|
||||
tst(1, 3, 1000000, "a",
|
||||
"34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F");
|
||||
|
||||
tst(2, 2, new byte[] {/* 8 bits, i.e. 1 byte */
|
||||
(byte)0x5e},
|
||||
"5e6f80a3 4a9798ca fc6a5db9 6cc57ba4 c4db59c2");
|
||||
tst(2, 4, new byte[] {/* 128 bits, i.e. 16 bytes */
|
||||
(byte)0x9a,(byte)0x7d,(byte)0xfd,(byte)0xf1,(byte)0xec,(byte)0xea,(byte)0xd0,(byte)0x6e,
|
||||
(byte)0xd6,(byte)0x46,(byte)0xaa,(byte)0x55,(byte)0xfe,(byte)0x75,(byte)0x71,(byte)0x46},
|
||||
"82abff66 05dbe1c1 7def12a3 94fa22a8 2b544a35");
|
||||
|
||||
tst(3, 2, new byte[] {/* 1304 bits, i.e. 163 bytes */
|
||||
(byte)0xf7,(byte)0x8f,(byte)0x92,(byte)0x14,(byte)0x1b,(byte)0xcd,(byte)0x17,(byte)0x0a,
|
||||
(byte)0xe8,(byte)0x9b,(byte)0x4f,(byte)0xba,(byte)0x15,(byte)0xa1,(byte)0xd5,(byte)0x9f,
|
||||
(byte)0x3f,(byte)0xd8,(byte)0x4d,(byte)0x22,(byte)0x3c,(byte)0x92,(byte)0x51,(byte)0xbd,
|
||||
(byte)0xac,(byte)0xbb,(byte)0xae,(byte)0x61,(byte)0xd0,(byte)0x5e,(byte)0xd1,(byte)0x15,
|
||||
(byte)0xa0,(byte)0x6a,(byte)0x7c,(byte)0xe1,(byte)0x17,(byte)0xb7,(byte)0xbe,(byte)0xea,
|
||||
(byte)0xd2,(byte)0x44,(byte)0x21,(byte)0xde,(byte)0xd9,(byte)0xc3,(byte)0x25,(byte)0x92,
|
||||
(byte)0xbd,(byte)0x57,(byte)0xed,(byte)0xea,(byte)0xe3,(byte)0x9c,(byte)0x39,(byte)0xfa,
|
||||
(byte)0x1f,(byte)0xe8,(byte)0x94,(byte)0x6a,(byte)0x84,(byte)0xd0,(byte)0xcf,(byte)0x1f,
|
||||
(byte)0x7b,(byte)0xee,(byte)0xad,(byte)0x17,(byte)0x13,(byte)0xe2,(byte)0xe0,(byte)0x95,
|
||||
(byte)0x98,(byte)0x97,(byte)0x34,(byte)0x7f,(byte)0x67,(byte)0xc8,(byte)0x0b,(byte)0x04,
|
||||
(byte)0x00,(byte)0xc2,(byte)0x09,(byte)0x81,(byte)0x5d,(byte)0x6b,(byte)0x10,(byte)0xa6,
|
||||
(byte)0x83,(byte)0x83,(byte)0x6f,(byte)0xd5,(byte)0x56,(byte)0x2a,(byte)0x56,(byte)0xca,
|
||||
(byte)0xb1,(byte)0xa2,(byte)0x8e,(byte)0x81,(byte)0xb6,(byte)0x57,(byte)0x66,(byte)0x54,
|
||||
(byte)0x63,(byte)0x1c,(byte)0xf1,(byte)0x65,(byte)0x66,(byte)0xb8,(byte)0x6e,(byte)0x3b,
|
||||
(byte)0x33,(byte)0xa1,(byte)0x08,(byte)0xb0,(byte)0x53,(byte)0x07,(byte)0xc0,(byte)0x0a,
|
||||
(byte)0xff,(byte)0x14,(byte)0xa7,(byte)0x68,(byte)0xed,(byte)0x73,(byte)0x50,(byte)0x60,
|
||||
(byte)0x6a,(byte)0x0f,(byte)0x85,(byte)0xe6,(byte)0xa9,(byte)0x1d,(byte)0x39,(byte)0x6f,
|
||||
(byte)0x5b,(byte)0x5c,(byte)0xbe,(byte)0x57,(byte)0x7f,(byte)0x9b,(byte)0x38,(byte)0x80,
|
||||
(byte)0x7c,(byte)0x7d,(byte)0x52,(byte)0x3d,(byte)0x6d,(byte)0x79,(byte)0x2f,(byte)0x6e,
|
||||
(byte)0xbc,(byte)0x24,(byte)0xa4,(byte)0xec,(byte)0xf2,(byte)0xb3,(byte)0xa4,(byte)0x27,
|
||||
(byte)0xcd,(byte)0xbb,(byte)0xfb},
|
||||
"cb0082c8 f197d260 991ba6a4 60e76e20 2bad27b3");
|
||||
|
||||
{
|
||||
final int RETRIES = 10;
|
||||
final int ITERATIONS = 2000;
|
||||
final int BLOCKSIZE = 65536;
|
||||
byte[] input = new byte[BLOCKSIZE];
|
||||
for (int i = BLOCKSIZE; --i >= 0; )
|
||||
input[i] = (byte)i;
|
||||
|
||||
|
||||
|
||||
for (int retry = 0; retry < RETRIES; retry++) {
|
||||
for (int i = ITERATIONS; --i >= 0; );
|
||||
for (int i = ITERATIONS; --i >= 0; )
|
||||
hash.engineUpdate(input, 0, BLOCKSIZE);
|
||||
}
|
||||
hash.engineReset();
|
||||
|
||||
|
||||
MessageDigest md = MessageDigest.getInstance("SHA");
|
||||
for (int retry = 0; retry < RETRIES; retry++) {
|
||||
for (int i = ITERATIONS; --i >= 0; );
|
||||
for (int i = ITERATIONS; --i >= 0; )
|
||||
md.update(input, 0, BLOCKSIZE);
|
||||
}
|
||||
md.reset();
|
||||
}
|
||||
}
|
||||
|
||||
private final void tst(final int set, final int vector,
|
||||
final String source,
|
||||
final String expect) {
|
||||
byte[] input = new byte[source.length()];
|
||||
for (int i = 0; i < input.length; i++)
|
||||
input[i] = (byte)source.charAt(i);
|
||||
tst(set, vector, input, expect);
|
||||
}
|
||||
|
||||
private final void tst(final int set, final int vector,
|
||||
final byte[] input,
|
||||
final String expect) {
|
||||
|
||||
hash.engineUpdate(input, 0, input.length);
|
||||
tstResult(expect);
|
||||
}
|
||||
|
||||
private final void tst(final int set, final int vector,
|
||||
final int times, final String source,
|
||||
final String expect) {
|
||||
byte[] input = new byte[source.length()];
|
||||
for (int i = 0; i < input.length; i++)
|
||||
input[i] = (byte)source.charAt(i);
|
||||
for (int i = 0; i < times; i++)
|
||||
hash.engineUpdate(input, 0, input.length);
|
||||
tstResult(expect);
|
||||
}
|
||||
|
||||
private final void tstResult(String expect) {
|
||||
final String result = toHex(hash.engineDigest());
|
||||
expect = expect.toUpperCase();
|
||||
assertEquals(expect, result);
|
||||
|
||||
}
|
||||
|
||||
private final String toHex(final byte[] bytes) {
|
||||
StringBuffer buf = new StringBuffer(bytes.length * 2);
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
if ((i & 3) == 0 && i != 0)
|
||||
buf.append(' ');
|
||||
buf.append(HEX.charAt((bytes[i] >> 4) & 0xF))
|
||||
.append(HEX.charAt( bytes[i] & 0xF));
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
private static final String HEX = "0123456789ABCDEF";
|
||||
}
|
100
core/java/test/net/i2p/crypto/SHA256Test.java
Normal file
100
core/java/test/net/i2p/crypto/SHA256Test.java
Normal file
@ -0,0 +1,100 @@
|
||||
package net.i2p.crypto;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.Hash;
|
||||
|
||||
import org.bouncycastle.crypto.digests.SHA256Digest;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class SHA256Test extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
|
||||
protected void setUp() {
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
public void testMultiple(){
|
||||
int size = 1;
|
||||
for(int i = 0; i < 24; i++){
|
||||
byte[] message = new byte[size];
|
||||
size*=2;
|
||||
_context.random().nextBytes(message);
|
||||
|
||||
SHA256Generator.getInstance().calculateHash(message);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCopyConstructor(){
|
||||
SHA256Digest orig = new SHA256Digest();
|
||||
byte[] message = "update this!".getBytes();
|
||||
orig.update(message, 0, message.length);
|
||||
|
||||
SHA256Digest copy = new SHA256Digest(orig);
|
||||
|
||||
byte[] origData = new byte[32];
|
||||
orig.doFinal(origData, 0);
|
||||
byte[] copyData = new byte[32];
|
||||
copy.doFinal(copyData, 0);
|
||||
|
||||
assertTrue(DataHelper.eq(origData, copyData));
|
||||
|
||||
}
|
||||
|
||||
public void testCheckName(){
|
||||
SHA256Digest digest = new SHA256Digest();
|
||||
assertEquals("SHA-256", digest.getAlgorithmName());
|
||||
}
|
||||
|
||||
public void testManualUpdate(){
|
||||
byte[] data = "deathnotronic".getBytes();
|
||||
|
||||
SHA256Digest one = new SHA256Digest();
|
||||
for(int i = 0; i < data.length; i++){
|
||||
one.update(data[i]);
|
||||
}
|
||||
|
||||
SHA256Digest two = new SHA256Digest();
|
||||
two.update(data[0]);
|
||||
two.update(data, 1, data.length-1);
|
||||
|
||||
byte[] oneData = new byte[32];
|
||||
one.doFinal(oneData, 0);
|
||||
byte[] twoData = new byte[32];
|
||||
two.doFinal(twoData, 0);
|
||||
|
||||
assertTrue(DataHelper.eq(oneData, twoData));
|
||||
}
|
||||
|
||||
public void test14Words(){
|
||||
byte message[] = new byte[56];
|
||||
_context.random().nextBytes(message);
|
||||
SHA256Digest orig = new SHA256Digest();
|
||||
orig.update(message, 0, message.length);
|
||||
orig.doFinal(new byte[32], 0);
|
||||
}
|
||||
|
||||
public void testSHA(){
|
||||
I2PAppContext ctx = I2PAppContext.getGlobalContext();
|
||||
byte orig[] = new byte[4096];
|
||||
ctx.random().nextBytes(orig);
|
||||
Hash old = ctx.sha().calculateHash(orig);
|
||||
SHA256Digest d = new SHA256Digest();
|
||||
d.update(orig, 0, orig.length);
|
||||
byte out[] = new byte[Hash.HASH_LENGTH];
|
||||
d.doFinal(out, 0);
|
||||
assertTrue(DataHelper.eq(out, old.getData()));
|
||||
}
|
||||
|
||||
}
|
@ -13,6 +13,7 @@ import net.i2p.data.PrivateKey;
|
||||
import net.i2p.data.SessionKey;
|
||||
import net.i2p.data.SessionTag;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.DataFormatException;
|
||||
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.util.Clock;
|
||||
@ -21,72 +22,49 @@ import net.i2p.I2PAppContext;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
* session key management unit tests:
|
||||
*
|
||||
* Run tagsIncluded useTag rekey
|
||||
* // no sessions
|
||||
* 1 no no no
|
||||
* 2 no no no
|
||||
* // session
|
||||
* 3 yes (2) no no
|
||||
* 4 no yes no
|
||||
* 5 yes (2) yes no
|
||||
* 6 no yes no
|
||||
* 7 no yes no
|
||||
* // rekeying
|
||||
* 8 yes (2) no no
|
||||
* 9 no yes no
|
||||
* 10 yes (2) yes yes
|
||||
* 11 no yes no
|
||||
* 12 no yes no
|
||||
* // long session
|
||||
* 13-1000 20 tags every 10 messages, rekey every 50
|
||||
*/
|
||||
public class SessionEncryptionTest {
|
||||
private final static Log _log = new Log(SessionEncryptionTest.class);
|
||||
public class SessionEncryptionTest extends TestCase{
|
||||
private static I2PAppContext _context = new I2PAppContext();
|
||||
public static void main(String args[]) {
|
||||
SessionEncryptionTest test = new SessionEncryptionTest();
|
||||
try {
|
||||
//test.testNoSessions();
|
||||
//test.testSessions();
|
||||
//test.testRekeying();
|
||||
test.testLongSession();
|
||||
} catch (Throwable t) {
|
||||
_log.error("Error running tests", t);
|
||||
}
|
||||
try { Thread.sleep(60*1000); } catch (InterruptedException ie) {}
|
||||
|
||||
protected void setUp(){
|
||||
_context = new I2PAppContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run tagsIncluded useTag rekey
|
||||
* 1 no no no
|
||||
* 2 no no no
|
||||
*/
|
||||
public void testNoSessions() throws Exception {
|
||||
protected void tearDown() {
|
||||
System.gc();
|
||||
}
|
||||
|
||||
|
||||
public void testNoSessions1() throws Exception{
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
SessionKey curKey = _context.sessionKeyManager().createSession(pubKey);
|
||||
|
||||
byte[] msg1 = "msg 1".getBytes();
|
||||
byte[] msg2 = "msg 2".getBytes();
|
||||
byte[] msg = "msg 1".getBytes();
|
||||
|
||||
byte emsg1[] = _context.elGamalAESEngine().encrypt(msg1, pubKey, curKey, 64);
|
||||
byte dmsg1[] = _context.elGamalAESEngine().decrypt(emsg1, privKey);
|
||||
if (DataHelper.eq(dmsg1, msg1))
|
||||
_log.info("PASSED: No sessions msg 1");
|
||||
else
|
||||
_log.error("FAILED: No sessions msg 1");
|
||||
byte emsg[] = _context.elGamalAESEngine().encrypt(msg, pubKey, curKey, 64);
|
||||
byte dmsg[] = _context.elGamalAESEngine().decrypt(emsg, privKey);
|
||||
assertTrue(DataHelper.eq(dmsg, msg));
|
||||
}
|
||||
|
||||
public void testNoSessions2() throws Exception{
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
SessionKey curKey = _context.sessionKeyManager().createSession(pubKey);
|
||||
|
||||
byte emsg2[] = _context.elGamalAESEngine().encrypt(msg2, pubKey, curKey, 64);
|
||||
byte dmsg2[] = _context.elGamalAESEngine().decrypt(emsg2, privKey);
|
||||
if (DataHelper.eq(dmsg2, msg2))
|
||||
_log.info("PASSED: No sessions msg 2");
|
||||
else
|
||||
_log.error("FAILED: No sessions msg 2");
|
||||
byte[] msg = "msg 2".getBytes();
|
||||
|
||||
byte emsg[] = _context.elGamalAESEngine().encrypt(msg, pubKey, curKey, 64);
|
||||
byte dmsg[] = _context.elGamalAESEngine().decrypt(emsg, privKey);
|
||||
assertTrue(DataHelper.eq(dmsg, msg));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -97,7 +75,7 @@ public class SessionEncryptionTest {
|
||||
* 4 no yes no
|
||||
* 5 no yes no
|
||||
*/
|
||||
public void testSessions() throws Exception {
|
||||
public void testSessions() throws Exception{
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
@ -123,96 +101,66 @@ public class SessionEncryptionTest {
|
||||
byte[] msg5 = "msg 5".getBytes();
|
||||
|
||||
byte emsg1[] = _context.elGamalAESEngine().encrypt(msg1, pubKey, curKey, firstTags, 64);
|
||||
|
||||
byte dmsg1[] = _context.elGamalAESEngine().decrypt(emsg1, privKey);
|
||||
if (DataHelper.eq(dmsg1, msg1))
|
||||
_log.info("PASSED: Sessions msg 1");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 1");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg1, msg1));
|
||||
|
||||
|
||||
|
||||
_context.sessionKeyManager().tagsDelivered(pubKey, curKey, firstTags);
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
SessionTag curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 2");
|
||||
return;
|
||||
}
|
||||
|
||||
assertNotNull(curTag);
|
||||
|
||||
byte emsg2[] = _context.elGamalAESEngine().encrypt(msg2, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg2[] = _context.elGamalAESEngine().decrypt(emsg2, privKey);
|
||||
if (DataHelper.eq(dmsg2, msg2))
|
||||
_log.info("PASSED: Sessions msg 2");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 2");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg2, msg2));
|
||||
|
||||
|
||||
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 3");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 3");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg3[] = _context.elGamalAESEngine().encrypt(msg3, pubKey, curKey, secondTags, curTag, 64);
|
||||
|
||||
byte dmsg3[] = _context.elGamalAESEngine().decrypt(emsg3, privKey);
|
||||
if (DataHelper.eq(dmsg3, msg3))
|
||||
_log.info("PASSED: Sessions msg 3");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 3");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg3, msg3));
|
||||
|
||||
|
||||
|
||||
_context.sessionKeyManager().tagsDelivered(pubKey, curKey, secondTags);
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 4");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 4");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg4[] = _context.elGamalAESEngine().encrypt(msg4, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg4[] = _context.elGamalAESEngine().decrypt(emsg4, privKey);
|
||||
if (DataHelper.eq(dmsg4, msg4))
|
||||
_log.info("PASSED: Sessions msg 4");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 4");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg4, msg4));
|
||||
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 5");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 5");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg5[] = _context.elGamalAESEngine().encrypt(msg5, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg5[] = _context.elGamalAESEngine().decrypt(emsg5, privKey);
|
||||
if (DataHelper.eq(dmsg5, msg5))
|
||||
_log.info("PASSED: Sessions msg 5");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 5");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg5, msg5));
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -223,7 +171,7 @@ public class SessionEncryptionTest {
|
||||
* 4 no yes no
|
||||
* 5 no yes no
|
||||
*/
|
||||
public void testRekeying() throws Exception {
|
||||
public void testRekeying() throws Exception{
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
@ -250,119 +198,80 @@ public class SessionEncryptionTest {
|
||||
byte[] msg5 = "msg 5".getBytes();
|
||||
|
||||
byte emsg1[] = _context.elGamalAESEngine().encrypt(msg1, pubKey, curKey, firstTags, 64);
|
||||
|
||||
byte dmsg1[] = _context.elGamalAESEngine().decrypt(emsg1, privKey);
|
||||
if (DataHelper.eq(dmsg1, msg1))
|
||||
_log.info("PASSED: Sessions msg 1");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 1");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg1, msg1));
|
||||
|
||||
|
||||
|
||||
_context.sessionKeyManager().tagsDelivered(pubKey, curKey, firstTags);
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
SessionTag curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 2");
|
||||
return;
|
||||
}
|
||||
|
||||
assertNotNull(curTag);
|
||||
|
||||
byte emsg2[] = _context.elGamalAESEngine().encrypt(msg2, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg2[] = _context.elGamalAESEngine().decrypt(emsg2, privKey);
|
||||
if (DataHelper.eq(dmsg2, msg2))
|
||||
_log.info("PASSED: Sessions msg 2");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 2");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg2, msg2));
|
||||
|
||||
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 3");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 3");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg3[] = _context.elGamalAESEngine().encrypt(msg3, pubKey, curKey, secondTags, curTag, nextKey, 64);
|
||||
|
||||
byte dmsg3[] = _context.elGamalAESEngine().decrypt(emsg3, privKey);
|
||||
if (DataHelper.eq(dmsg3, msg3))
|
||||
_log.info("PASSED: Sessions msg 3");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 3");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg3, msg3));
|
||||
|
||||
|
||||
|
||||
_context.sessionKeyManager().tagsDelivered(pubKey, nextKey, secondTags); // note nextKey not curKey
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 4");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 4");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg4[] = _context.elGamalAESEngine().encrypt(msg4, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg4[] = _context.elGamalAESEngine().decrypt(emsg4, privKey);
|
||||
if (DataHelper.eq(dmsg4, msg4))
|
||||
_log.info("PASSED: Sessions msg 4");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 4");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg4, msg4));
|
||||
|
||||
|
||||
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
|
||||
|
||||
if (curTag == null) {
|
||||
_log.error("Not able to consume next tag for message 5");
|
||||
return;
|
||||
}
|
||||
if (curKey == null) {
|
||||
_log.error("Not able to consume next KEY for message 5");
|
||||
return;
|
||||
}
|
||||
assertNotNull(curTag);
|
||||
assertNotNull(curKey);
|
||||
|
||||
byte emsg5[] = _context.elGamalAESEngine().encrypt(msg5, pubKey, curKey, null, curTag, 64);
|
||||
|
||||
byte dmsg5[] = _context.elGamalAESEngine().decrypt(emsg5, privKey);
|
||||
if (DataHelper.eq(dmsg5, msg5))
|
||||
_log.info("PASSED: Sessions msg 5");
|
||||
else {
|
||||
_log.error("FAILED: Sessions msg 5");
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg5, msg5));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 20 tags every 10 messages, rekey every 50
|
||||
*/
|
||||
public void testLongSession() throws Exception {
|
||||
int num = 1000;
|
||||
long start = Clock.getInstance().now();
|
||||
testLongSession(num);
|
||||
long end = Clock.getInstance().now();
|
||||
long time = end - start;
|
||||
float msEach = (float)num / time;
|
||||
_log.error("Test long session duration: " + num + " messages in " + time + "ms (or " + msEach + "ms each)");
|
||||
}
|
||||
|
||||
public void testLongSession(int numMsgs) throws Exception {
|
||||
public void testLongSession() throws Exception{
|
||||
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
PublicKey pubKey = (PublicKey)keys[0];
|
||||
PrivateKey privKey = (PrivateKey)keys[1];
|
||||
SessionKey curKey = _context.sessionKeyManager().createSession(pubKey);
|
||||
|
||||
for (int i = 0; i < numMsgs; i++) {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Set tags = null;
|
||||
SessionKey nextKey = null;
|
||||
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
|
||||
@ -371,23 +280,16 @@ public class SessionEncryptionTest {
|
||||
int availTags = _context.sessionKeyManager().getAvailableTags(pubKey, curKey);
|
||||
if ((availTags < 1)) {
|
||||
tags = generateNewTags(50);
|
||||
_log.info("Generating new tags");
|
||||
} else {
|
||||
_log.info("Tags already available: " + availTags + " curTag: " + curTag);
|
||||
}
|
||||
}
|
||||
if (i % 50 == 0)
|
||||
nextKey = KeyGenerator.getInstance().generateSessionKey();
|
||||
|
||||
byte[] msg = ("msg " + i).getBytes();
|
||||
|
||||
byte emsg[] = _context.elGamalAESEngine().encrypt(msg, pubKey, curKey, tags, curTag, nextKey, 64);
|
||||
|
||||
byte dmsg[] = _context.elGamalAESEngine().decrypt(emsg, privKey);
|
||||
if (DataHelper.eq(dmsg, msg))
|
||||
_log.info("PASSED: Long session msg " + i);
|
||||
else {
|
||||
_log.error("FAILED: Long session msg " + i);
|
||||
return;
|
||||
}
|
||||
assertTrue(DataHelper.eq(dmsg, msg));
|
||||
|
||||
if ( (tags != null) && (tags.size() > 0) ) {
|
||||
if (nextKey == null) {
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.i2cp.AbuseReason;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class AbuseReasonTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new AbuseReasonTest(), "AbuseReason");
|
||||
}
|
||||
public class AbuseReasonTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
AbuseReason res = new AbuseReason();
|
||||
res.setReason("Because they're mean");
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.i2cp.AbuseSeverity;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class AbuseSeverityTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new AbuseSeverityTest(), "AbuseSeverity");
|
||||
}
|
||||
public class AbuseSeverityTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
AbuseSeverity sev = new AbuseSeverity();
|
||||
sev.setSeverity(64);
|
||||
|
28
core/java/test/net/i2p/data/Base64Test.java
Normal file
28
core/java/test/net/i2p/data/Base64Test.java
Normal file
@ -0,0 +1,28 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class Base64Test extends TestCase{
|
||||
public void testBase64(){
|
||||
String orig = "you smell";
|
||||
String encoded = Base64.encode(orig.getBytes());
|
||||
byte decoded[] = Base64.decode(encoded);
|
||||
String transformed = new String(decoded);
|
||||
assertTrue(orig.equals(transformed));
|
||||
|
||||
byte all[] = new byte[256];
|
||||
for (int i = 0; i < all.length; i++)
|
||||
all[i] = (byte) (0xFF & i);
|
||||
encoded = Base64.encode(all);
|
||||
decoded = Base64.decode(encoded);
|
||||
assertTrue(DataHelper.eq(decoded, all));
|
||||
}
|
||||
}
|
@ -9,6 +9,7 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@ -16,44 +17,30 @@ import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test harness for the boolean structure
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class BooleanTest implements TestDataGenerator, TestDataPrinter {
|
||||
static {
|
||||
TestData.registerGenerator(new BooleanTest(), "Boolean");
|
||||
TestData.registerPrinter(new BooleanTest(), "Boolean");
|
||||
}
|
||||
private static final Log _log = new Log(BooleanTest.class);
|
||||
public class BooleanTest extends TestCase{
|
||||
|
||||
public byte[] getData() {
|
||||
public void testBoolean() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
DataHelper.writeBoolean(baos, Boolean.TRUE);
|
||||
return baos.toByteArray();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the boolean", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the boolean", ioe);
|
||||
return null;
|
||||
}
|
||||
|
||||
DataHelper.writeBoolean(baos, Boolean.TRUE);
|
||||
temp = baos.toByteArray();
|
||||
|
||||
|
||||
Boolean b = null;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
b = DataHelper.readBoolean(bais);
|
||||
|
||||
assertEquals(Boolean.TRUE, b);
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
Boolean b = DataHelper.readBoolean(inputStream);
|
||||
return ""+b;
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the boolean", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the boolean", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -17,10 +17,7 @@ import net.i2p.data.DataStructure;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class CertificateTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new CertificateTest(), "Certificate");
|
||||
}
|
||||
public class CertificateTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Certificate cert = new Certificate();
|
||||
byte data[] = new byte[32];
|
||||
|
@ -21,15 +21,12 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class CreateLeaseSetMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new CreateLeaseSetMessageTest(), "CreateLeaseSetMessage");
|
||||
}
|
||||
public class CreateLeaseSetMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
CreateLeaseSetMessage msg = new CreateLeaseSetMessage();
|
||||
msg.setPrivateKey((PrivateKey)(new PrivateKeyTest()).createDataStructure());
|
||||
msg.setSigningPrivateKey((SigningPrivateKey)(new SigningPrivateKeyTest()).createDataStructure());
|
||||
msg.setLeaseSet((LeaseSet)(new LeaseSetTest()).createDataStructure());
|
||||
msg.setPrivateKey((PrivateKey)(new PrivateKeyTest()).createDataStructure());
|
||||
msg.setSigningPrivateKey((SigningPrivateKey)(new SigningPrivateKeyTest()).createDataStructure());
|
||||
msg.setLeaseSet((LeaseSet)(new LeaseSetTest()).createDataStructure());
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
return msg;
|
||||
}
|
||||
|
@ -18,10 +18,7 @@ import net.i2p.data.i2cp.SessionConfig;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class CreateSessionMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new CreateSessionMessageTest(), "CreateSessionMessage");
|
||||
}
|
||||
public class CreateSessionMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
CreateSessionMessage msg = new CreateSessionMessage();
|
||||
msg.setSessionConfig((SessionConfig)(new SessionConfigTest()).createDataStructure());
|
||||
|
@ -7,88 +7,60 @@ import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* basic unit tests for the DataHelper
|
||||
*
|
||||
*/
|
||||
public class DataHelperTest {
|
||||
public class DataHelperTest extends TestCase{
|
||||
private I2PAppContext _context;
|
||||
private Log _log;
|
||||
|
||||
public DataHelperTest(I2PAppContext ctx) {
|
||||
_context = ctx;
|
||||
_log = ctx.logManager().getLog(DataHelperTest.class);
|
||||
}
|
||||
|
||||
public void runTests() {
|
||||
// compress
|
||||
testCompress();
|
||||
// long (read/write/to/from)
|
||||
testLong();
|
||||
// date (read/write/to/from)
|
||||
testDate();
|
||||
// string
|
||||
// properties
|
||||
// boolean
|
||||
// readline
|
||||
protected void setUp() {
|
||||
_context = I2PAppContext.getGlobalContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to/from/read/writeLong with every 1, 2, and 4 byte value, as
|
||||
* well as some 8 byte values.
|
||||
*/
|
||||
public void testLong() {
|
||||
for (int i = 0; i <= 0xFF; i++)
|
||||
testLong(1, i);
|
||||
System.out.println("Test 1byte passed");
|
||||
for (long i = 0; i <= 0xFFFF; i++)
|
||||
testLong(2, i);
|
||||
System.out.println("Test 2byte passed");
|
||||
for (long i = 0; i <= 0xFFFFFF; i ++)
|
||||
testLong(3, i);
|
||||
System.out.println("Test 3byte passed");
|
||||
for (long i = 0; i <= 0xFFFFFFFF; i++)
|
||||
testLong(4, i);
|
||||
System.out.println("Test 4byte passed");
|
||||
public void testLong() throws Exception{
|
||||
for (int i = 0; i <= 0xFF; i+=4)
|
||||
checkLong(1, i);
|
||||
for (long i = 0; i <= 0xFFFF; i+=16)
|
||||
checkLong(2, i);
|
||||
for (long i = 0; i <= 0xFFFFFF; i +=128)
|
||||
checkLong(3, i);
|
||||
for (long i = 0; i <= 0xFFFFFFFFl; i+=512)
|
||||
checkLong(4, i);
|
||||
// i know, doesnt test (2^63)-(2^64-1)
|
||||
for (long i = Long.MAX_VALUE - 0xFFFFFFl; i < Long.MAX_VALUE; i++)
|
||||
testLong(8, i);
|
||||
System.out.println("Test 8byte passed");
|
||||
checkLong(8, i);
|
||||
}
|
||||
private static void testLong(int numBytes, long value) {
|
||||
try {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(numBytes);
|
||||
DataHelper.writeLong(baos, numBytes, value);
|
||||
byte written[] = baos.toByteArray();
|
||||
byte extract[] = DataHelper.toLong(numBytes, value);
|
||||
if (extract.length != numBytes)
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED (len="+extract.length+")");
|
||||
if (!DataHelper.eq(written, extract))
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED");
|
||||
byte extract2[] = new byte[numBytes];
|
||||
DataHelper.toLong(extract2, 0, numBytes, value);
|
||||
if (!DataHelper.eq(extract, extract2))
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED on toLong");
|
||||
|
||||
long read = DataHelper.fromLong(extract, 0, numBytes);
|
||||
if (read != value)
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED on read (" + read + ")");
|
||||
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(written);
|
||||
read = DataHelper.readLong(bais, numBytes);
|
||||
if (read != value)
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED on readLong (" + read + ")");
|
||||
read = DataHelper.fromLong(written, 0, numBytes);
|
||||
if (read != value)
|
||||
throw new RuntimeException("testLong("+numBytes+","+value+") FAILED on fromLong (" + read + ")");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("test(" + numBytes +","+ value +"): " + e.getMessage());
|
||||
}
|
||||
private static void checkLong(int numBytes, long value) throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(numBytes);
|
||||
DataHelper.writeLong(baos, numBytes, value);
|
||||
byte written[] = baos.toByteArray();
|
||||
byte extract[] = DataHelper.toLong(numBytes, value);
|
||||
assertTrue(extract.length == numBytes);
|
||||
assertTrue(DataHelper.eq(written, extract));
|
||||
byte extract2[] = new byte[numBytes];
|
||||
DataHelper.toLong(extract2, 0, numBytes, value);
|
||||
assertTrue(DataHelper.eq(extract, extract2));
|
||||
|
||||
long read = DataHelper.fromLong(extract, 0, numBytes);
|
||||
assertTrue(read == value);
|
||||
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(written);
|
||||
read = DataHelper.readLong(bais, numBytes);
|
||||
assertTrue(read == value);
|
||||
read = DataHelper.fromLong(written, 0, numBytes);
|
||||
assertTrue(read == value);
|
||||
|
||||
}
|
||||
|
||||
private void testDate() {
|
||||
public void testDate() throws Exception{
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
cal.set(Calendar.YEAR, 1970);
|
||||
@ -97,10 +69,10 @@ public class DataHelperTest {
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
cal.set(Calendar.SECOND, 1);
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
cal.set(Calendar.YEAR, 1999);
|
||||
cal.set(Calendar.MONTH, 11);
|
||||
@ -108,7 +80,7 @@ public class DataHelperTest {
|
||||
cal.set(Calendar.HOUR_OF_DAY, 23);
|
||||
cal.set(Calendar.MINUTE, 59);
|
||||
cal.set(Calendar.SECOND, 59);
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
cal.set(Calendar.YEAR, 2000);
|
||||
cal.set(Calendar.MONTH, 0);
|
||||
@ -116,68 +88,47 @@ public class DataHelperTest {
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
cal.setTimeInMillis(System.currentTimeMillis());
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+10);
|
||||
testDate(cal.getTime());
|
||||
checkDate(cal.getTime());
|
||||
|
||||
try {
|
||||
cal.set(Calendar.YEAR, 1969);
|
||||
cal.set(Calendar.MONTH, 11);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 31);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 23);
|
||||
cal.set(Calendar.MINUTE, 59);
|
||||
cal.set(Calendar.SECOND, 59);
|
||||
testDate(cal.getTime());
|
||||
System.err.println("foo! this should fail");
|
||||
} catch (RuntimeException re) {
|
||||
// should fail on dates prior to the epoch
|
||||
cal.set(Calendar.YEAR, 1969);
|
||||
cal.set(Calendar.MONTH, 11);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 31);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 23);
|
||||
cal.set(Calendar.MINUTE, 59);
|
||||
cal.set(Calendar.SECOND, 59);
|
||||
boolean error = false;
|
||||
try{
|
||||
checkDate(cal.getTime());
|
||||
}catch(Exception e){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
private void testDate(Date when) {
|
||||
try {
|
||||
byte buf[] = new byte[DataHelper.DATE_LENGTH];
|
||||
DataHelper.toDate(buf, 0, when.getTime());
|
||||
byte tbuf[] = DataHelper.toDate(when);
|
||||
if (!DataHelper.eq(tbuf, buf))
|
||||
throw new RuntimeException("testDate("+when.toString()+") failed on toDate");
|
||||
Date time = DataHelper.fromDate(buf, 0);
|
||||
if (when.getTime() != time.getTime())
|
||||
throw new RuntimeException("testDate("+when.toString()+") failed (" + time.toString() + ")");
|
||||
System.out.println("eq: " + time);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
private void checkDate(Date when) throws Exception{
|
||||
byte buf[] = new byte[DataHelper.DATE_LENGTH];
|
||||
DataHelper.toDate(buf, 0, when.getTime());
|
||||
byte tbuf[] = DataHelper.toDate(when);
|
||||
assertTrue(DataHelper.eq(tbuf, buf));
|
||||
Date time = DataHelper.fromDate(buf, 0);
|
||||
assertEquals(when.getTime(), time.getTime());
|
||||
}
|
||||
|
||||
private void testCompress() {
|
||||
for (int i = 0; i < 32*1024; i++)
|
||||
testCompress(i);
|
||||
}
|
||||
|
||||
private void testCompress(int size) {
|
||||
byte data[] = new byte[size];
|
||||
_context.random().nextBytes(data);
|
||||
byte compressed[] = DataHelper.compress(data);
|
||||
try {
|
||||
public void testCompress() throws Exception{
|
||||
for (int size = 0; size < 32*1024; size+=32){ // Original had size++, changed value because
|
||||
// speed was a problem. -Comwiz
|
||||
byte data[] = new byte[size];
|
||||
_context.random().nextBytes(data);
|
||||
byte compressed[] = DataHelper.compress(data);
|
||||
byte decompressed[] = DataHelper.decompress(compressed);
|
||||
boolean ok = DataHelper.eq(data, decompressed);
|
||||
if (!ok)
|
||||
throw new RuntimeException("failed match at size=" + size);
|
||||
else
|
||||
System.out.println("Match at size=" + size);
|
||||
} catch (java.io.IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
throw new RuntimeException("Error at size=" + size +":" + ioe.getMessage());
|
||||
assertTrue(DataHelper.eq(data, decompressed));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
DataHelperTest test = new DataHelperTest(I2PAppContext.getGlobalContext());
|
||||
test.runTests();
|
||||
}
|
||||
}
|
||||
|
76
core/java/test/net/i2p/data/DataStructureImplTest.java
Normal file
76
core/java/test/net/i2p/data/DataStructureImplTest.java
Normal file
@ -0,0 +1,76 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
import net.i2p.data.DataStructureImpl;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class DataStructureImplTest extends TestCase{
|
||||
DataStructure _struct;
|
||||
|
||||
protected void setUp(){
|
||||
_struct = new DataStructureImpl(){
|
||||
private int x = 0;
|
||||
public void writeBytes(OutputStream out) throws IOException, DataFormatException{
|
||||
if(x++==0)
|
||||
throw new DataFormatException("let it enfold you", new Exception());
|
||||
else
|
||||
throw new IOException();
|
||||
}
|
||||
public void readBytes(InputStream in) throws IOException{
|
||||
throw new IOException();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void testNulls() throws Exception{
|
||||
assertNull(_struct.toBase64());
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
_struct.fromBase64(null);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
|
||||
assertNull(_struct.calculateHash());
|
||||
|
||||
error = false;
|
||||
try{
|
||||
_struct.fromByteArray(null);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testErrors() throws Exception{
|
||||
boolean error = false;
|
||||
try{
|
||||
_struct.fromByteArray("water is poison".getBytes());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
|
||||
assertNull(_struct.toByteArray());
|
||||
assertNull(_struct.toByteArray());
|
||||
}
|
||||
}
|
56
core/java/test/net/i2p/data/DataTestSuite.java
Normal file
56
core/java/test/net/i2p/data/DataTestSuite.java
Normal file
@ -0,0 +1,56 @@
|
||||
package net.i2p.data;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
public class DataTestSuite {
|
||||
|
||||
public static Test suite() {
|
||||
|
||||
TestSuite suite = new TestSuite("net.i2p.data.DataTestSuite");
|
||||
|
||||
suite.addTestSuite(AbuseReasonTest.class);
|
||||
suite.addTestSuite(AbuseSeverityTest.class);
|
||||
suite.addTestSuite(Base64Test.class);
|
||||
suite.addTestSuite(BooleanTest.class);
|
||||
suite.addTestSuite(CertificateTest.class);
|
||||
suite.addTestSuite(CreateLeaseSetMessageTest.class);
|
||||
suite.addTestSuite(CreateSessionMessageTest.class);
|
||||
suite.addTestSuite(DataHelperTest.class);
|
||||
suite.addTestSuite(DataStructureImplTest.class);
|
||||
suite.addTestSuite(DateTest.class);
|
||||
suite.addTestSuite(DestinationTest.class);
|
||||
suite.addTestSuite(DestroySessionMessageTest.class);
|
||||
suite.addTestSuite(DisconnectMessageTest.class);
|
||||
suite.addTestSuite(HashTest.class);
|
||||
suite.addTestSuite(LeaseSetTest.class);
|
||||
suite.addTestSuite(LeaseTest.class);
|
||||
suite.addTestSuite(MappingTest.class);
|
||||
suite.addTestSuite(MessageIdTest.class);
|
||||
suite.addTestSuite(MessagePayloadMessageTest.class);
|
||||
suite.addTestSuite(MessageStatusMessageTest.class);
|
||||
suite.addTestSuite(PayloadTest.class);
|
||||
suite.addTestSuite(PrivateKeyTest.class);
|
||||
suite.addTestSuite(PublicKeyTest.class);
|
||||
suite.addTestSuite(ReceiveMessageBeginMessageTest.class);
|
||||
suite.addTestSuite(ReceiveMessageEndMessageTest.class);
|
||||
suite.addTestSuite(ReportAbuseMessageTest.class);
|
||||
suite.addTestSuite(RequestLeaseSetMessageTest.class);
|
||||
suite.addTestSuite(RouterAddressTest.class);
|
||||
suite.addTestSuite(RouterIdentityTest.class);
|
||||
suite.addTestSuite(RouterInfoTest.class);
|
||||
suite.addTestSuite(SendMessageMessageTest.class);
|
||||
suite.addTestSuite(SessionConfigTest.class);
|
||||
suite.addTestSuite(SessionIdTest.class);
|
||||
suite.addTestSuite(SessionKeyTest.class);
|
||||
suite.addTestSuite(SessionStatusMessageTest.class);
|
||||
suite.addTestSuite(SignatureTest.class);
|
||||
suite.addTestSuite(SigningPrivateKeyTest.class);
|
||||
suite.addTestSuite(SigningPublicKeyTest.class);
|
||||
suite.addTestSuite(StringTest.class);
|
||||
suite.addTestSuite(TunnelIdTest.class);
|
||||
suite.addTestSuite(UnsignedIntegerTest.class);
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
@ -9,6 +9,7 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
@ -17,44 +18,31 @@ import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test harness for the boolean structure
|
||||
* Test harness for the date structure
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class DateTest implements TestDataGenerator, TestDataPrinter {
|
||||
static {
|
||||
TestData.registerGenerator(new DateTest(), "Date");
|
||||
TestData.registerPrinter(new DateTest(), "Date");
|
||||
}
|
||||
private static final Log _log = new Log(DateTest.class);
|
||||
public class DateTest extends TestCase{
|
||||
|
||||
public byte[] getData() {
|
||||
public void testDate() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
Date orig = new Date();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
DataHelper.writeDate(baos, new Date());
|
||||
return baos.toByteArray();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the date", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the date", ioe);
|
||||
return null;
|
||||
}
|
||||
|
||||
DataHelper.writeDate(baos, orig);
|
||||
temp = baos.toByteArray();
|
||||
|
||||
|
||||
Date d = null;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
d = DataHelper.readDate(bais);
|
||||
|
||||
assertEquals(orig, d);
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
Date d = DataHelper.readDate(inputStream);
|
||||
return ""+d;
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the date", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the date", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -20,10 +20,7 @@ import net.i2p.data.SigningPublicKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class DestinationTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new DestinationTest(), "Destination");
|
||||
}
|
||||
public class DestinationTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Destination dest = new Destination();
|
||||
StructureTest tst = new CertificateTest();
|
||||
|
@ -18,10 +18,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class DestroySessionMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new DestroySessionMessageTest(), "DestroySessionMessage");
|
||||
}
|
||||
public class DestroySessionMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
DestroySessionMessage msg = new DestroySessionMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.i2cp.DisconnectMessage;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class DisconnectMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new DisconnectMessageTest(), "DisconnectMessage");
|
||||
}
|
||||
public class DisconnectMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
DisconnectMessage msg = new DisconnectMessage();
|
||||
msg.setReason("Because I say so");
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.Hash;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class HashTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new HashTest(), "Hash");
|
||||
}
|
||||
public class HashTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Hash hash = new Hash();
|
||||
byte data[] = new byte[32];
|
||||
|
@ -21,10 +21,7 @@ import net.i2p.data.SigningPublicKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class LeaseSetTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new LeaseSetTest(), "LeaseSet");
|
||||
}
|
||||
public class LeaseSetTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
LeaseSet leaseSet = new LeaseSet();
|
||||
leaseSet.setDestination((Destination)(new DestinationTest()).createDataStructure());
|
||||
|
@ -9,6 +9,7 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.util.Date;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
@ -21,14 +22,10 @@ import net.i2p.data.TunnelId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class LeaseTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new LeaseTest(), "Lease");
|
||||
}
|
||||
public class LeaseTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Lease lease = new Lease();
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
//lease.setStartDate(new Date(1000*60));
|
||||
byte h[] = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(new Hash(h));
|
||||
StructureTest tst = new TunnelIdTest();
|
||||
@ -37,4 +34,68 @@ class LeaseTest extends StructureTest {
|
||||
return lease;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new Lease(); }
|
||||
|
||||
public void testNumSuccessFail() throws Exception{
|
||||
Lease lease = new Lease();
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
byte h[] = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(new Hash(h));
|
||||
StructureTest tst = new TunnelIdTest();
|
||||
lease.setTunnelId((TunnelId)tst.createDataStructure());
|
||||
|
||||
lease.getNumSuccess();
|
||||
lease.getNumFailure();
|
||||
}
|
||||
|
||||
public void testExpiration() throws Exception{
|
||||
Lease lease = new Lease();
|
||||
assertTrue(lease.isExpired());
|
||||
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
byte h[] = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(new Hash(h));
|
||||
StructureTest tst = new TunnelIdTest();
|
||||
lease.setTunnelId((TunnelId)tst.createDataStructure());
|
||||
|
||||
assertTrue(lease.isExpired());
|
||||
}
|
||||
|
||||
public void testNullWrite() throws Exception{
|
||||
Lease lease = new Lease();
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
byte h[] = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(new Hash(h));
|
||||
lease.setTunnelId(null);
|
||||
boolean error = false;
|
||||
try{
|
||||
lease.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
|
||||
lease = new Lease();
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
h = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(null);
|
||||
StructureTest tst = new TunnelIdTest();
|
||||
lease.setTunnelId((TunnelId)tst.createDataStructure());
|
||||
error = false;
|
||||
try{
|
||||
lease.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testNullEquals() throws Exception{
|
||||
Lease lease = new Lease();
|
||||
lease.setEndDate(new Date(1000*60*2));
|
||||
byte h[] = new byte[Hash.HASH_LENGTH];
|
||||
lease.setGateway(new Hash(h));
|
||||
lease.setTunnelId(null);
|
||||
assertFalse(lease.equals(null));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,56 +9,42 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test harness for the mapping structure (in java, a Properties map)
|
||||
* Test harness for the date structure
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class MappingTest implements TestDataGenerator, TestDataPrinter {
|
||||
static {
|
||||
TestData.registerGenerator(new MappingTest(), "Mapping");
|
||||
TestData.registerPrinter(new MappingTest(), "Mapping");
|
||||
}
|
||||
private static final Log _log = new Log(MappingTest.class);
|
||||
public class MappingTest extends TestCase{
|
||||
|
||||
public byte[] getData() {
|
||||
public void testProperties() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
Properties orig = new Properties();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
Properties options = new Properties();
|
||||
options.setProperty("key1", "val1");
|
||||
options.setProperty("key2", "val2");
|
||||
options.setProperty("key3", "val3");
|
||||
try {
|
||||
DataHelper.writeProperties(baos, options);
|
||||
return baos.toByteArray();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the mapping", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the mapping", ioe);
|
||||
return null;
|
||||
}
|
||||
orig.setProperty("key1", "val1");
|
||||
orig.setProperty("key2", "val2");
|
||||
orig.setProperty("key3", "val3");
|
||||
|
||||
DataHelper.writeProperties(baos, orig);
|
||||
temp = baos.toByteArray();
|
||||
|
||||
|
||||
Properties p = null;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
p = DataHelper.readProperties(bais);
|
||||
|
||||
assertEquals(orig, p);
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
Properties options = DataHelper.readProperties(inputStream);
|
||||
return DataHelper.toString(options);
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the mapping", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the mapping", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -17,10 +17,7 @@ import net.i2p.data.i2cp.MessageId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class MessageIdTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new MessageIdTest(), "MessageId");
|
||||
}
|
||||
public class MessageIdTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
MessageId id = new MessageId();
|
||||
id.setMessageId(101);
|
||||
|
@ -10,6 +10,8 @@ package net.i2p.data;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
@ -24,12 +26,8 @@ import net.i2p.util.Log;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class MessagePayloadMessageTest extends StructureTest {
|
||||
private final static Log _log = new Log(MessagePayloadMessage.class);
|
||||
|
||||
static {
|
||||
TestData.registerTest(new MessagePayloadMessageTest(), "MessagePayloadMessage");
|
||||
}
|
||||
|
||||
public class MessagePayloadMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
MessagePayloadMessage msg = new MessagePayloadMessage();
|
||||
msg.setMessageId((MessageId)(new MessageIdTest()).createDataStructure());
|
||||
@ -37,20 +35,25 @@ class MessagePayloadMessageTest extends StructureTest {
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
return msg;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new MessagePayloadMessage(); }
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
DataStructure structure = createStructureToRead();
|
||||
structure.readBytes(inputStream);
|
||||
((MessagePayloadMessage)structure).getPayload().setUnencryptedData(((MessagePayloadMessage)structure).getPayload().getEncryptedData());
|
||||
return structure.toString();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the data structure", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the data structure", ioe);
|
||||
return null;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new MessagePayloadMessage(); }
|
||||
|
||||
public void testStructure() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
DataStructure orig;
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
orig = createDataStructure();
|
||||
orig.writeBytes(baos);
|
||||
|
||||
temp = baos.toByteArray();
|
||||
|
||||
DataStructure ds;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
ds = createStructureToRead();
|
||||
ds.readBytes(bais);
|
||||
((MessagePayloadMessage)ds).getPayload().setUnencryptedData(((MessagePayloadMessage)ds).getPayload().getEncryptedData());
|
||||
|
||||
assertEquals(orig, ds);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -19,16 +19,14 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class MessageStatusMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new MessageStatusMessageTest(), "MessageStatusMessage");
|
||||
}
|
||||
public class MessageStatusMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
MessageStatusMessage msg = new MessageStatusMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
msg.setMessageId((MessageId)(new MessageIdTest()).createDataStructure());
|
||||
msg.setSize(1024*1024*42L);
|
||||
msg.setStatus(MessageStatusMessage.STATUS_AVAILABLE);
|
||||
msg.setNonce(1);
|
||||
return msg;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new MessageStatusMessage(); }
|
||||
|
@ -10,6 +10,8 @@ package net.i2p.data;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
@ -24,42 +26,45 @@ import net.i2p.util.Log;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class PayloadTest extends StructureTest {
|
||||
private final static Log _log = new Log(PayloadTest.class);
|
||||
|
||||
static {
|
||||
TestData.registerTest(new PayloadTest(), "Payload");
|
||||
}
|
||||
|
||||
public class PayloadTest extends StructureTest{
|
||||
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Payload payload = new Payload();
|
||||
SessionKey key = (SessionKey)(new SessionKeyTest()).createDataStructure();
|
||||
//payload.setEncryptionKey(key);
|
||||
|
||||
byte data[] = "Hello, I2P".getBytes();
|
||||
payload.setUnencryptedData(data);
|
||||
Hash hash = (Hash)(new HashTest()).createDataStructure();
|
||||
//payload.setHash(hash);
|
||||
|
||||
Destination target = (Destination)(new DestinationTest()).createDataStructure();
|
||||
payload.setEncryptedData(data);
|
||||
//payload.encryptPayload(target, 128);
|
||||
payload.setEncryptedData(data);
|
||||
|
||||
return payload;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new Payload(); }
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
DataStructure structure = createStructureToRead();
|
||||
structure.readBytes(inputStream);
|
||||
Payload payload = (Payload)structure;
|
||||
payload.setUnencryptedData(payload.getEncryptedData());
|
||||
//((Payload)structure).decryptPayload((PrivateKey)(new PrivateKeyTest()).createDataStructure());
|
||||
return structure.toString();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the data structure", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the data structure", ioe);
|
||||
return null;
|
||||
}
|
||||
public void testStructure() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
DataStructure orig;
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
orig = createDataStructure();
|
||||
orig.writeBytes(baos);
|
||||
|
||||
|
||||
temp = baos.toByteArray();
|
||||
|
||||
DataStructure ds;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
ds = createStructureToRead();
|
||||
ds.readBytes(bais);
|
||||
Payload payload = (Payload)ds;
|
||||
payload.setUnencryptedData(payload.getEncryptedData());
|
||||
|
||||
assertEquals(orig, ds);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,13 +1,17 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* Written by jrandom in 2003 and released into the Private domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
import net.i2p.data.PrivateKey;
|
||||
@ -17,10 +21,7 @@ import net.i2p.data.PrivateKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class PrivateKeyTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new PrivateKeyTest(), "PrivateKey");
|
||||
}
|
||||
public class PrivateKeyTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
byte data[] = new byte[PrivateKey.KEYSIZE_BYTES];
|
||||
@ -30,4 +31,67 @@ class PrivateKeyTest extends StructureTest {
|
||||
return privateKey;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new PrivateKey(); }
|
||||
|
||||
public void testBase64Constructor() throws Exception{
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
byte data[] = new byte[PrivateKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
privateKey.setData(data);
|
||||
|
||||
PrivateKey key2 = new PrivateKey(privateKey.toBase64());
|
||||
assertEquals(privateKey, key2);
|
||||
}
|
||||
|
||||
public void testNullEquals(){
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
byte data[] = new byte[PrivateKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
privateKey.setData(data);
|
||||
|
||||
assertFalse(privateKey.equals(null));
|
||||
}
|
||||
|
||||
public void testNullData() throws Exception{
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
privateKey.toString();
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
privateKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortData() throws Exception{
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
byte data[] = new byte[56];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i);
|
||||
privateKey.setData(data);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
privateKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortRead() throws Exception{
|
||||
PrivateKey privateKey = new PrivateKey();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream("six times nine equals forty-two".getBytes());
|
||||
boolean error = false;
|
||||
try{
|
||||
privateKey.readBytes(in);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,6 +8,9 @@ package net.i2p.data;
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
import net.i2p.data.PublicKey;
|
||||
@ -17,10 +20,7 @@ import net.i2p.data.PublicKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class PublicKeyTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new PublicKeyTest(), "PublicKey");
|
||||
}
|
||||
public class PublicKeyTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
PublicKey publicKey = new PublicKey();
|
||||
byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
|
||||
@ -30,4 +30,66 @@ class PublicKeyTest extends StructureTest {
|
||||
return publicKey;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new PublicKey(); }
|
||||
|
||||
public void testBase64Constructor() throws Exception{
|
||||
PublicKey publicKey = new PublicKey();
|
||||
byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
publicKey.setData(data);
|
||||
|
||||
PublicKey key2 = new PublicKey(publicKey.toBase64());
|
||||
assertEquals(publicKey, key2);
|
||||
}
|
||||
|
||||
public void testNullEquals(){
|
||||
PublicKey publicKey = new PublicKey();
|
||||
byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
publicKey.setData(data);
|
||||
|
||||
assertFalse(publicKey.equals(null));
|
||||
}
|
||||
|
||||
public void testNullData() throws Exception{
|
||||
PublicKey publicKey = new PublicKey();
|
||||
publicKey.toString();
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortData() throws Exception{
|
||||
PublicKey publicKey = new PublicKey();
|
||||
byte data[] = new byte[56];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i);
|
||||
publicKey.setData(data);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortRead() throws Exception{
|
||||
PublicKey publicKey = new PublicKey();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream("six times nine equals forty-two".getBytes());
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.readBytes(in);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
}
|
||||
|
@ -19,10 +19,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class ReceiveMessageBeginMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new ReceiveMessageBeginMessageTest(), "ReceiveMessageBeginMessage");
|
||||
}
|
||||
public class ReceiveMessageBeginMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
ReceiveMessageBeginMessage msg = new ReceiveMessageBeginMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
|
@ -19,10 +19,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class ReceiveMessageEndMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new ReceiveMessageEndMessageTest(), "ReceiveMessageEndMessage");
|
||||
}
|
||||
public class ReceiveMessageEndMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
ReceiveMessageEndMessage msg = new ReceiveMessageEndMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
|
@ -21,10 +21,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class ReportAbuseMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new ReportAbuseMessageTest(), "ReportAbuseMessage");
|
||||
}
|
||||
public class ReportAbuseMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
ReportAbuseMessage msg = new ReportAbuseMessage();
|
||||
msg.setMessageId((MessageId)(new MessageIdTest()).createDataStructure());
|
||||
|
@ -22,10 +22,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class RequestLeaseSetMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new RequestLeaseSetMessageTest(), "RequestLeaseSetMessage");
|
||||
}
|
||||
public class RequestLeaseSetMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
RequestLeaseSetMessage msg = new RequestLeaseSetMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
|
@ -7,7 +7,8 @@ package net.i2p.data;
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Date;
|
||||
import java.util.Properties;
|
||||
|
||||
@ -20,10 +21,7 @@ import net.i2p.data.RouterAddress;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class RouterAddressTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new RouterAddressTest(), "RouterAddress");
|
||||
}
|
||||
public class RouterAddressTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
RouterAddress addr = new RouterAddress();
|
||||
byte data[] = new byte[32];
|
||||
@ -39,4 +37,45 @@ class RouterAddressTest extends StructureTest {
|
||||
return addr;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new RouterAddress(); }
|
||||
|
||||
public void testBadWrite() throws Exception{
|
||||
RouterAddress addr = new RouterAddress();
|
||||
boolean error = true;
|
||||
try{
|
||||
addr.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testNullEquals(){
|
||||
RouterAddress addr = new RouterAddress();
|
||||
byte data[] = new byte[32];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%16);
|
||||
addr.setCost(42);
|
||||
addr.setExpiration(new Date(1000*60*60*24)); // jan 2 1970
|
||||
Properties options = new Properties();
|
||||
options.setProperty("hostname", "localhost");
|
||||
options.setProperty("portnum", "1234");
|
||||
addr.setOptions(options);
|
||||
addr.setTransportStyle("Blah");
|
||||
assertFalse(addr.equals(null));
|
||||
}
|
||||
|
||||
public void testToString(){
|
||||
RouterAddress addr = new RouterAddress();
|
||||
byte data[] = new byte[32];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%16);
|
||||
addr.setCost(42);
|
||||
addr.setExpiration(new Date(1000*60*60*24)); // jan 2 1970
|
||||
Properties options = new Properties();
|
||||
options.setProperty("hostname", "localhost");
|
||||
options.setProperty("portnum", "1234");
|
||||
addr.setOptions(options);
|
||||
addr.setTransportStyle("Blah");
|
||||
addr.toString();
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,8 @@ package net.i2p.data;
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import net.i2p.data.Certificate;
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
@ -20,10 +22,7 @@ import net.i2p.data.SigningPublicKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class RouterIdentityTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new RouterIdentityTest(), "RouterIdentity");
|
||||
}
|
||||
public class RouterIdentityTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
Certificate cert = (Certificate)(new CertificateTest()).createDataStructure();
|
||||
@ -35,4 +34,84 @@ class RouterIdentityTest extends StructureTest {
|
||||
return ident;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new RouterIdentity(); }
|
||||
|
||||
public void testNullCert() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
ident.setCertificate(null);
|
||||
PublicKey pk = (PublicKey)(new PublicKeyTest()).createDataStructure();
|
||||
ident.setPublicKey(pk);
|
||||
SigningPublicKey k = (SigningPublicKey)(new SigningPublicKeyTest()).createDataStructure();
|
||||
ident.setSigningPublicKey(k);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
ident.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testNullPublicKey() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
Certificate cert = (Certificate)(new CertificateTest()).createDataStructure();
|
||||
ident.setCertificate(cert);
|
||||
ident.setPublicKey(null);
|
||||
SigningPublicKey k = (SigningPublicKey)(new SigningPublicKeyTest()).createDataStructure();
|
||||
ident.setSigningPublicKey(k);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
ident.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
|
||||
}
|
||||
|
||||
public void testNullSigningKey() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
Certificate cert = (Certificate)(new CertificateTest()).createDataStructure();
|
||||
ident.setCertificate(cert);
|
||||
PublicKey pk = (PublicKey)(new PublicKeyTest()).createDataStructure();
|
||||
ident.setPublicKey(pk);
|
||||
ident.setSigningPublicKey(null);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
ident.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testNullEquals() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
assertFalse(ident.equals(null));
|
||||
}
|
||||
|
||||
public void testCalculatedHash() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
Certificate cert = (Certificate)(new CertificateTest()).createDataStructure();
|
||||
ident.setCertificate(cert);
|
||||
PublicKey pk = (PublicKey)(new PublicKeyTest()).createDataStructure();
|
||||
ident.setPublicKey(pk);
|
||||
SigningPublicKey k = (SigningPublicKey)(new SigningPublicKeyTest()).createDataStructure();
|
||||
ident.setSigningPublicKey(k);
|
||||
|
||||
ident.calculateHash();
|
||||
ident.calculateHash();
|
||||
ident.calculateHash();
|
||||
ident.calculateHash();
|
||||
ident.calculateHash();
|
||||
}
|
||||
|
||||
public void testBadHash() throws Exception{
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
ident.getHash();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -30,9 +30,6 @@ import net.i2p.util.Log;
|
||||
*/
|
||||
public class RouterInfoTest extends StructureTest {
|
||||
private final static Log _log = new Log(RouterInfoTest.class);
|
||||
static {
|
||||
TestData.registerTest(new RouterInfoTest(), "RouterInfo");
|
||||
}
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
RouterInfo info = new RouterInfo();
|
||||
HashSet addresses = new HashSet();
|
||||
@ -40,32 +37,32 @@ public class RouterInfoTest extends StructureTest {
|
||||
addresses.add(structure);
|
||||
info.setAddresses(addresses);
|
||||
|
||||
PublicKey pubKey = null;
|
||||
SigningPublicKey signingPubKey = null;
|
||||
PrivateKey privKey = null;
|
||||
SigningPrivateKey signingPrivKey = null;
|
||||
|
||||
Object obj[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
pubKey = (PublicKey)obj[0];
|
||||
privKey = (PrivateKey)obj[1];
|
||||
obj = KeyGenerator.getInstance().generateSigningKeypair();
|
||||
signingPubKey = (SigningPublicKey)obj[0];
|
||||
signingPrivKey = (SigningPrivateKey)obj[1];
|
||||
|
||||
_log.debug("SigningPublicKey: " + signingPubKey);
|
||||
_log.debug("SigningPrivateKey: " + signingPrivKey);
|
||||
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
ident.setCertificate(new Certificate(Certificate.CERTIFICATE_TYPE_NULL, null));
|
||||
ident.setPublicKey(pubKey);
|
||||
ident.setSigningPublicKey(signingPubKey);
|
||||
|
||||
PublicKey pubKey = null;
|
||||
SigningPublicKey signingPubKey = null;
|
||||
PrivateKey privKey = null;
|
||||
SigningPrivateKey signingPrivKey = null;
|
||||
|
||||
Object obj[] = KeyGenerator.getInstance().generatePKIKeypair();
|
||||
pubKey = (PublicKey)obj[0];
|
||||
privKey = (PrivateKey)obj[1];
|
||||
obj = KeyGenerator.getInstance().generateSigningKeypair();
|
||||
signingPubKey = (SigningPublicKey)obj[0];
|
||||
signingPrivKey = (SigningPrivateKey)obj[1];
|
||||
|
||||
_log.debug("SigningPublicKey: " + signingPubKey);
|
||||
_log.debug("SigningPrivateKey: " + signingPrivKey);
|
||||
|
||||
RouterIdentity ident = new RouterIdentity();
|
||||
ident.setCertificate(new Certificate(Certificate.CERTIFICATE_TYPE_NULL, null));
|
||||
ident.setPublicKey(pubKey);
|
||||
ident.setSigningPublicKey(signingPubKey);
|
||||
|
||||
info.setIdentity(ident);
|
||||
|
||||
Properties options = new Properties();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
options.setProperty("option." + i, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890$:." + i);
|
||||
}
|
||||
for (int i = 0; i < 16; i++) {
|
||||
options.setProperty("option." + i, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890$:." + i);
|
||||
}
|
||||
options.setProperty("netConnectionSpeed", "OC12");
|
||||
info.setOptions(options);
|
||||
|
||||
@ -73,12 +70,12 @@ public class RouterInfoTest extends StructureTest {
|
||||
structure = (new HashTest()).createDataStructure();
|
||||
peers.add(structure);
|
||||
info.setPeers(peers);
|
||||
info.setPublished(System.currentTimeMillis());
|
||||
|
||||
//info.setVersion(69);
|
||||
|
||||
info.sign(signingPrivKey);
|
||||
|
||||
info.setPublished(System.currentTimeMillis());
|
||||
|
||||
//info.setVersion(69);
|
||||
|
||||
info.sign(signingPrivKey);
|
||||
|
||||
return info;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new RouterInfo(); }
|
||||
|
@ -10,6 +10,8 @@ package net.i2p.data;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
@ -24,33 +26,39 @@ import net.i2p.util.Log;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SendMessageMessageTest extends StructureTest {
|
||||
private final static Log _log = new Log(SendMessageMessageTest.class);
|
||||
|
||||
static {
|
||||
TestData.registerTest(new SendMessageMessageTest(), "SendMessageMessage");
|
||||
}
|
||||
|
||||
public class SendMessageMessageTest extends StructureTest {
|
||||
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SendMessageMessage msg = new SendMessageMessage();
|
||||
msg.setDestination((Destination)(new DestinationTest()).createDataStructure());
|
||||
msg.setPayload((Payload)(new PayloadTest()).createDataStructure());
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
msg.setNonce(1);
|
||||
return msg;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new SendMessageMessage(); }
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
DataStructure structure = createStructureToRead();
|
||||
structure.readBytes(inputStream);
|
||||
((SendMessageMessage)structure).getPayload().setUnencryptedData(((SendMessageMessage)structure).getPayload().getEncryptedData());
|
||||
return structure.toString();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the data structure", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the data structure", ioe);
|
||||
return null;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new SendMessageMessage(); }
|
||||
|
||||
public void testStructure() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
DataStructure orig;
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
orig = createDataStructure();
|
||||
orig.writeBytes(baos);
|
||||
|
||||
|
||||
temp = baos.toByteArray();
|
||||
|
||||
DataStructure ds;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
ds = createStructureToRead();
|
||||
ds.readBytes(bais);
|
||||
((SendMessageMessage)ds).getPayload().setUnencryptedData(((SendMessageMessage)ds).getPayload().getEncryptedData());
|
||||
|
||||
assertEquals(orig, ds);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -22,10 +22,7 @@ import net.i2p.data.i2cp.SessionConfig;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SessionConfigTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SessionConfigTest(), "SessionConfig");
|
||||
}
|
||||
public class SessionConfigTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SessionConfig cfg = new SessionConfig((Destination)(new DestinationTest()).createDataStructure());
|
||||
cfg.setSignature((Signature)(new SignatureTest()).createDataStructure());
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.i2cp.SessionId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SessionIdTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SessionIdTest(), "SessionId");
|
||||
}
|
||||
public class SessionIdTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SessionId id = new SessionId();
|
||||
id.setSessionId(7);
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.SessionKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SessionKeyTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SessionKeyTest(), "SessionKey");
|
||||
}
|
||||
public class SessionKeyTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SessionKey key = new SessionKey();
|
||||
byte data[] = new byte[SessionKey.KEYSIZE_BYTES];
|
||||
|
@ -18,10 +18,7 @@ import net.i2p.data.i2cp.SessionStatusMessage;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SessionStatusMessageTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SessionStatusMessageTest(), "SessionStatusMessage");
|
||||
}
|
||||
public class SessionStatusMessageTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SessionStatusMessage msg = new SessionStatusMessage();
|
||||
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.Signature;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SignatureTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SignatureTest(), "Signature");
|
||||
}
|
||||
public class SignatureTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
Signature sig = new Signature();
|
||||
byte data[] = new byte[Signature.SIGNATURE_BYTES];
|
||||
|
@ -7,7 +7,11 @@ package net.i2p.data;
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
import net.i2p.data.SigningPrivateKey;
|
||||
@ -17,17 +21,78 @@ import net.i2p.data.SigningPrivateKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SigningPrivateKeyTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SigningPrivateKeyTest(), "SigningPrivateKey");
|
||||
}
|
||||
public class SigningPrivateKeyTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SigningPrivateKey privateKey = new SigningPrivateKey();
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
byte data[] = new byte[SigningPrivateKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%16);
|
||||
privateKey.setData(data);
|
||||
return privateKey;
|
||||
signingPrivateKey.setData(data);
|
||||
return signingPrivateKey;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new SigningPrivateKey(); }
|
||||
|
||||
public void testBase64Constructor() throws Exception{
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
byte data[] = new byte[SigningPrivateKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
signingPrivateKey.setData(data);
|
||||
|
||||
SigningPrivateKey key2 = new SigningPrivateKey(signingPrivateKey.toBase64());
|
||||
assertEquals(signingPrivateKey, key2);
|
||||
}
|
||||
|
||||
public void testNullEquals(){
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
byte data[] = new byte[SigningPrivateKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
signingPrivateKey.setData(data);
|
||||
|
||||
assertFalse(signingPrivateKey.equals(null));
|
||||
}
|
||||
|
||||
public void testNullData() throws Exception{
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
signingPrivateKey.toString();
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
signingPrivateKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortData() throws Exception{
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
byte data[] = new byte[56];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i);
|
||||
signingPrivateKey.setData(data);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
signingPrivateKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortRead() throws Exception{
|
||||
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream("short".getBytes());
|
||||
boolean error = false;
|
||||
try{
|
||||
signingPrivateKey.readBytes(in);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -8,6 +8,9 @@ package net.i2p.data;
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataStructure;
|
||||
import net.i2p.data.SigningPublicKey;
|
||||
@ -17,10 +20,7 @@ import net.i2p.data.SigningPublicKey;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class SigningPublicKeyTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new SigningPublicKeyTest(), "SigningPublicKey");
|
||||
}
|
||||
public class SigningPublicKeyTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
byte data[] = new byte[SigningPublicKey.KEYSIZE_BYTES];
|
||||
@ -30,4 +30,67 @@ class SigningPublicKeyTest extends StructureTest {
|
||||
return publicKey;
|
||||
}
|
||||
public DataStructure createStructureToRead() { return new SigningPublicKey(); }
|
||||
|
||||
public void testBase64Constructor() throws Exception{
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
byte data[] = new byte[SigningPublicKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
publicKey.setData(data);
|
||||
|
||||
SigningPublicKey key2 = new SigningPublicKey(publicKey.toBase64());
|
||||
assertEquals(publicKey, key2);
|
||||
}
|
||||
|
||||
public void testNullEquals(){
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
byte data[] = new byte[SigningPublicKey.KEYSIZE_BYTES];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i%56);
|
||||
publicKey.setData(data);
|
||||
|
||||
assertFalse(publicKey.equals(null));
|
||||
}
|
||||
|
||||
public void testNullData() throws Exception{
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
publicKey.toString();
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortData() throws Exception{
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
byte data[] = new byte[56];
|
||||
for (int i = 0; i < data.length; i++)
|
||||
data[i] = (byte)(i);
|
||||
publicKey.setData(data);
|
||||
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.writeBytes(new ByteArrayOutputStream());
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
public void testShortRead() throws Exception{
|
||||
SigningPublicKey publicKey = new SigningPublicKey();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream("six times nine equals forty-two".getBytes());
|
||||
boolean error = false;
|
||||
try{
|
||||
publicKey.readBytes(in);
|
||||
}catch(DataFormatException dfe){
|
||||
error = true;
|
||||
}
|
||||
assertTrue(error);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@ -16,44 +17,30 @@ import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test harness for the boolean structure
|
||||
* Test harness for the date structure
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class StringTest implements TestDataGenerator, TestDataPrinter {
|
||||
static {
|
||||
TestData.registerGenerator(new StringTest(), "String");
|
||||
TestData.registerPrinter(new StringTest(), "String");
|
||||
}
|
||||
private static final Log _log = new Log(StringTest.class);
|
||||
public class StringTest extends TestCase{
|
||||
|
||||
public byte[] getData() {
|
||||
public void testString() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
DataHelper.writeString(baos, "Hello, I2P");
|
||||
return baos.toByteArray();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the string", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the string", ioe);
|
||||
return null;
|
||||
}
|
||||
|
||||
DataHelper.writeString(baos, "Hello, I2P");
|
||||
temp = baos.toByteArray();
|
||||
|
||||
|
||||
String s = null;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
s = DataHelper.readString(bais);
|
||||
|
||||
assertEquals(s, "Hello, I2P");
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
String str = DataHelper.readString(inputStream);
|
||||
return ""+str;
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the string", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the string", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -9,6 +9,7 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@ -17,46 +18,38 @@ import net.i2p.data.DataStructure;
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.I2PAppContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Utility class for wrapping data structure tests
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
public abstract class StructureTest implements TestDataGenerator, TestDataPrinter {
|
||||
private static final Log _log = new Log(StructureTest.class);
|
||||
protected static I2PAppContext _context = I2PAppContext.getGlobalContext();
|
||||
|
||||
public abstract class StructureTest extends TestCase{
|
||||
|
||||
public abstract DataStructure createDataStructure() throws DataFormatException;
|
||||
public abstract DataStructure createStructureToRead();
|
||||
|
||||
public byte[] getData() {
|
||||
|
||||
public void testStructure() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
DataStructure orig;
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
DataStructure structure = createDataStructure();
|
||||
structure.writeBytes(baos);
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the data structure", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the data structure", ioe);
|
||||
return null;
|
||||
}
|
||||
return baos.toByteArray();
|
||||
|
||||
orig = createDataStructure();
|
||||
orig.writeBytes(baos);
|
||||
|
||||
|
||||
temp = baos.toByteArray();
|
||||
|
||||
DataStructure ds;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
ds = createStructureToRead();
|
||||
ds.readBytes(bais);
|
||||
|
||||
assertEquals(orig, ds);
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
DataStructure structure = createStructureToRead();
|
||||
structure.readBytes(inputStream);
|
||||
return structure.toString() + "\n\nIn base 64: " + structure.toBase64();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the data structure", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the data structure", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -1,150 +0,0 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import net.i2p.util.Log;
|
||||
|
||||
/**
|
||||
* Test harness for loading / storing data structures
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
public class TestData {
|
||||
private final static Log _log = new Log(TestData.class);
|
||||
private final static String HELP = "\nUsage: TestData generate objectType outFile\n" +
|
||||
" TestData display objectType inFile\n" +
|
||||
" TestData test objectType tempFile\n" +
|
||||
"Known types: ";
|
||||
|
||||
private final static String OP_GENERATE = "generate";
|
||||
private final static String OP_DISPLAY = "display";
|
||||
private final static String OP_TEST = "test";
|
||||
|
||||
private final static HashMap _generators;
|
||||
private final static HashMap _printers;
|
||||
static {
|
||||
_generators = new HashMap();
|
||||
_generators.put("NullType", new TestDataGenerator() { public byte[] getData() { return new byte[1]; } });
|
||||
|
||||
_printers = new HashMap();
|
||||
_printers.put("NullType", new TestDataPrinter() { public String testData(InputStream in) { return "Null data read successfully"; } });
|
||||
}
|
||||
|
||||
public static void registerTest(StructureTest test, String name) {
|
||||
registerGenerator(test, name);
|
||||
registerPrinter(test, name);
|
||||
}
|
||||
public static void registerGenerator(TestDataGenerator test, String name) {
|
||||
_generators.put(name, test);
|
||||
}
|
||||
public static void registerPrinter(TestDataPrinter test, String name) {
|
||||
_printers.put(name, test);
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
if (args.length < 1) {
|
||||
showHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (OP_GENERATE.equalsIgnoreCase(args[0])) {
|
||||
validateTest(args[1]);
|
||||
if (args.length != 3) {
|
||||
showHelp();
|
||||
return;
|
||||
}
|
||||
generate(args[1], args[2]);
|
||||
return;
|
||||
} else if (OP_DISPLAY.equalsIgnoreCase(args[0])) {
|
||||
validateTest(args[1]);
|
||||
if (args.length != 3) {
|
||||
showHelp();
|
||||
return;
|
||||
}
|
||||
display(args[1], args[2]);
|
||||
} else if (OP_TEST.equalsIgnoreCase(args[0])) {
|
||||
validateTest(args[1]);
|
||||
if (args.length != 3) {
|
||||
showHelp();
|
||||
return;
|
||||
}
|
||||
generate(args[1], args[2]);
|
||||
display(args[1], args[2]);
|
||||
} else {
|
||||
showHelp();
|
||||
}
|
||||
try { Thread.sleep(2000); } catch (InterruptedException ie) {}
|
||||
}
|
||||
|
||||
private static void validateTest(String objectType) {
|
||||
try {
|
||||
String clsName = TestData.class.getPackage().getName() + "." + objectType + "Test";
|
||||
Class.forName(clsName);
|
||||
} catch (Throwable t) {
|
||||
_log.error("Error validating the object type", t);
|
||||
}
|
||||
}
|
||||
|
||||
public static void generate(String objectType, String outFile) {
|
||||
TestDataGenerator gen = (TestDataGenerator)_generators.get(objectType);
|
||||
byte[] data = gen.getData();
|
||||
if (data == null) {
|
||||
_log.error("Error generating the data. fail");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
File f = new File(outFile);
|
||||
FileOutputStream out = new FileOutputStream(f);
|
||||
out.write(data);
|
||||
out.flush();
|
||||
out.close();
|
||||
_log.debug("Wrote the file out to " + f.getAbsolutePath());
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing out the object", ioe);
|
||||
}
|
||||
}
|
||||
|
||||
public static void display(String type, String inFile) {
|
||||
try {
|
||||
File f = new File(inFile);
|
||||
FileInputStream in = new FileInputStream(f);
|
||||
TestDataPrinter printer = (TestDataPrinter)_printers.get(type);
|
||||
String display = printer.testData(in);
|
||||
in.close();
|
||||
_log.info("Displaying " + inFile + " of type: " + type);
|
||||
_log.info(display);
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the file to display", ioe);
|
||||
}
|
||||
}
|
||||
|
||||
private static String listTypes() {
|
||||
StringBuffer buf = new StringBuffer();
|
||||
for (Iterator iter = _generators.keySet().iterator(); iter.hasNext(); ) {
|
||||
String type = (String)iter.next();
|
||||
buf.append(type);
|
||||
if (iter.hasNext())
|
||||
buf.append(", ");
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static void showHelp() {
|
||||
_log.info(HELP+listTypes());
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Defines a method to create the serialization of an object
|
||||
*/
|
||||
public interface TestDataGenerator {
|
||||
public byte[] getData();
|
||||
}
|
||||
|
@ -1,18 +0,0 @@
|
||||
package net.i2p.data;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* Defines a method to read the serialization of an object and display it
|
||||
*/
|
||||
public interface TestDataPrinter {
|
||||
public String testData(InputStream stream);
|
||||
}
|
||||
|
@ -17,10 +17,7 @@ import net.i2p.data.TunnelId;
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class TunnelIdTest extends StructureTest {
|
||||
static {
|
||||
TestData.registerTest(new TunnelIdTest(), "TunnelId");
|
||||
}
|
||||
public class TunnelIdTest extends StructureTest {
|
||||
public DataStructure createDataStructure() throws DataFormatException {
|
||||
TunnelId id = new TunnelId();
|
||||
id.setTunnelId(42);
|
||||
|
@ -9,51 +9,38 @@ package net.i2p.data;
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
|
||||
import net.i2p.data.DataFormatException;
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test harness for the numerical structure (in java, an UnsignedInteger)
|
||||
* Test harness for the date structure
|
||||
*
|
||||
* @author jrandom
|
||||
*/
|
||||
class UnsignedIntegerTest implements TestDataGenerator, TestDataPrinter {
|
||||
static {
|
||||
TestData.registerGenerator(new UnsignedIntegerTest(), "UnsignedInteger");
|
||||
TestData.registerPrinter(new UnsignedIntegerTest(), "UnsignedInteger");
|
||||
}
|
||||
private static final Log _log = new Log(UnsignedIntegerTest.class);
|
||||
public class UnsignedIntegerTest extends TestCase{
|
||||
|
||||
public byte[] getData() {
|
||||
public void testLong() throws Exception{
|
||||
byte[] temp = null;
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
DataHelper.writeLong(baos, 4, 42);
|
||||
return baos.toByteArray();
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error writing the integer", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error writing the integer", ioe);
|
||||
return null;
|
||||
}
|
||||
|
||||
DataHelper.writeLong(baos, 4, 42);
|
||||
temp = baos.toByteArray();
|
||||
|
||||
|
||||
long l;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
|
||||
|
||||
l = DataHelper.readLong(bais, 4);
|
||||
|
||||
assertEquals(42, l);
|
||||
}
|
||||
|
||||
public String testData(InputStream inputStream) {
|
||||
try {
|
||||
long val = DataHelper.readLong(inputStream, 4);
|
||||
return ""+val;
|
||||
} catch (DataFormatException dfe) {
|
||||
_log.error("Error reading the integer", dfe);
|
||||
return null;
|
||||
} catch (IOException ioe) {
|
||||
_log.error("Error reading the integer", ioe);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
33
core/java/test/net/i2p/stat/RateStatTest.java
Normal file
33
core/java/test/net/i2p/stat/RateStatTest.java
Normal file
@ -0,0 +1,33 @@
|
||||
package net.i2p.stat;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class RateStatTest extends TestCase {
|
||||
public void testRateStat() throws Exception{
|
||||
RateStat rs = new RateStat("moo", "moo moo moo", "cow trueisms", new long[] { 60 * 1000, 60 * 60 * 1000,
|
||||
24 * 60 * 60 * 1000});
|
||||
for (int i = 0; i < 50; i++) {
|
||||
Thread.sleep(20);
|
||||
rs.addData(i * 100, 20);
|
||||
}
|
||||
rs.coalesceStats();
|
||||
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(2048);
|
||||
|
||||
rs.store(baos, "rateStat.test");
|
||||
byte data[] = baos.toByteArray();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.load(new java.io.ByteArrayInputStream(data));
|
||||
|
||||
RateStat loadedRs = new RateStat("moo", "moo moo moo", "cow trueisms", new long[] { 60 * 1000,
|
||||
60 * 60 * 1000,
|
||||
24 * 60 * 60 * 1000});
|
||||
loadedRs.load(props, "rateStat.test", true);
|
||||
|
||||
assertEquals(rs, loadedRs);
|
||||
|
||||
}
|
||||
}
|
28
core/java/test/net/i2p/stat/RateTest.java
Normal file
28
core/java/test/net/i2p/stat/RateTest.java
Normal file
@ -0,0 +1,28 @@
|
||||
package net.i2p.stat;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class RateTest extends TestCase {
|
||||
public void testRate() throws Exception{
|
||||
Rate rate = new Rate(1000);
|
||||
for (int i = 0; i < 50; i++) {
|
||||
Thread.sleep(20);
|
||||
rate.addData(i * 100, 20);
|
||||
}
|
||||
rate.coalesce();
|
||||
StringBuffer buf = new StringBuffer(1024);
|
||||
|
||||
rate.store("rate.test", buf);
|
||||
byte data[] = buf.toString().getBytes();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.load(new java.io.ByteArrayInputStream(data));
|
||||
|
||||
Rate r = new Rate(props, "rate.test", true);
|
||||
|
||||
assertEquals(r, rate);
|
||||
}
|
||||
}
|
27
core/java/test/net/i2p/stat/StatTestSuite.java
Normal file
27
core/java/test/net/i2p/stat/StatTestSuite.java
Normal file
@ -0,0 +1,27 @@
|
||||
package net.i2p.stat;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class StatTestSuite {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("net.i2p.stat.StatTestSuite");
|
||||
|
||||
suite.addTestSuite(RateStatTest.class);
|
||||
suite.addTestSuite(RateTest.class);
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
package net.i2p.util;
|
||||
|
||||
import java.util.Properties;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
/**
|
||||
* Check to make sure the updates to the logger.config are
|
||||
* honored.
|
||||
*
|
||||
*/
|
||||
public class LogSettings {
|
||||
private static I2PAppContext _context;
|
||||
|
||||
public static void main(String args[]) {
|
||||
_context = I2PAppContext.getGlobalContext();
|
||||
Log log = _context.logManager().getLog(LogSettings.class);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
setLevel(Log.DEBUG);
|
||||
test("DEBUG", log);
|
||||
setLevel(Log.INFO);
|
||||
test("INFO", log);
|
||||
setLevel(Log.WARN);
|
||||
test("WARN", log);
|
||||
setLevel(Log.ERROR);
|
||||
test("ERROR", log);
|
||||
setLevel(Log.CRIT);
|
||||
test("CRIT", log);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setLevel(int level) {
|
||||
try {
|
||||
Properties p = new Properties();
|
||||
File f = new File("logger.config");
|
||||
DataHelper.loadProps(p, f);
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(level));
|
||||
DataHelper.storeProps(p, f);
|
||||
try { Thread.sleep(90*1000); } catch (InterruptedException ie) {}
|
||||
//_context.logManager().rereadConfig();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void test(String setting, Log log) {
|
||||
log.debug(setting + ": debug");
|
||||
log.info(setting + ": info");
|
||||
log.warn(setting + ": warn");
|
||||
log.error(setting + ": error");
|
||||
log.log(Log.CRIT, setting + ": crit");
|
||||
}
|
||||
}
|
||||
|
249
core/java/test/net/i2p/util/LogSettingsTest.java
Normal file
249
core/java/test/net/i2p/util/LogSettingsTest.java
Normal file
@ -0,0 +1,249 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.util.Properties;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.PrintStream;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import net.i2p.I2PAppContext;
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
* @author Comwiz
|
||||
*/
|
||||
public class LogSettingsTest extends TestCase {
|
||||
|
||||
|
||||
private Properties p;
|
||||
private Log log;
|
||||
private I2PAppContext _context;
|
||||
private File f;
|
||||
|
||||
private String origMinimumOnScreenLevel;
|
||||
private String origLogSettings;
|
||||
|
||||
|
||||
/**
|
||||
* Sets up the test fixture.
|
||||
*
|
||||
* Called before every test case method.
|
||||
*/
|
||||
protected void setUp() throws IOException {
|
||||
|
||||
_context = I2PAppContext.getGlobalContext();
|
||||
log = _context.logManager().getLog(LogSettingsTest.class);
|
||||
p = new Properties();
|
||||
f = new File("logger.config");
|
||||
if(!f.exists()){
|
||||
FileWriter temp = new FileWriter(f);
|
||||
temp.close();
|
||||
}
|
||||
DataHelper.loadProps(p, f);
|
||||
origMinimumOnScreenLevel = p.getProperty("logger.record.net.i2p.util.LogSettings", Log.STR_ERROR);
|
||||
origLogSettings = p.getProperty("logger.minimumOnScreenLevel", Log.STR_CRIT);
|
||||
}
|
||||
|
||||
protected void tearDown() throws IOException{
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", origMinimumOnScreenLevel);
|
||||
p.setProperty("logger.minimumOnScreenLevel", origLogSettings);
|
||||
DataHelper.storeProps(p, f);
|
||||
|
||||
System.gc();
|
||||
}
|
||||
|
||||
public void testDebug() throws IOException {
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(Log.DEBUG));
|
||||
p.setProperty("logger.minimumOnScreenLevel", Log.toLevelString(Log.DEBUG));
|
||||
|
||||
DataHelper.storeProps(p, f);
|
||||
|
||||
_context.logManager().rereadConfig();
|
||||
|
||||
PipedInputStream pin = new PipedInputStream();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(pin));
|
||||
|
||||
PrintStream systemOut = System.out;
|
||||
PrintStream pout = new PrintStream(new PipedOutputStream(pin));
|
||||
|
||||
System.setOut(pout);
|
||||
|
||||
log.debug("DEBUG" + ": debug");
|
||||
log.info("DEBUG" + ": info");
|
||||
log.warn("DEBUG" + ": warn");
|
||||
log.error("DEBUG" + ": error");
|
||||
log.log(Log.CRIT, "DEBUG" + ": crit");
|
||||
_context.logManager().shutdown();
|
||||
|
||||
String l1 = in.readLine();
|
||||
String l2 = in.readLine();
|
||||
String l3 = in.readLine();
|
||||
String l4 = in.readLine();
|
||||
String l5 = in.readLine();
|
||||
|
||||
assertTrue(
|
||||
l1.matches(".*DEBUG: debug") &&
|
||||
l2.matches(".*DEBUG: info") &&
|
||||
l3.matches(".*DEBUG: warn") &&
|
||||
l4.matches(".*DEBUG: error") &&
|
||||
l5.matches(".*DEBUG: crit")
|
||||
);
|
||||
|
||||
System.setOut(systemOut);
|
||||
|
||||
}
|
||||
|
||||
public void testInfo() throws IOException {
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(Log.INFO));
|
||||
p.setProperty("logger.minimumOnScreenLevel", Log.toLevelString(Log.DEBUG));
|
||||
|
||||
DataHelper.storeProps(p, f);
|
||||
_context.logManager().rereadConfig();
|
||||
|
||||
PipedInputStream pin = new PipedInputStream();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(pin));
|
||||
|
||||
PrintStream systemOut = System.out;
|
||||
PrintStream pout = new PrintStream(new PipedOutputStream(pin));
|
||||
|
||||
System.setOut(pout);
|
||||
|
||||
log.debug("INFO" + ": debug");
|
||||
log.info("INFO" + ": info");
|
||||
log.warn("INFO" + ": warn");
|
||||
log.error("INFO" + ": error");
|
||||
log.log(Log.CRIT, "INFO" + ": crit");
|
||||
_context.logManager().shutdown();
|
||||
|
||||
String l1 = in.readLine();
|
||||
String l2 = in.readLine();
|
||||
String l3 = in.readLine();
|
||||
String l4 = in.readLine();
|
||||
|
||||
assertTrue(
|
||||
l1.matches(".*INFO: info") &&
|
||||
l2.matches(".*INFO: warn") &&
|
||||
l3.matches(".*INFO: error") &&
|
||||
l4.matches(".*INFO: crit")
|
||||
);
|
||||
|
||||
System.setOut(systemOut);
|
||||
|
||||
}
|
||||
|
||||
public void testWarn() throws IOException {
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(Log.WARN));
|
||||
p.setProperty("logger.minimumOnScreenLevel", Log.toLevelString(Log.DEBUG));
|
||||
|
||||
DataHelper.storeProps(p, f);
|
||||
_context.logManager().rereadConfig();
|
||||
|
||||
PipedInputStream pin = new PipedInputStream();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(pin));
|
||||
|
||||
PrintStream systemOut = System.out;
|
||||
PrintStream pout = new PrintStream(new PipedOutputStream(pin));
|
||||
|
||||
System.setOut(pout);
|
||||
|
||||
log.debug("WARN" + ": debug");
|
||||
log.info("WARN" + ": info");
|
||||
log.warn("WARN" + ": warn");
|
||||
log.error("WARN" + ": error");
|
||||
log.log(Log.CRIT, "WARN" + ": crit");
|
||||
_context.logManager().shutdown();
|
||||
|
||||
String l1 = in.readLine();
|
||||
String l2 = in.readLine();
|
||||
String l3 = in.readLine();
|
||||
|
||||
assertTrue(
|
||||
l1.matches(".*WARN: warn") &&
|
||||
l2.matches(".*WARN: error") &&
|
||||
l3.matches(".*WARN: crit")
|
||||
);
|
||||
|
||||
System.setOut(systemOut);
|
||||
}
|
||||
|
||||
public void testError() throws IOException{
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(Log.ERROR));
|
||||
p.setProperty("logger.minimumOnScreenLevel", Log.toLevelString(Log.DEBUG));
|
||||
|
||||
DataHelper.storeProps(p, f);
|
||||
_context.logManager().rereadConfig();
|
||||
|
||||
PipedInputStream pin = new PipedInputStream();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(pin));
|
||||
|
||||
PrintStream systemOut = System.out;
|
||||
PrintStream pout = new PrintStream(new PipedOutputStream(pin));
|
||||
|
||||
System.setOut(pout);
|
||||
|
||||
log.debug("ERROR" + ": debug");
|
||||
log.info("ERROR" + ": info");
|
||||
log.warn("ERROR" + ": warn");
|
||||
log.error("ERROR" + ": error");
|
||||
log.log(Log.CRIT, "ERROR" + ": crit");
|
||||
_context.logManager().shutdown();
|
||||
|
||||
String l1 = in.readLine();
|
||||
String l2 = in.readLine();
|
||||
|
||||
assertTrue(
|
||||
l1.matches(".*ERROR: error") &&
|
||||
l2.matches(".*ERROR: crit")
|
||||
);
|
||||
|
||||
System.setOut(systemOut);
|
||||
}
|
||||
|
||||
public void testCrit() throws IOException {
|
||||
p.setProperty("logger.record.net.i2p.util.LogSettings", Log.toLevelString(Log.CRIT));
|
||||
p.setProperty("logger.minimumOnScreenLevel", Log.toLevelString(Log.DEBUG));
|
||||
|
||||
DataHelper.storeProps(p, f);
|
||||
_context.logManager().rereadConfig();
|
||||
|
||||
PipedInputStream pin = new PipedInputStream();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(pin));
|
||||
|
||||
PrintStream systemOut = System.out;
|
||||
PrintStream pout = new PrintStream(new PipedOutputStream(pin));
|
||||
|
||||
System.setOut(pout);
|
||||
|
||||
log.debug("CRIT" + ": debug");
|
||||
log.info("CRIT" + ": info");
|
||||
log.warn("CRIT" + ": warn");
|
||||
log.error("CRIT" + ": error");
|
||||
log.log(Log.CRIT, "CRIT" + ": crit");
|
||||
_context.logManager().shutdown();
|
||||
|
||||
String l1 = in.readLine();
|
||||
|
||||
assertTrue(
|
||||
l1.matches(".*CRIT: crit")
|
||||
);
|
||||
|
||||
System.setOut(systemOut);
|
||||
}
|
||||
|
||||
|
||||
}
|
50
core/java/test/net/i2p/util/LookAheadInputStreamTest.java
Normal file
50
core/java/test/net/i2p/util/LookAheadInputStreamTest.java
Normal file
@ -0,0 +1,50 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class LookAheadInputStreamTest extends TestCase {
|
||||
public void testLookAheadInputStream() throws Exception{
|
||||
byte buf[] = new byte[32];
|
||||
for (int i = 0; i < 32; i++)
|
||||
buf[i] = (byte)i;
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
|
||||
|
||||
LookaheadInputStream lis = new LookaheadInputStream(8);
|
||||
lis.initialize(bais);
|
||||
byte rbuf[] = new byte[32];
|
||||
int read = lis.read(rbuf);
|
||||
assertEquals(read,24);
|
||||
for (int i = 0; i < 24; i++)
|
||||
assertEquals(rbuf[i],(byte)i);
|
||||
for (int i = 0; i < 8; i++)
|
||||
assertEquals(lis.getFooter()[i],(byte)(i+24));
|
||||
|
||||
|
||||
for (int size = 9; size < 32*1024; size+=100) {
|
||||
buf = new byte[size];
|
||||
new java.util.Random().nextBytes(buf);
|
||||
bais = new ByteArrayInputStream(buf);
|
||||
|
||||
lis = new LookaheadInputStream(8);
|
||||
lis.initialize(bais);
|
||||
rbuf = new byte[size];
|
||||
read = lis.read(rbuf);
|
||||
assertEquals(read,(size-8));
|
||||
for (int i = 0; i < (size-8); i++)
|
||||
assertEquals(rbuf[i],buf[i]);
|
||||
for (int i = 0; i < 8; i++)
|
||||
assertEquals(lis.getFooter()[i],buf[i+(size-8)]);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class ResettableGZIPInputStreamTest extends TestCase {
|
||||
public void testResettableGZIPInputStream() throws Exception{
|
||||
for (int size = 129; size < 64*1024; size+=100) {
|
||||
byte b[] = new byte[size];
|
||||
new java.util.Random().nextBytes(b);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
|
||||
GZIPOutputStream o = new GZIPOutputStream(baos);
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = baos.toByteArray();
|
||||
|
||||
ResettableGZIPInputStream in = new ResettableGZIPInputStream(new ByteArrayInputStream(compressed));
|
||||
ByteArrayOutputStream baos2 = new ByteArrayOutputStream(size);
|
||||
byte rbuf[] = new byte[512];
|
||||
while (true) {
|
||||
int read = in.read(rbuf);
|
||||
if (read == -1)
|
||||
break;
|
||||
baos2.write(rbuf, 0, read);
|
||||
}
|
||||
byte rv[] = baos2.toByteArray();
|
||||
assertEquals(rv.length,b.length);
|
||||
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
|
||||
}
|
||||
|
||||
byte orig[] = "ho ho ho, merry christmas".getBytes();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
|
||||
GZIPOutputStream o = new GZIPOutputStream(baos);
|
||||
o.write(orig);
|
||||
o.finish();
|
||||
o.flush();
|
||||
o.close();
|
||||
byte compressed[] = baos.toByteArray();
|
||||
|
||||
ResettableGZIPInputStream i = new ResettableGZIPInputStream();
|
||||
i.initialize(new ByteArrayInputStream(compressed));
|
||||
byte readBuf[] = new byte[128];
|
||||
int read = i.read(readBuf);
|
||||
assertEquals(read,orig.length);
|
||||
for (int j = 0; j < read; j++)
|
||||
assertEquals(readBuf[j],orig[j]);
|
||||
assertEquals(-1,i.read());
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class ResettableGZIPOutputStreamTest extends TestCase {
|
||||
public void testResettableGZIPOutputStream() throws Exception{
|
||||
byte b[] = "hi, how are you today?".getBytes();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ResettableGZIPOutputStream o = new ResettableGZIPOutputStream(baos);
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = baos.toByteArray();
|
||||
|
||||
/*ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
|
||||
GZIPOutputStream gzo = new GZIPOutputStream(baos2);
|
||||
gzo.write(b);
|
||||
gzo.finish();
|
||||
gzo.flush();
|
||||
byte compressed2[] = baos2.toByteArray();
|
||||
|
||||
assertTrue(DataHelper.eq(compressed, compressed2));*/
|
||||
|
||||
GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));
|
||||
byte rv[] = new byte[128];
|
||||
int read = in.read(rv);
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
|
||||
}
|
||||
}
|
65
core/java/test/net/i2p/util/ReusableGZIPInputStreamTest.java
Normal file
65
core/java/test/net/i2p/util/ReusableGZIPInputStreamTest.java
Normal file
@ -0,0 +1,65 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class ReusableGZIPInputStreamTest extends TestCase {
|
||||
public void testReusableGZIPInputStream() throws Exception{
|
||||
{
|
||||
byte b[] = "hi, how are you today?".getBytes();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
|
||||
GZIPOutputStream o = new GZIPOutputStream(baos);
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = baos.toByteArray();
|
||||
|
||||
ReusableGZIPInputStream in = ReusableGZIPInputStream.acquire();
|
||||
in.initialize(new ByteArrayInputStream(compressed));
|
||||
byte rv[] = new byte[128];
|
||||
int read = in.read(rv);
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
ReusableGZIPInputStream.release(in);
|
||||
}
|
||||
|
||||
for (int size = 0; size < 64*1024; size+=100) {
|
||||
byte b[] = new byte[size];
|
||||
new java.util.Random().nextBytes(b);
|
||||
|
||||
ReusableGZIPOutputStream o = ReusableGZIPOutputStream.acquire();
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = o.getData();
|
||||
ReusableGZIPOutputStream.release(o);
|
||||
|
||||
GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));
|
||||
ByteArrayOutputStream baos2 = new ByteArrayOutputStream(256*1024);
|
||||
byte rbuf[] = new byte[128];
|
||||
while (true) {
|
||||
int read = in.read(rbuf);
|
||||
if (read == -1)
|
||||
break;
|
||||
baos2.write(rbuf, 0, read);
|
||||
}
|
||||
byte rv[] = baos2.toByteArray();
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package net.i2p.util;
|
||||
/*
|
||||
* free (adj.): unencumbered; not under the control of others
|
||||
* Written by jrandom in 2003 and released into the public domain
|
||||
* with no warranty of any kind, either expressed or implied.
|
||||
* It probably won't make your computer catch on fire, or eat
|
||||
* your children, but it might. Use at your own risk.
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
public class ReusableGZIPOutputStreamTest extends TestCase {
|
||||
public void testReusableGZIPOutputStream() throws Exception{
|
||||
{
|
||||
byte b[] = "hi, how are you today?".getBytes();
|
||||
ReusableGZIPOutputStream o = ReusableGZIPOutputStream.acquire();
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = o.getData();
|
||||
ReusableGZIPOutputStream.release(o);
|
||||
|
||||
GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));
|
||||
byte rv[] = new byte[128];
|
||||
int read = in.read(rv);
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
}
|
||||
|
||||
for (int size = 500; size < 64*1024; size+=100) {
|
||||
byte b[] = new byte[size];
|
||||
new java.util.Random().nextBytes(b);
|
||||
|
||||
ReusableGZIPOutputStream o = ReusableGZIPOutputStream.acquire();
|
||||
o.write(b);
|
||||
o.finish();
|
||||
o.flush();
|
||||
byte compressed[] = o.getData();
|
||||
ReusableGZIPOutputStream.release(o);
|
||||
|
||||
GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));
|
||||
ByteArrayOutputStream baos2 = new ByteArrayOutputStream(256*1024);
|
||||
byte rbuf[] = new byte[128];
|
||||
while (true) {
|
||||
int read = in.read(rbuf);
|
||||
if (read == -1)
|
||||
break;
|
||||
baos2.write(rbuf, 0, read);
|
||||
}
|
||||
byte rv[] = baos2.toByteArray();
|
||||
assertTrue(DataHelper.eq(rv, 0, b, 0, b.length));
|
||||
}
|
||||
}
|
||||
}
|
25
core/java/test/net/i2p/util/UtilTestSuite.java
Normal file
25
core/java/test/net/i2p/util/UtilTestSuite.java
Normal file
@ -0,0 +1,25 @@
|
||||
package net.i2p.util;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Test suite for all available tests in the net.i2p.util package
|
||||
*
|
||||
* @author comwiz
|
||||
*/
|
||||
public class UtilTestSuite {
|
||||
|
||||
public static Test suite() {
|
||||
TestSuite suite = new TestSuite("net.i2p.util.UtilTestSuite");
|
||||
|
||||
suite.addTestSuite(LogSettingsTest.class);
|
||||
suite.addTestSuite(LookAheadInputStreamTest.class);
|
||||
suite.addTestSuite(ResettableGZIPInputStreamTest.class);
|
||||
suite.addTestSuite(ResettableGZIPOutputStreamTest.class);
|
||||
suite.addTestSuite(ReusableGZIPInputStreamTest.class);
|
||||
suite.addTestSuite(ReusableGZIPOutputStreamTest.class);
|
||||
|
||||
return suite;
|
||||
}
|
||||
}
|
@ -8,7 +8,7 @@
|
||||
<target name="compile">
|
||||
<mkdir dir="./build" />
|
||||
<mkdir dir="./build/obj" />
|
||||
<javac srcdir="./src:./test" debug="true" source="1.3" target="1.3" deprecation="on" destdir="./build/obj" classpath="../../core/java/build/i2p.jar" />
|
||||
<javac srcdir="./src" debug="true" source="1.3" target="1.3" deprecation="on" destdir="./build/obj" classpath="../../core/java/build/i2p.jar" />
|
||||
</target>
|
||||
<target name="jar" depends="compile">
|
||||
<jar destfile="./build/router.jar" basedir="./build/obj" includes="**/*.class" />
|
||||
|
Reference in New Issue
Block a user