Moved existing JUnit tests to junittest/ in preparation for ScalaTest

This commit is contained in:
str4d
2012-07-30 04:04:07 +00:00
parent d27d0bd2e4
commit 48df91f796
101 changed files with 1 additions and 1 deletions

View File

@ -1,30 +0,0 @@
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;
}
}

View File

@ -1,34 +0,0 @@
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 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);
}
}

View File

@ -1,29 +0,0 @@
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 junit.framework.Test;
import junit.framework.TestSuite;
import net.i2p.client.datagram.DatagramTest;
/**
* @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;
}
}

View File

@ -1,90 +0,0 @@
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 java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.Destination;
/**
*
* @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){}
}

View File

@ -1,121 +0,0 @@
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 junit.framework.TestCase;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.crypto.DSAEngine;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.data.Hash;
/**
*
* @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;
}
assertTrue(error);
error = false;
try{
dd.getSender();
}catch(I2PInvalidDatagramException i2pide){
error = true;
}
assertTrue(error);
error = false;
try{
dd.getHash();
}catch(I2PInvalidDatagramException i2pide){
error = true;
}
assertTrue(error);
}
}

View File

@ -1,65 +0,0 @@
package net.i2p.client.naming;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import junit.framework.TestCase;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
public class BlockfileNamingServiceTest extends TestCase {
BlockfileNamingService _bns;
List<String> _names;
public void setUp() {
I2PAppContext ctx = new I2PAppContext();
_bns = new BlockfileNamingService(ctx);
_names = null;
Properties props = new Properties();
try {
DataHelper.loadProps(props, new File("../../installer/resources/hosts.txt"), true);
_names = new ArrayList(props.keySet());
Collections.shuffle(_names);
} catch (IOException ioe) {
_bns.shutdown();
return;
}
}
public void tearDown() {
_bns.shutdown();
File f = new File("hostsdb.blockfile");
f.delete();
}
public void testRepeatedLookup() throws Exception{
int found = 0;
int notfound = 0;
int rfound = 0;
int rnotfound = 0;
for (String name : _names) {
Destination dest = _bns.lookup(name);
if (dest != null) {
found++;
String reverse = _bns.reverseLookup(dest);
if (reverse != null)
rfound++;
else
rnotfound++;
} else {
notfound++;
}
}
assertEquals(0, notfound);
assertEquals(0, rnotfound);
}
}

View File

@ -1,45 +0,0 @@
package net.i2p.client.naming;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.Destination;
public class DummyNamingServiceTest extends TestCase {
private I2PAppContext _context;
public void setUp() {
_context = new I2PAppContext();
}
public void testLookup() throws Exception{
// The good b64 and b32 are the destination of www.i2p2.i2p =)
String goodB64 = "-KR6qyfPWXoN~F3UzzYSMIsaRy4quickbrownfoxXSzUQXQdi2Af1TV2UMH3PpPuNu-GwrqihwmLSkPFg4fv4yQQY3E10VeQVuI67dn5vlan3NGMsjqxoXTSHHt7C3nX3szXK90JSoO~tRMDl1xyqtKm94-RpIyNcLXofd0H6b02683CQIjb-7JiCpDD0zharm6SU54rhdisIUVXpi1xYgg2pKVpssL~KCp7RAGzpt2rSgz~RHFsecqGBeFwJdiko-6CYW~tcBcigM8ea57LK7JjCFVhOoYTqgk95AG04-hfehnmBtuAFHWklFyFh88x6mS9sbVPvi-am4La0G0jvUJw9a3wQ67jMr6KWQ~w~bFe~FDqoZqVXl8t88qHPIvXelvWw2Y8EMSF5PJhWw~AZfoWOA5VQVYvcmGzZIEKtFGE7bgQf3rFtJ2FAtig9XXBsoLisHbJgeVb29Ew5E7bkwxvEe9NYkIqvrKvUAt1i55we0Nkt6xlEdhBqg6xXOyIAAAA";
String goodB32 = "rjxwbsw4zjhv4zsplma6jmf5nr24e4ymvvbycd3swgiinbvg7oga.b32.i2p";
// TODO: Come up with an actual bad b64 and b32
String badB64 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
String badB32 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.b32.i2p";
DummyNamingService ns = new DummyNamingService(_context);
assertNull(ns.lookup(""));
// TODO: Could this case ever come up?
//assertNull(ns.lookup(null));
Destination dGoodB64 = ns.lookup(goodB64);
assertNotNull(dGoodB64);
// TODO: Check that the b64 is preserved.
Destination dGoodB32 = ns.lookup(goodB32);
assertNotNull(dGoodB32);
// TODO: Check that the b32 is preserved.
// TODO: Come up with an actual bad b64 and b32
//assertNull(ns.lookup(badB64));
//assertNull(ns.lookup(badB32));
// DummyNameService only handles b64 and b32 addresses
assertNull(ns.lookup("www.i2p2.i2p"));
}
}

View File

@ -1,66 +0,0 @@
package net.i2p.client.naming;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import junit.framework.TestCase;
import java.io.File;
import java.util.Collections;
import net.i2p.I2PAppContext;
import net.i2p.data.Destination;
public class SingleFileNamingServiceTest extends TestCase {
private I2PAppContext _context;
public void setUp() {
_context = new I2PAppContext();
}
public void tearDown() {
File f = new File("testhosts.txt");
f.delete();
}
public void testAddRemoveLookup() throws Exception{
String testB64 = "-KR6qyfPWXoN~F3UzzYSMIsaRy4quickbrownfoxXSzUQXQdi2Af1TV2UMH3PpPuNu-GwrqihwmLSkPFg4fv4yQQY3E10VeQVuI67dn5vlan3NGMsjqxoXTSHHt7C3nX3szXK90JSoO~tRMDl1xyqtKm94-RpIyNcLXofd0H6b02683CQIjb-7JiCpDD0zharm6SU54rhdisIUVXpi1xYgg2pKVpssL~KCp7RAGzpt2rSgz~RHFsecqGBeFwJdiko-6CYW~tcBcigM8ea57LK7JjCFVhOoYTqgk95AG04-hfehnmBtuAFHWklFyFh88x6mS9sbVPvi-am4La0G0jvUJw9a3wQ67jMr6KWQ~w~bFe~FDqoZqVXl8t88qHPIvXelvWw2Y8EMSF5PJhWw~AZfoWOA5VQVYvcmGzZIEKtFGE7bgQf3rFtJ2FAtig9XXBsoLisHbJgeVb29Ew5E7bkwxvEe9NYkIqvrKvUAt1i55we0Nkt6xlEdhBqg6xXOyIAAAA";
Destination testDest = new Destination();
testDest.fromBase64(testB64);
String testB642 = "24SmhWiRDm-GzpV5Gq2sXhuvPpa1OihY7rkxQO4aHy5qKjr6zmEnZ3xQXdkFJJ0Z1lKy73XRmgCyys02G25Hl3cuxlZ2fNbp6KhOzlRKpOIAWFdSWZNF4Fp7sos0x-a-9fxOWnwwQ9MFcRYwixE~iCZf4JG~-Pd-MHgAuDhIX0P3~GmfUvo~9xPjof1ZsnaOV1zC0XUkHxZA5D6V0Bse~Ptfb66lPNcgBxIEntCStBAy~rTjaA3SdAufG29IRWDscpFq1-D4XPaXHnlXu7n7WdpFEM8WWd3ebUMqnq8XvLL1eqoWYzKCe3aaavC3W6~pJp8cxKl2IKrhvSFatHZ0chRg3B4~ja1Cxmw1psisplSkJqMnF921E6pury0i6GH52XAVoj4iiDY~EAvqDhzG-ThwlzTs~2JKzslwxOrD2ejd-dcKdi4i9xvi2JQ4Ib2Mw2ktaQhuAw3Y9EkqAs7oriQQN8N8dwIoYkJLfvh7ousm0iKJJvMt3s55PccM46SoAAAA";
Destination testDest2 = new Destination();
testDest2.fromBase64(testB642);
SingleFileNamingService ns = new SingleFileNamingService(_context, "testhosts.txt");
// testhosts.txt is empty.
assertThat(ns.size(), is(equalTo(0)));
assertThat(ns.getEntries(), is(equalTo(Collections.EMPTY_MAP)));
assertThat(ns.lookup("test.i2p"), is(nullValue()));
assertThat(ns.reverseLookup(testDest), is(nullValue()));
// First put should add the hostname.
ns.put("test.i2p", testDest);
assertThat(ns.size(), is(equalTo(1)));
assertThat(ns.getEntries().size(), is(equalTo(1)));
assertThat(ns.lookup("test.i2p"), is(equalTo(testDest)));
assertThat(ns.reverseLookup(testDest), is(equalTo("test.i2p")));
// Second put should replace the first.
ns.put("test.i2p", testDest2);
assertThat(ns.size(), is(equalTo(1)));
assertThat(ns.lookup("test.i2p"), is(equalTo(testDest2)));
assertThat(ns.reverseLookup(testDest2), is(equalTo("test.i2p")));
assertThat(ns.lookup("test.i2p"), is(not(equalTo(testDest))));
assertThat(ns.reverseLookup(testDest), is(nullValue()));
// Removing the hostname should give an empty file again.
ns.remove("test.i2p");
assertThat(ns.lookup("test.i2p"), is(nullValue()));
assertThat(ns.reverseLookup(testDest2), is(nullValue()));
// Odd quirk - the above lookups don't update size, but getEntries() does...
assertThat(ns.size(), is(equalTo(1)));
assertThat(ns.getEntries(), is(equalTo(Collections.EMPTY_MAP)));
assertThat(ns.size(), is(equalTo(0)));
}
}

View File

@ -1,148 +0,0 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the TheCrypto may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
public class AES256Bench {
private static I2PAppContext _context = new I2PAppContext();
public static void main(String args[]) {
char[] cplain = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
};
byte[] plain = new byte[cplain.length];
for (int x = 0; x < cplain.length; x++) {
plain[x] = (byte)cplain[x];
}
char[] ckey = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
byte[] bkey = new byte[ckey.length];
for (int x = 0; x < ckey.length; x++) {
bkey[x] = (byte)ckey[x];
}
SessionKey key = new SessionKey();
key.setData(bkey);
char[] civ = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
0xfe, 0xdc, 0xba, 0x98, 0x67, 0x54, 0x32, 0x10
};
byte[] iv = new byte[civ.length];
for (int x = 0; x < iv.length; x++) {
iv[x] = (byte)civ[x];
}
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;
for (int x = 0; x < d.length; x++) {
if (plain[x] != d[x]) {
throw new RuntimeException("Failed decrypt at " + x);
}
}
System.out.println("Standard test D(E(value)) == value? " + same);
if (!same) throw new RuntimeException("moo");
plain = "1234567890123456".getBytes();
e = new byte[plain.length];
_context.aes().encrypt(plain, 0, e, 0, key, iv, plain.length);
d = new byte[e.length];
_context.aes().decrypt(e, 0, d, 0, key, iv, d.length);
same = DataHelper.eq(plain, d);
System.out.println("Different value test D(E(value)) == value? " + same);
if (!same) throw new RuntimeException("moo");
System.out.println();
System.out.println();
long times = 100;
long encrypttime = 0;
long decrypttime = 0;
long maxE = 0;
long minE = 0;
long maxD = 0;
long minD = 0;
byte[] message = new byte[2*1024];
for (int i = 0; i < message.length; i++)
message[i] = (byte)((i%26)+'a');
for (int x = 0; x < times; x++) {
long startencrypt = System.currentTimeMillis();
e = new byte[message.length];
d = new byte[e.length];
_context.aes().encrypt(message, 0, e, 0, key, iv, message.length);
long endencryptstartdecrypt = System.currentTimeMillis();
_context.aes().decrypt(e, 0, d, 0, key, iv, d.length);
long enddecrypt = System.currentTimeMillis();
System.out.print(".");
encrypttime += endencryptstartdecrypt - startencrypt;
decrypttime += enddecrypt - endencryptstartdecrypt;
if (!DataHelper.eq(d, message)) {
System.out.println("Lengths: source [" + message.length + "] dest [" + d.length + "]");
System.out.println("Data: dest [" + DataHelper.toString(d, d.length) + "]");
throw new RuntimeException("Holy crap, decrypted != source message");
}
if ( (minE == 0) && (minD == 0) ) {
minE = endencryptstartdecrypt - startencrypt;
maxE = endencryptstartdecrypt - startencrypt;
minD = enddecrypt - endencryptstartdecrypt;
maxD = enddecrypt - endencryptstartdecrypt;
} else {
if (minE > endencryptstartdecrypt - startencrypt) minE = endencryptstartdecrypt - startencrypt;
if (maxE < endencryptstartdecrypt - startencrypt) maxE = endencryptstartdecrypt - startencrypt;
if (minD > enddecrypt - endencryptstartdecrypt) minD = enddecrypt - endencryptstartdecrypt;
if (maxD < enddecrypt - endencryptstartdecrypt) maxD = enddecrypt - endencryptstartdecrypt;
}
}
System.out.println();
System.out.println("Data size : " + message.length);
System.out.println("Encryption Time Average : " + (encrypttime/times) + "ms\ttotal: " + encrypttime + "ms\tmin: " + minE + "ms\tmax: " + maxE + "ms\tEncryption Bps: " + (times*message.length*1000)/encrypttime);
System.out.println("Decryption Time Average : " + (decrypttime/times) + "ms\ttotal: " + decrypttime + "ms\tmin: " + minD + "ms\tmax: " + maxD + "ms\tDecryption Bps: " + (times*message.length*1000)/decrypttime);
}
}

View File

@ -1,76 +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 junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
import net.i2p.util.RandomSource;
/**
* @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));
}
}

View File

@ -1,470 +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 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;
/**
* This reads an underlying stream as written by AESOutputStream - AES256 encrypted
* in CBC mode with PKCS#5 padding, with the padding on each and every block of
* 16 bytes. This minimizes the overhead when communication is intermittent,
* rather than when streams of large sets of data are sent (in which case, the
* padding would be on a larger size - say, 1k, though in the worst case that
* would have 1023 bytes of padding, while in the worst case here, we only have
* 15 bytes of padding). So we have an expansion factor of 6.25%. c'est la vie
*
*/
public class AESInputStream extends FilterInputStream {
private Log _log;
private I2PAppContext _context;
private SessionKey _key;
private byte[] _lastBlock;
private boolean _eofFound;
private long _cumulativeRead; // how many read from the source stream
private long _cumulativePrepared; // how many bytes decrypted and added to _readyBuf
private long _cumulativePaddingStripped; // how many bytes have been stripped
/** read but not yet decrypted */
private byte _encryptedBuf[];
/** how many bytes have been added to the encryptedBuf since it was decrypted? */
private int _writesSinceDecrypt;
/** decrypted bytes ready for reading (first available == index of 0) */
private int _decryptedBuf[];
/** how many bytes are available for reading without decrypt? */
private int _decryptedSize;
private final static int BLOCK_SIZE = CryptixRijndael_Algorithm._BLOCK_SIZE;
public AESInputStream(I2PAppContext context, InputStream source, SessionKey key, byte[] iv) {
super(source);
_context = context;
_log = context.logManager().getLog(AESInputStream.class);
_key = key;
_lastBlock = new byte[BLOCK_SIZE];
System.arraycopy(iv, 0, _lastBlock, 0, BLOCK_SIZE);
_encryptedBuf = new byte[BLOCK_SIZE];
_writesSinceDecrypt = 0;
_decryptedBuf = new int[BLOCK_SIZE-1];
_decryptedSize = 0;
_cumulativePaddingStripped = 0;
_eofFound = false;
}
@Override
public int read() throws IOException {
while ((!_eofFound) && (_decryptedSize <= 0)) {
refill();
}
if (_decryptedSize > 0) {
int c = _decryptedBuf[0];
System.arraycopy(_decryptedBuf, 1, _decryptedBuf, 0, _decryptedBuf.length-1);
_decryptedSize--;
return c;
} else if (_eofFound) {
return -1;
} else {
throw new IOException("Not EOF, but none available? " + _decryptedSize
+ "/" + _writesSinceDecrypt
+ "/" + _cumulativeRead + "... impossible");
}
}
@Override
public int read(byte dest[]) throws IOException {
return read(dest, 0, dest.length);
}
@Override
public int read(byte dest[], int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
int val = read();
if (val == -1) {
// no more to read... can they expect more?
if (_eofFound && (i == 0)) {
if (_log.shouldLog(Log.DEBUG))
_log.info("EOF? " + _eofFound
+ "\nread=" + i + " decryptedSize=" + _decryptedSize
+ " \nencryptedSize=" + _writesSinceDecrypt
+ " \ntotal=" + _cumulativeRead
+ " \npadding=" + _cumulativePaddingStripped
+ " \nprepared=" + _cumulativePrepared);
return -1;
} else {
if (i != len)
if (_log.shouldLog(Log.DEBUG))
_log.info("non-terminal eof: " + _eofFound + " i=" + i + " len=" + len);
}
return i;
}
dest[off+i] = (byte)val;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Read the full buffer of size " + len);
return len;
}
@Override
public long skip(long numBytes) throws IOException {
for (long l = 0; l < numBytes; l++) {
int val = read();
if (val == -1) return l;
}
return numBytes;
}
@Override
public int available() throws IOException {
return _decryptedSize;
}
@Override
public void close() throws IOException {
in.close();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Cumulative bytes read from source/decrypted/stripped: " + _cumulativeRead + "/"
+ _cumulativePrepared + "/" + _cumulativePaddingStripped + "] remaining [" + _decryptedSize + " ready, "
+ _writesSinceDecrypt + " still encrypted]");
}
@Override
public void mark(int readLimit) { // nop
}
@Override
public void reset() throws IOException {
throw new IOException("Reset not supported");
}
@Override
public boolean markSupported() {
return false;
}
/**
* Read at least one new byte from the underlying stream, and up to max new bytes,
* but not necessarily enough for a new decrypted block. This blocks until at least
* one new byte is read from the stream
*
*/
private void refill() throws IOException {
if ( (!_eofFound) && (_writesSinceDecrypt < BLOCK_SIZE) ) {
int read = in.read(_encryptedBuf, _writesSinceDecrypt, _encryptedBuf.length - _writesSinceDecrypt);
if (read == -1) {
_eofFound = true;
} else if (read > 0) {
_cumulativeRead += read;
_writesSinceDecrypt += read;
}
}
if (_writesSinceDecrypt == BLOCK_SIZE) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("We have " + _writesSinceDecrypt + " available to decrypt... doing so");
decryptBlock();
if ( (_writesSinceDecrypt > 0) && (_log.shouldLog(Log.DEBUG)) )
_log.debug("Bytes left in the encrypted buffer after decrypt: "
+ _writesSinceDecrypt);
}
}
/**
* Decrypt the
*/
private void decryptBlock() throws IOException {
if (_writesSinceDecrypt != BLOCK_SIZE)
throw new IOException("Error decrypting - no data to decrypt");
if (_decryptedSize != 0)
throw new IOException("wtf, decrypted size is not 0? " + _decryptedSize);
_context.aes().decrypt(_encryptedBuf, 0, _encryptedBuf, 0, _key, _lastBlock, BLOCK_SIZE);
DataHelper.xor(_encryptedBuf, 0, _lastBlock, 0, _encryptedBuf, 0, BLOCK_SIZE);
int payloadBytes = countBlockPayload(_encryptedBuf, 0);
for (int i = 0; i < payloadBytes; i++) {
int c = _encryptedBuf[i];
if (c <= 0)
c += 256;
_decryptedBuf[i] = c;
}
_decryptedSize = payloadBytes;
_cumulativePaddingStripped += BLOCK_SIZE - payloadBytes;
_cumulativePrepared += payloadBytes;
System.arraycopy(_encryptedBuf, 0, _lastBlock, 0, BLOCK_SIZE);
_writesSinceDecrypt = 0;
}
/**
* How many non-padded bytes are there in the block starting at the given
* location.
*
* PKCS#5 specifies the padding for the block has the # of padding bytes
* located in the last byte of the block, and each of the padding bytes are
* equal to that value.
* e.g. in a 4 byte block:
* 0x0a padded would become
* 0x0a 0x03 0x03 0x03
* e.g. in a 4 byte block:
* 0x01 0x02 padded would become
* 0x01 0x02 0x02 0x02
*
* We use 16 byte blocks in this AES implementation
*
* @throws IOException if the padding is invalid
*/
private int countBlockPayload(byte data[], int startIndex) throws IOException {
int numPadBytes = data[startIndex + BLOCK_SIZE - 1];
if ((numPadBytes >= BLOCK_SIZE) || (numPadBytes <= 0)) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("countBlockPayload on block index " + startIndex
+ numPadBytes + " is an invalid # of pad bytes");
throw new IOException("Invalid number of pad bytes (" + numPadBytes
+ ") for " + startIndex + " index");
}
// optional, but a really good idea: verify the padding
if (true) {
for (int i = BLOCK_SIZE - numPadBytes; i < BLOCK_SIZE; i++) {
if (data[startIndex + i] != (byte) numPadBytes) {
throw new IOException("Incorrect padding on decryption: data[" + i
+ "] = " + data[startIndex + i] + " not " + numPadBytes);
}
}
}
return BLOCK_SIZE - numPadBytes;
}
int remainingBytes() {
return _writesSinceDecrypt;
}
int readyBytes() {
return _decryptedSize;
}
/**
* Test AESOutputStream/AESInputStream
*/
public static void main(String args[]) {
I2PAppContext ctx = new I2PAppContext();
try {
System.out.println("pwd=" + new java.io.File(".").getAbsolutePath());
System.out.println("Beginning");
runTest(ctx);
} catch (Throwable e) {
ctx.logManager().getLog(AESInputStream.class).error("Fail", e);
}
try { Thread.sleep(30*1000); } catch (InterruptedException ie) {}
System.out.println("Done");
}
private static void runTest(I2PAppContext ctx) {
Log log = ctx.logManager().getLog(AESInputStream.class);
log.setMinimumPriority(Log.DEBUG);
byte orig[] = new byte[1024 * 32];
RandomSource.getInstance().nextBytes(orig);
//byte orig[] = "you are my sunshine, my only sunshine".getBytes();
SessionKey key = KeyGenerator.getInstance().generateSessionKey();
byte iv[] = "there once was a".getBytes();
for (int i = 0; i < 20; i++) {
runTest(ctx, orig, key, iv);
}
log.info("Done testing 32KB data");
orig = new byte[20];
RandomSource.getInstance().nextBytes(orig);
for (int i = 0; i < 20; i++) {
runTest(ctx, orig, key, iv);
}
log.info("Done testing 20 byte data");
orig = new byte[3];
RandomSource.getInstance().nextBytes(orig);
for (int i = 0; i < 20; i++) {
runTest(ctx, orig, key, iv);
}
log.info("Done testing 3 byte data");
orig = new byte[0];
RandomSource.getInstance().nextBytes(orig);
for (int i = 0; i < 20; i++) {
runTest(ctx, orig, key, iv);
}
log.info("Done testing 0 byte data");
for (int i = 0; i <= 32768; i++) {
orig = new byte[i];
ctx.random().nextBytes(orig);
try {
log.info("Testing " + orig.length);
runTest(ctx, orig, key, iv);
} catch (RuntimeException re) {
log.error("Error testing " + orig.length);
throw re;
}
}
/*
orig = new byte[615280];
RandomSource.getInstance().nextBytes(orig);
for (int i = 0; i < 20; i++) {
runTest(ctx, orig, key, iv);
}
log.info("Done testing 615280 byte data");
*/
/*
for (int i = 0; i < 100; i++) {
orig = new byte[ctx.random().nextInt(1024*1024)];
ctx.random().nextBytes(orig);
try {
runTest(ctx, orig, key, iv);
} catch (RuntimeException re) {
log.error("Error testing " + orig.length);
throw re;
}
}
log.info("Done testing 100 random lengths");
*/
orig = new byte[32];
RandomSource.getInstance().nextBytes(orig);
try {
runOffsetTest(ctx, orig, key, iv);
} catch (Exception e) {
log.info("Error running offset test", e);
}
log.info("Done testing offset test (it should have come back with a statement NOT EQUAL!)");
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException ie) { // nop
}
}
private static void runTest(I2PAppContext ctx, byte orig[], SessionKey key, byte[] iv) {
Log log = ctx.logManager().getLog(AESInputStream.class);
try {
long start = Clock.getInstance().now();
ByteArrayOutputStream origStream = new ByteArrayOutputStream(512);
AESOutputStream out = new AESOutputStream(ctx, origStream, key, iv);
out.write(orig);
out.close();
byte encrypted[] = origStream.toByteArray();
long endE = Clock.getInstance().now();
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();
long end = Clock.getInstance().now();
Hash origHash = SHA256Generator.getInstance().calculateHash(orig);
Hash newHash = SHA256Generator.getInstance().calculateHash(fin);
boolean eq = origHash.equals(newHash);
if (eq) {
//log.info("Equal hashes. hash: " + origHash);
} else {
throw new RuntimeException("NOT EQUAL! len=" + orig.length + " read=" + read
+ "\norig: \t" + Base64.encode(orig) + "\nnew : \t"
+ Base64.encode(fin));
}
boolean ok = DataHelper.eq(orig, fin);
log.debug("EQ data? " + ok + " origLen: " + orig.length + " fin.length: " + fin.length);
log.debug("Time to D(E(" + orig.length + ")): " + (end - start) + "ms");
log.debug("Time to E(" + orig.length + "): " + (endE - start) + "ms");
log.debug("Time to D(" + orig.length + "): " + (end - endE) + "ms");
} catch (IOException ioe) {
log.error("ERROR transferring", ioe);
}
//try { Thread.sleep(5000); } catch (Throwable t) {}
}
private static void runOffsetTest(I2PAppContext ctx, byte orig[], SessionKey key, byte[] iv) {
Log log = ctx.logManager().getLog(AESInputStream.class);
try {
long start = Clock.getInstance().now();
ByteArrayOutputStream origStream = new ByteArrayOutputStream(512);
AESOutputStream out = new AESOutputStream(ctx, origStream, key, iv);
out.write(orig);
out.close();
byte encrypted[] = origStream.toByteArray();
long endE = Clock.getInstance().now();
log.info("Encrypted segment length: " + encrypted.length);
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();
log.info("Read: " + read);
if (read > 0) baos.write(buf, 0, read);
sin.close();
byte fin[] = baos.toByteArray();
log.info("fin.length: " + fin.length + " remaining: " + remaining + " ready: " + readyBytes);
long end = Clock.getInstance().now();
Hash origHash = SHA256Generator.getInstance().calculateHash(orig);
Hash newHash = SHA256Generator.getInstance().calculateHash(fin);
boolean eq = origHash.equals(newHash);
if (eq)
log.info("Equal hashes. hash: " + origHash);
else
throw new RuntimeException("NOT EQUAL! len=" + orig.length + "\norig: \t" + Base64.encode(orig) + "\nnew : \t" + Base64.encode(fin));
boolean ok = DataHelper.eq(orig, fin);
log.debug("EQ data? " + ok + " origLen: " + orig.length + " fin.length: " + fin.length);
log.debug("Time to D(E(" + orig.length + ")): " + (end - start) + "ms");
log.debug("Time to E(" + orig.length + "): " + (endE - start) + "ms");
log.debug("Time to D(" + orig.length + "): " + (end - endE) + "ms");
} catch (RuntimeException re) {
throw re;
} catch (IOException ioe) {
log.error("ERROR transferring", ioe);
}
//try { Thread.sleep(5000); } catch (Throwable t) {}
}
}

View File

@ -1,104 +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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.util.RandomSource;
/**
* @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));
}
}

View File

@ -1,152 +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 java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
import net.i2p.util.Log;
/**
* This writes everything as CBC with PKCS#5 padding, but each block is padded
* so as soon as a block is received it can be decrypted (rather than wait for
* an arbitrary number of blocks to arrive). That means that each block sent
* will contain exactly one padding byte (unless it was flushed with
* numBytes % (BLOCK_SIZE-1) != 0, in which case that last block will be padded
* with up to 15 bytes). So we have an expansion factor of 6.25%. c'est la vie
*
*/
public class AESOutputStream extends FilterOutputStream {
private Log _log;
private I2PAppContext _context;
private SessionKey _key;
private byte[] _lastBlock;
/**
* buffer containing the unwritten bytes. The first unwritten
* byte is _lastCommitted+1, and the last unwritten byte is _nextWrite-1
* (aka the next byte to be written on the array is _nextWrite)
*/
private byte[] _unencryptedBuf;
private byte _writeBlock[];
/** how many bytes have we been given since we flushed it to the stream? */
private int _writesSinceCommit;
private long _cumulativeProvided; // how many bytes provided to this stream
private long _cumulativeWritten; // how many bytes written to the underlying stream
private long _cumulativePadding; // how many bytes of padding written
public final static float EXPANSION_FACTOR = 1.0625f; // 6% overhead w/ the padding
private final static int BLOCK_SIZE = CryptixRijndael_Algorithm._BLOCK_SIZE;
private final static int MAX_BUF = 256;
public AESOutputStream(I2PAppContext context, OutputStream source, SessionKey key, byte[] iv) {
super(source);
_context = context;
_log = context.logManager().getLog(AESOutputStream.class);
_key = key;
_lastBlock = new byte[BLOCK_SIZE];
System.arraycopy(iv, 0, _lastBlock, 0, BLOCK_SIZE);
_unencryptedBuf = new byte[MAX_BUF];
_writeBlock = new byte[BLOCK_SIZE];
_writesSinceCommit = 0;
}
@Override
public void write(int val) throws IOException {
_cumulativeProvided++;
_unencryptedBuf[_writesSinceCommit++] = (byte)(val & 0xFF);
if (_writesSinceCommit == _unencryptedBuf.length)
doFlush();
}
@Override
public void write(byte src[]) throws IOException {
write(src, 0, src.length);
}
@Override
public void write(byte src[], int off, int len) throws IOException {
// i'm too lazy to unroll this into the partial writes (dealing with
// wrapping around the buffer size)
for (int i = 0; i < len; i++)
write(src[i+off]);
}
@Override
public void close() throws IOException {
flush();
out.close();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Cumulative bytes provided to this stream / written out / padded: "
+ _cumulativeProvided + "/" + _cumulativeWritten + "/" + _cumulativePadding);
}
@Override
public void flush() throws IOException {
doFlush();
out.flush();
}
private void doFlush() throws IOException {
if (_log.shouldLog(Log.INFO))
_log.info("doFlush(): writesSinceCommit=" + _writesSinceCommit);
writeEncrypted();
_writesSinceCommit = 0;
}
/**
* Encrypt an arbitrary size array with AES using CBC and PKCS#5 padding,
* write it to the stream, and set _lastBlock to the last encrypted
* block. This operation works by taking every (BLOCK_SIZE-1) bytes
* from the src, padding it with PKCS#5 (aka adding 0x01), and encrypting
* it. If the last block doesn't contain exactly (BLOCK_SIZE-1) bytes, it
* is padded with PKCS#5 as well (adding # padding bytes repeated that many
* times).
*
*/
private void writeEncrypted() throws IOException {
int numBlocks = _writesSinceCommit / (BLOCK_SIZE - 1);
if (_log.shouldLog(Log.INFO))
_log.info("writeE(): #=" + _writesSinceCommit + " blocks=" + numBlocks);
for (int i = 0; i < numBlocks; i++) {
DataHelper.xor(_unencryptedBuf, i * 15, _lastBlock, 0, _writeBlock, 0, 15);
// the padding byte for "full" blocks
_writeBlock[BLOCK_SIZE - 1] = (byte)(_lastBlock[BLOCK_SIZE - 1] ^ 0x01);
_context.aes().encrypt(_writeBlock, 0, _writeBlock, 0, _key, _lastBlock, BLOCK_SIZE);
out.write(_writeBlock);
System.arraycopy(_writeBlock, 0, _lastBlock, 0, BLOCK_SIZE);
_cumulativeWritten += BLOCK_SIZE;
_cumulativePadding++;
}
if (_writesSinceCommit % 15 != 0) {
// we need to do non trivial padding
int remainingBytes = _writesSinceCommit - numBlocks * 15;
int paddingBytes = BLOCK_SIZE - remainingBytes;
if (_log.shouldLog(Log.DEBUG))
_log.debug("Padding " + _writesSinceCommit + " with " + paddingBytes + " bytes in " + (numBlocks+1) + " blocks");
System.arraycopy(_unencryptedBuf, numBlocks * 15, _writeBlock, 0, remainingBytes);
Arrays.fill(_writeBlock, remainingBytes, BLOCK_SIZE, (byte) paddingBytes);
DataHelper.xor(_writeBlock, 0, _lastBlock, 0, _writeBlock, 0, BLOCK_SIZE);
_context.aes().encrypt(_writeBlock, 0, _writeBlock, 0, _key, _lastBlock, BLOCK_SIZE);
out.write(_writeBlock);
System.arraycopy(_writeBlock, 0, _lastBlock, 0, BLOCK_SIZE);
_cumulativePadding += paddingBytes;
_cumulativeWritten += BLOCK_SIZE;
}
}
}

View File

@ -1,112 +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 junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
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));
}
}

View File

@ -1,42 +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 junit.framework.TestCase;
import net.i2p.data.DataHelper;
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));
}
}
}

View File

@ -1,37 +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 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(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;
}
}

View File

@ -1,100 +0,0 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the TheCrypto may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.ByteArrayInputStream;
import net.i2p.data.Signature;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
public class DSABench {
public static void main(String args[]) {
int times = 100;
long keygentime = 0;
long signtime = 0;
long verifytime = 0;
long maxKey = 0;
long minKey = 0;
long maxS = 0;
long minS = 0;
long maxV = 0;
long minV = 0;
Object[] keys = KeyGenerator.getInstance().generateSigningKeypair();
byte[] message = new byte[32+32];
for (int i = 0; i < message.length; i++)
message[i] = (byte)((i%26)+'a');
for (int x = 0; x < times; x++) {
long startkeys = System.currentTimeMillis();
keys = KeyGenerator.getInstance().generateSigningKeypair();
SigningPublicKey pubkey = (SigningPublicKey)keys[0];
SigningPrivateKey privkey = (SigningPrivateKey)keys[1];
long endkeys = System.currentTimeMillis();
long startsign = System.currentTimeMillis();
Signature s = DSAEngine.getInstance().sign(message, privkey);
Signature s1 = DSAEngine.getInstance().sign(new ByteArrayInputStream(message), privkey);
long endsignstartverify = System.currentTimeMillis();
boolean v = DSAEngine.getInstance().verifySignature(s, message, pubkey);
boolean v1 = DSAEngine.getInstance().verifySignature(s1, new ByteArrayInputStream(message), pubkey);
boolean v2 = DSAEngine.getInstance().verifySignature(s1, message, pubkey);
boolean v3 = DSAEngine.getInstance().verifySignature(s, new ByteArrayInputStream(message), pubkey);
long endverify = System.currentTimeMillis();
System.out.print(".");
keygentime += endkeys - startkeys;
signtime += endsignstartverify - startsign;
verifytime += endverify - endsignstartverify;
if (!v) {
throw new RuntimeException("Holy crap, did not verify");
}
if (!(v1 && v2 && v3))
throw new RuntimeException("Stream did not verify");
if ( (minKey == 0) && (minS == 0) && (minV == 0) ) {
minKey = endkeys - startkeys;
maxKey = endkeys - startkeys;
minS = endsignstartverify - startsign;
maxS = endsignstartverify - startsign;
minV = endverify - endsignstartverify;
maxV = endverify - endsignstartverify;
} else {
if (minKey > endkeys - startkeys) minKey = endkeys - startkeys;
if (maxKey < endkeys - startkeys) maxKey = endkeys - startkeys;
if (minS > endsignstartverify - startsign) minS = endsignstartverify - startsign;
if (maxS < endsignstartverify - startsign) maxS = endsignstartverify - startsign;
if (minV > endverify - endsignstartverify) minV = endverify - endsignstartverify;
if (maxV < endverify - endsignstartverify) maxV = endverify - endsignstartverify;
}
}
System.out.println();
System.out.println("Key Generation Time Average: " + (keygentime/times) + "\ttotal: " + keygentime + "\tmin: " + minKey + "\tmax: " + maxKey + "\tKeygen/second: " + (keygentime == 0 ? "NaN" : ""+(times*1000)/keygentime));
System.out.println("Signing Time Average : " + (signtime/times) + "\ttotal: " + signtime + "\tmin: " + minS + "\tmax: " + maxS + "\tSigning Bps: " + (times*message.length*1000)/signtime);
System.out.println("Verification Time Average : " + (verifytime/times) + "\ttotal: " + verifytime + "\tmin: " + minV + "\tmax: " + maxV + "\tDecryption Bps: " + (times*message.length*1000)/verifytime);
}
}

View File

@ -1,44 +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 java.io.ByteArrayInputStream;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.Signature;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
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));
}
}
}

View File

@ -1,108 +0,0 @@
package net.i2p.crypto;
import java.util.Random;
import net.i2p.I2PAppContext;
import net.i2p.util.PooledRandomSource;
import net.i2p.util.RandomSource;
/**
*
*/
public class DummyPooledRandomSource extends PooledRandomSource {
public DummyPooledRandomSource(I2PAppContext context) {
super(context);
}
@Override
protected void initializePool(I2PAppContext context) {
_pool = new RandomSource[POOL_SIZE];
for (int i = 0; i < POOL_SIZE; i++) {
_pool[i] = new DummyRandomSource(context);
_pool[i].nextBoolean();
}
_nextPool = 0;
}
private class DummyRandomSource extends RandomSource {
private Random _prng;
public DummyRandomSource(I2PAppContext context) {
super(context);
// when we replace to have hooks for fortuna (etc), replace with
// a factory (or just a factory method)
_prng = new Random();
}
/**
* According to the java docs (http://java.sun.com/j2se/1.4.1/docs/api/java/util/Random.html#nextInt(int))
* nextInt(n) should return a number between 0 and n (including 0 and excluding n). However, their pseudocode,
* as well as sun's, kaffe's, and classpath's implementation INCLUDES NEGATIVE VALUES.
* WTF. Ok, so we're going to have it return between 0 and n (including 0, excluding n), since
* thats what it has been used for.
*
*/
@Override
public int nextInt(int n) {
if (n == 0) return 0;
int val = _prng.nextInt(n);
if (val < 0) val = 0 - val;
if (val >= n) val = val % n;
return val;
}
/**
* Like the modified nextInt, nextLong(n) returns a random number from 0 through n,
* including 0, excluding n.
*/
@Override
public long nextLong(long n) {
long v = _prng.nextLong();
if (v < 0) v = 0 - v;
if (v >= n) v = v % n;
return v;
}
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public boolean nextBoolean() { return _prng.nextBoolean(); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public void nextBytes(byte buf[]) { _prng.nextBytes(buf); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public double nextDouble() { return _prng.nextDouble(); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public float nextFloat() { return _prng.nextFloat(); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public double nextGaussian() { return _prng.nextGaussian(); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public int nextInt() { return _prng.nextInt(); }
/**
* override as synchronized, for those JVMs that don't always pull via
* nextBytes (cough ibm)
*/
@Override
public long nextLong() { return _prng.nextLong(); }
}
}

View File

@ -1,98 +0,0 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the TheCrypto may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
public class ElGamalBench {
private static I2PAppContext _context = new I2PAppContext();
public static void main(String args[]) {
int times = 100;
long keygentime = 0;
long encrypttime = 0;
long decrypttime = 0;
long maxKey = 0;
long minKey = 0;
long maxE = 0;
long minE = 0;
long maxD = 0;
long minD = 0;
Object[] keys = KeyGenerator.getInstance().generatePKIKeypair();
byte[] message = new byte[222];
for (int i = 0; i < message.length; i++)
message[i] = (byte)((i%26)+'a');
for (int x = 0; x < times; x++) {
long startkeys = System.currentTimeMillis();
keys = KeyGenerator.getInstance().generatePKIKeypair();
PublicKey pubkey = (PublicKey)keys[0];
PrivateKey privkey = (PrivateKey)keys[1];
long endkeys = System.currentTimeMillis();
long startencrypt = System.currentTimeMillis();
byte[] e = _context.elGamalEngine().encrypt(message, pubkey);
long endencryptstartdecrypt = System.currentTimeMillis();
byte[] d = _context.elGamalEngine().decrypt(e, privkey);
long enddecrypt = System.currentTimeMillis();
System.out.print(".");
keygentime += endkeys - startkeys;
encrypttime += endencryptstartdecrypt - startencrypt;
decrypttime += enddecrypt - endencryptstartdecrypt;
if (!DataHelper.eq(d, message)) {
System.out.println("Lengths: source [" + message.length + "] dest [" + d.length + "]");
byte hash1[] = SHA256Generator.getInstance().calculateHash(message).getData();
byte hash2[] = SHA256Generator.getInstance().calculateHash(d).getData();
System.out.println("Hashes: source [" + DataHelper.toString(hash1, hash1.length) + "] dest [" + DataHelper.toString(hash2, hash2.length) + "]");
throw new RuntimeException("Holy crap, decrypted != source message");
}
if ( (minKey == 0) && (minE == 0) && (minD == 0) ) {
minKey = endkeys - startkeys;
maxKey = endkeys - startkeys;
minE = endencryptstartdecrypt - startencrypt;
maxE = endencryptstartdecrypt - startencrypt;
minD = enddecrypt - endencryptstartdecrypt;
maxD = enddecrypt - endencryptstartdecrypt;
} else {
if (minKey > endkeys - startkeys) minKey = endkeys - startkeys;
if (maxKey < endkeys - startkeys) maxKey = endkeys - startkeys;
if (minE > endencryptstartdecrypt - startencrypt) minE = endencryptstartdecrypt - startencrypt;
if (maxE < endencryptstartdecrypt - startencrypt) maxE = endencryptstartdecrypt - startencrypt;
if (minD > enddecrypt - endencryptstartdecrypt) minD = enddecrypt - endencryptstartdecrypt;
if (maxD < enddecrypt - endencryptstartdecrypt) maxD = enddecrypt - endencryptstartdecrypt;
}
}
System.out.println();
System.out.println("Key Generation Time Average: " + (keygentime/times) + "\ttotal: " + keygentime + "\tmin: " + minKey + "\tmax: " + maxKey + "\tKeygen/second: " + (keygentime == 0 ? "NaN" : ""+(times*1000)/keygentime));
System.out.println("Encryption Time Average : " + (encrypttime/times) + "\ttotal: " + encrypttime + "\tmin: " + minE + "\tmax: " + maxE + "\tEncryption Bps: " + (times*message.length*1000)/encrypttime);
System.out.println("Decryption Time Average : " + (decrypttime/times) + "\ttotal: " + decrypttime + "\tmin: " + minD + "\tmax: " + maxD + "\tDecryption Bps: " + (times*message.length*1000)/decrypttime);
}
}

View File

@ -1,381 +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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.Base64;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
import net.i2p.util.RandomSource;
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();
I2PAppContext context = new I2PAppContext();
YKGenerator ykgen = new YKGenerator(context);
for (int i = 0; i < 5; i++) {
ykgen.getNextYK();
}
}
}

View File

@ -1,117 +0,0 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the TheCrypto may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Properties;
import net.i2p.I2PAppContext;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
public class HMACSHA256Bench {
public static void main(String args[]) {
runTest(new I2PAppContext());
System.out.println("Running as MD5");
Properties props = new Properties();
//props.setProperty("i2p.fakeHMAC", "true");
props.setProperty("i2p.HMACMD5", "true");
runTest(new I2PAppContext(props));
}
private static void runTest(I2PAppContext ctx) {
SessionKey key = ctx.keyGenerator().generateSessionKey();
Hash asdfs = ctx.hmac().calculate(key, "qwerty".getBytes());
int times = 100000;
long shorttime = 0;
long medtime = 0;
long longtime = 0;
long minShort = 0;
long maxShort = 0;
long minMed = 0;
long maxMed = 0;
long minLong = 0;
long maxLong = 0;
long shorttime1 = 0;
long medtime1 = 0;
long longtime1 = 0;
long minShort1 = 0;
long maxShort1 = 0;
long minMed1 = 0;
long maxMed1 = 0;
long minLong1 = 0;
long maxLong1 = 0;
byte[] smess = new String("abc").getBytes();
StringBuilder buf = new StringBuilder();
for (int x = 0; x < 2*1024; x++) {
buf.append("a");
}
byte[] mmess = buf.toString().getBytes(); // new String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq").getBytes();
buf = new StringBuilder();
for (int x = 0; x < 10000; x++) {
buf.append("a");
}
byte[] lmess = buf.toString().getBytes();
// warm up the engines
ctx.hmac().calculate(key, smess);
ctx.hmac().calculate(key, mmess);
ctx.hmac().calculate(key, lmess);
long before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
ctx.hmac().calculate(key, smess);
long after = System.currentTimeMillis();
display(times, before, after, smess.length, "3 byte");
before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
ctx.hmac().calculate(key, mmess);
after = System.currentTimeMillis();
display(times, before, after, mmess.length, "2KB");
before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
ctx.hmac().calculate(key, lmess);
after = System.currentTimeMillis();
display(times, before, after, lmess.length, "10KB");
}
private static void display(int times, long before, long after, int len, String name) {
double rate = times/(((double)after-(double)before)/1000.0d);
double kbps = (len/1024.0d)*times/(((double)after-(double)before)/1000.0d);
System.out.println(name + " HMAC pulled " + kbps + "KBps or " + rate + " calcs per second");
}
}

View File

@ -1,34 +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 junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.SessionKey;
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);
}
}
}

View File

@ -1,49 +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 junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.Signature;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.util.RandomSource;
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();
}
}
}

View File

@ -1,146 +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.
*
*/
/* @(#)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.MessageDigest;
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) {
StringBuilder buf = new StringBuilder(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";
}

View File

@ -1,113 +0,0 @@
package net.i2p.crypto;
/*
* Copyright (c) 2003, TheCrypto
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the TheCrypto may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import net.i2p.data.Hash;
public class SHA256Bench {
public static void main(String args[]) {
Hash asdfs = SHA256Generator.getInstance().calculateHash("qwerty".getBytes());
int times = 100;
long shorttime = 0;
long medtime = 0;
long longtime = 0;
long minShort = 0;
long maxShort = 0;
long minMed = 0;
long maxMed = 0;
long minLong = 0;
long maxLong = 0;
long shorttime1 = 0;
long medtime1 = 0;
long longtime1 = 0;
long minShort1 = 0;
long maxShort1 = 0;
long minMed1 = 0;
long maxMed1 = 0;
long minLong1 = 0;
long maxLong1 = 0;
byte[] smess = new String("abc").getBytes();
StringBuilder buf = new StringBuilder();
for (int x = 0; x < 10*1024; x++) {
buf.append("a");
}
byte[] mmess = buf.toString().getBytes(); // new String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq").getBytes();
buf = new StringBuilder();
for (int x = 0; x < 1000000; x++) {
buf.append("a");
}
byte[] lmess = buf.toString().getBytes();
// warm up the engines
SHA256Generator.getInstance().calculateHash(smess);
SHA256Generator.getInstance().calculateHash(mmess);
SHA256Generator.getInstance().calculateHash(lmess);
// now do it
for (int x = 0; x < times; x++) {
long startshort = System.currentTimeMillis();
boolean cacheOnly = false;
// no caching
Hash s = cacheOnly ? null : SHA256Generator.getInstance().calculateHash(smess);
long endshortstartmed = System.currentTimeMillis();
Hash m = cacheOnly ? null : SHA256Generator.getInstance().calculateHash(mmess);
long endmedstartlong = System.currentTimeMillis();
Hash l = cacheOnly ? null : SHA256Generator.getInstance().calculateHash(lmess);
long endlong = System.currentTimeMillis();
shorttime += endshortstartmed - startshort;
medtime += endmedstartlong - endshortstartmed;
longtime += endlong - endmedstartlong;
if ((minShort == 0) && (minMed == 0) && (minLong == 0) ) {
minShort = endshortstartmed - startshort;
maxShort = endshortstartmed - startshort;
minMed = endmedstartlong - endshortstartmed;
maxMed = endmedstartlong - endshortstartmed;
minLong = endlong - endmedstartlong;
maxLong = endlong - endmedstartlong;
} else {
if (minShort > endshortstartmed - startshort) minShort = endshortstartmed - startshort;
if (maxShort < endshortstartmed - startshort) maxShort = endshortstartmed - startshort;
if (minMed > endmedstartlong - endshortstartmed) minMed = endmedstartlong - endshortstartmed;
if (maxMed < endmedstartlong - endshortstartmed) maxMed = endmedstartlong - endshortstartmed;
if (minLong > endlong - endmedstartlong) minLong = endlong - endmedstartlong;
if (maxLong < endlong - endmedstartlong) maxLong = endlong - endmedstartlong;
}
}
System.out.println();
System.out.println("Short Message Time Average : " + (shorttime/times) + "\ttotal: " + shorttime + "\tmin: " + minShort + "\tmax: " + maxShort + "\tBps: " + (shorttime == 0 ? "NaN" : ""+(times*smess.length)/shorttime));
System.out.println("Medium Message Time Average : " + (medtime/times) + "\ttotal: " + medtime + "\tmin: " + minMed + "\tmax: " + maxMed + "\tBps: " + (medtime == 0 ? "NaN" : ""+(times*mmess.length*1000)/medtime));
System.out.println("Long Message Time Average : " + (longtime/times) + "\ttotal: " + longtime + "\tmin: " + minLong + "\tmax: " + maxLong + "\tBps: " + (longtime == 0 ? "NaN" : "" + (times*lmess.length*1000)/longtime));
}
}

View File

@ -1,50 +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 junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
/**
* @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);
}
}
/**
* Check if the behaviour remains the same.
*/
public void testMultipleEquality(){
byte[] data = "blahblah".getBytes();
Hash firstHash = SHA256Generator.getInstance().calculateHash(data);
for(int i=0; i<5; i++){
Hash h = SHA256Generator.getInstance().calculateHash(data);
assertEquals(firstHash, h);
}
}
}

View File

@ -1,311 +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 java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SessionTag;
/**
*
* session key management unit tests:
*
*/
public class SessionEncryptionTest extends TestCase{
private static I2PAppContext _context = new I2PAppContext();
protected void setUp(){
_context = new I2PAppContext();
}
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[] msg = "msg 1".getBytes();
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[] 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));
}
/**
* Run tagsIncluded useTag rekey
* 1 yes (2) no no
* 2 no yes no
* 3 yes (2) yes no
* 4 no yes no
* 5 no yes no
*/
public void testSessions() throws Exception{
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
PublicKey pubKey = (PublicKey)keys[0];
PrivateKey privKey = (PrivateKey)keys[1];
SessionKey curKey = _context.sessionKeyManager().createSession(pubKey);
SessionTag tag1 = new SessionTag(true);
SessionTag tag2 = new SessionTag(true);
SessionTag tag3 = new SessionTag(true);
SessionTag tag4 = new SessionTag(true);
HashSet firstTags = new HashSet();
firstTags.add(tag1);
firstTags.add(tag2);
HashSet secondTags = new HashSet();
secondTags.add(tag3);
secondTags.add(tag4);
byte[] msg1 = "msg 1".getBytes();
byte[] msg2 = "msg 2".getBytes();
byte[] msg3 = "msg 3".getBytes();
byte[] msg4 = "msg 4".getBytes();
byte[] msg5 = "msg 5".getBytes();
byte emsg1[] = _context.elGamalAESEngine().encrypt(msg1, pubKey, curKey, firstTags, 64);
byte dmsg1[] = _context.elGamalAESEngine().decrypt(emsg1, privKey);
assertTrue(DataHelper.eq(dmsg1, msg1));
TagSetHandle tsh = _context.sessionKeyManager().tagsDelivered(pubKey, curKey, firstTags);
_context.sessionKeyManager().tagsAcked(pubKey, curKey, tsh);
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
SessionTag curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
byte emsg2[] = _context.elGamalAESEngine().encrypt(msg2, pubKey, curKey, null, curTag, 64);
byte dmsg2[] = _context.elGamalAESEngine().decrypt(emsg2, privKey);
assertTrue(DataHelper.eq(dmsg2, msg2));
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg3[] = _context.elGamalAESEngine().encrypt(msg3, pubKey, curKey, secondTags, curTag, 64);
byte dmsg3[] = _context.elGamalAESEngine().decrypt(emsg3, privKey);
assertTrue(DataHelper.eq(dmsg3, msg3));
tsh = _context.sessionKeyManager().tagsDelivered(pubKey, curKey, secondTags);
_context.sessionKeyManager().tagsAcked(pubKey, curKey, tsh);
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg4[] = _context.elGamalAESEngine().encrypt(msg4, pubKey, curKey, null, curTag, 64);
byte dmsg4[] = _context.elGamalAESEngine().decrypt(emsg4, privKey);
assertTrue(DataHelper.eq(dmsg4, msg4));
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg5[] = _context.elGamalAESEngine().encrypt(msg5, pubKey, curKey, null, curTag, 64);
byte dmsg5[] = _context.elGamalAESEngine().decrypt(emsg5, privKey);
assertTrue(DataHelper.eq(dmsg5, msg5));
}
/**
* Run tagsIncluded useTag rekey
* 1 yes (2) no no
* 2 no yes no
* 3 yes (2) yes yes
* 4 no yes no
* 5 no yes no
*/
public void testRekeying() throws Exception{
Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
PublicKey pubKey = (PublicKey)keys[0];
PrivateKey privKey = (PrivateKey)keys[1];
SessionKey curKey = _context.sessionKeyManager().createSession(pubKey);
SessionKey nextKey = KeyGenerator.getInstance().generateSessionKey();
SessionTag tag1 = new SessionTag(true);
SessionTag tag2 = new SessionTag(true);
SessionTag tag3 = new SessionTag(true);
SessionTag tag4 = new SessionTag(true);
HashSet firstTags = new HashSet();
firstTags.add(tag1);
firstTags.add(tag2);
HashSet secondTags = new HashSet();
secondTags.add(tag3);
secondTags.add(tag4);
byte[] msg1 = "msg 1".getBytes();
byte[] msg2 = "msg 2".getBytes();
byte[] msg3 = "msg 3".getBytes();
byte[] msg4 = "msg 4".getBytes();
byte[] msg5 = "msg 5".getBytes();
byte emsg1[] = _context.elGamalAESEngine().encrypt(msg1, pubKey, curKey, firstTags, 64);
byte dmsg1[] = _context.elGamalAESEngine().decrypt(emsg1, privKey);
assertTrue(DataHelper.eq(dmsg1, msg1));
TagSetHandle tsh = _context.sessionKeyManager().tagsDelivered(pubKey, curKey, firstTags);
_context.sessionKeyManager().tagsAcked(pubKey, curKey, tsh);
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
SessionTag curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
byte emsg2[] = _context.elGamalAESEngine().encrypt(msg2, pubKey, curKey, null, curTag, 64);
byte dmsg2[] = _context.elGamalAESEngine().decrypt(emsg2, privKey);
assertTrue(DataHelper.eq(dmsg2, msg2));
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg3[] = _context.elGamalAESEngine().encrypt(msg3, pubKey, curKey, secondTags, curTag, nextKey, 64);
byte dmsg3[] = _context.elGamalAESEngine().decrypt(emsg3, privKey);
assertTrue(DataHelper.eq(dmsg3, msg3));
tsh = _context.sessionKeyManager().tagsDelivered(pubKey, nextKey, secondTags); // note nextKey not curKey
_context.sessionKeyManager().tagsAcked(pubKey, nextKey, tsh);
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg4[] = _context.elGamalAESEngine().encrypt(msg4, pubKey, curKey, null, curTag, 64);
byte dmsg4[] = _context.elGamalAESEngine().decrypt(emsg4, privKey);
assertTrue(DataHelper.eq(dmsg4, msg4));
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
assertNotNull(curTag);
assertNotNull(curKey);
byte emsg5[] = _context.elGamalAESEngine().encrypt(msg5, pubKey, curKey, null, curTag, 64);
byte dmsg5[] = _context.elGamalAESEngine().decrypt(emsg5, privKey);
assertTrue(DataHelper.eq(dmsg5, msg5));
}
/**
* 20 tags every 10 messages, rekey every 50
*/
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 < 1000; i++) {
Set tags = null;
SessionKey nextKey = null;
curKey = _context.sessionKeyManager().getCurrentKey(pubKey);
SessionTag curTag = _context.sessionKeyManager().consumeNextAvailableTag(pubKey, curKey);
int availTags = _context.sessionKeyManager().getAvailableTags(pubKey, curKey);
if ((availTags < 1)) {
tags = generateNewTags(50);
}
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);
assertTrue(DataHelper.eq(dmsg, msg));
if ( (tags != null) && (tags.size() > 0) ) {
if (nextKey == null) {
TagSetHandle tsh = _context.sessionKeyManager().tagsDelivered(pubKey, curKey, tags);
_context.sessionKeyManager().tagsAcked(pubKey, curKey, tsh);
} else {
TagSetHandle tsh = _context.sessionKeyManager().tagsDelivered(pubKey, nextKey, tags);
_context.sessionKeyManager().tagsAcked(pubKey, nextKey, tsh);
}
}
}
}
private Set generateNewTags(int numTags) {
Set tags = new HashSet(numTags);
for (int i = 0; i < numTags; i++)
tags.add(new SessionTag(true));
return tags;
}
}

View File

@ -1,28 +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 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));
}
}

View File

@ -1,40 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
/**
* Test harness for the boolean structure
*
* @author jrandom
*/
public class BooleanTest extends TestCase{
public void testBoolean() throws Exception{
byte[] temp = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeBoolean(baos, Boolean.TRUE);
temp = baos.toByteArray();
Boolean b = null;
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
b = DataHelper.readBoolean(bais);
assertEquals(Boolean.TRUE, b);
}
}

View File

@ -1,28 +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.
*
*/
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class CertificateTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
Certificate cert = new Certificate();
byte data[] = new byte[32];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
cert.setPayload(data);
cert.setCertificateType(Certificate.CERTIFICATE_TYPE_NULL);
return cert;
}
public DataStructure createStructureToRead() { return new Certificate(); }
}

View File

@ -1,133 +0,0 @@
package net.i2p.data;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
/**
* basic unit tests for the DataHelper
*
*/
public class DataHelperTest extends TestCase{
private I2PAppContext _context;
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() 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++)
checkLong(8, i);
}
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);
}
public void testDate() throws Exception{
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
checkDate(cal.getTime());
cal.set(Calendar.SECOND, 1);
checkDate(cal.getTime());
cal.set(Calendar.YEAR, 1999);
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);
checkDate(cal.getTime());
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
checkDate(cal.getTime());
cal.setTimeInMillis(System.currentTimeMillis());
checkDate(cal.getTime());
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+10);
checkDate(cal.getTime());
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 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());
}
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);
assertTrue(DataHelper.eq(data, decompressed));
}
}
}

View File

@ -1,72 +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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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());
}
}

View File

@ -1,39 +0,0 @@
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(Base64Test.class);
suite.addTestSuite(BooleanTest.class);
suite.addTestSuite(CertificateTest.class);
suite.addTestSuite(DataHelperTest.class);
suite.addTestSuite(DataStructureImplTest.class);
suite.addTestSuite(DateTest.class);
suite.addTestSuite(DestinationTest.class);
suite.addTestSuite(HashTest.class);
suite.addTestSuite(LeaseSetTest.class);
suite.addTestSuite(LeaseTest.class);
suite.addTestSuite(MappingTest.class);
suite.addTestSuite(PayloadTest.class);
suite.addTestSuite(PrivateKeyTest.class);
suite.addTestSuite(PublicKeyTest.class);
suite.addTestSuite(RouterAddressTest.class);
suite.addTestSuite(RouterIdentityTest.class);
suite.addTestSuite(RouterInfoTest.class);
suite.addTestSuite(SessionKeyTest.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;
}
}

View File

@ -1,42 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import junit.framework.TestCase;
/**
* Test harness for the date structure
*
* @author jrandom
*/
public class DateTest extends TestCase{
public void testDate() throws Exception{
byte[] temp = null;
Date orig = new Date();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeDate(baos, orig);
temp = baos.toByteArray();
Date d = null;
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
d = DataHelper.readDate(bais);
assertEquals(orig, d);
}
}

View File

@ -1,29 +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.
*
*/
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class DestinationTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
Destination dest = new Destination();
StructureTest tst = new CertificateTest();
dest.setCertificate((Certificate)tst.createDataStructure());
tst = new PublicKeyTest();
dest.setPublicKey((PublicKey)tst.createDataStructure());
tst = new SigningPublicKeyTest();
dest.setSigningPublicKey((SigningPublicKey)tst.createDataStructure());
return dest;
}
public DataStructure createStructureToRead() { return new Destination(); }
}

View File

@ -1,27 +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.
*
*/
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class HashTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
Hash hash = new Hash();
byte data[] = new byte[32];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
hash.setData(data);
return hash;
}
public DataStructure createStructureToRead() { return new Hash(); }
}

View File

@ -1,74 +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.
*
*/
/**
* Test harness for loading / storing Lease objects
*
* @author jrandom
*/
public class LeaseSetTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
LeaseSet leaseSet = new LeaseSet();
leaseSet.setDestination((Destination)(new DestinationTest()).createDataStructure());
leaseSet.setEncryptionKey((PublicKey)(new PublicKeyTest()).createDataStructure());
leaseSet.setSignature((Signature)(new SignatureTest()).createDataStructure());
leaseSet.setSigningKey((SigningPublicKey)(new SigningPublicKeyTest()).createDataStructure());
//leaseSet.setVersion(42l);
return leaseSet;
}
public DataStructure createStructureToRead() { return new LeaseSet(); }
public void testGetLeaseInvalid() {
// create test subject
LeaseSet subj = new LeaseSet();
// should contain no leases now..
try {
assertNull(subj.getLease(0));
} catch(RuntimeException exc) {
// all good
}
// this shouldn't work either
try {
assertNull(subj.getLease(-1));
} catch(RuntimeException exc) {
// all good
}
}
public void testAddLeaseNull() {
// create test subject
LeaseSet subj = new LeaseSet();
// now add an null lease
try {
subj.addLease(null);
fail("Failed at failing.");
} catch(IllegalArgumentException exc) {
// all good
}
}
public void testAddLeaseInvalid() {
// create test subject
LeaseSet subj = new LeaseSet();
// try to add completely invalid lease(ie. no data)
try {
subj.addLease(new Lease());
fail("Failed at failing.");
} catch(IllegalArgumentException exc) {
// all good
}
}
}

View File

@ -1,97 +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.ByteArrayOutputStream;
import java.util.Date;
/**
* Test harness for loading / storing Lease objects
*
* @author jrandom
*/
public class LeaseTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
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());
return lease;
}
public DataStructure createStructureToRead() { return new Lease(); }
/* TODO: Delete this if Lease.getNumSuccess() / getNumFailure() get deleted
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));
}
}

View File

@ -1,45 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import junit.framework.TestCase;
/**
* Test harness for the date structure
*
* @author jrandom
*/
public class MappingTest extends TestCase{
public void testProperties() throws Exception{
byte[] temp = null;
Properties orig = new Properties();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
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);
}
}

View File

@ -1,60 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Test harness for loading / storing Payload objects
*
* @author jrandom
*/
public class PayloadTest extends StructureTest{
public DataStructure createDataStructure() throws DataFormatException {
Payload payload = new Payload();
SessionKey key = (SessionKey)(new SessionKeyTest()).createDataStructure();
byte data[] = "Hello, I2P".getBytes();
payload.setUnencryptedData(data);
Hash hash = (Hash)(new HashTest()).createDataStructure();
Destination target = (Destination)(new DestinationTest()).createDataStructure();
payload.setEncryptedData(data);
return payload;
}
public DataStructure createStructureToRead() { return new Payload(); }
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);
}
}

View File

@ -1,94 +0,0 @@
package net.i2p.data;
/*
* free (adj.): unencumbered; not under the control of others
* 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Test harness for loading / storing PrivateKey objects
*
* @author jrandom
*/
public class PrivateKeyTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
PrivateKey privateKey = new PrivateKey();
byte data[] = new byte[PrivateKey.KEYSIZE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
privateKey.setData(data);
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);
boolean error = false;
try{
privateKey.setData(data);
privateKey.writeBytes(new ByteArrayOutputStream());
}catch(DataFormatException dfe){
error = true;
}catch(IllegalArgumentException exc) {
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);
}
}

View File

@ -1,93 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Test harness for loading / storing PublicKey objects
*
* @author jrandom
*/
public class PublicKeyTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
PublicKey publicKey = new PublicKey();
byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
publicKey.setData(data);
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);
boolean error = false;
try{
publicKey.setData(data);
publicKey.writeBytes(new ByteArrayOutputStream());
}catch(DataFormatException dfe){
error = true;
}catch(IllegalArgumentException exc) {
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);
}
}

View File

@ -1,106 +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.ByteArrayOutputStream;
import java.util.Date;
import java.util.Properties;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class RouterAddressTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
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");
return addr;
}
public DataStructure createStructureToRead() { return new RouterAddress(); }
public void testSetNullOptions(){
RouterAddress addr = new RouterAddress();
boolean error = false;
try{
addr.setOptions(null);
}catch(NullPointerException dfe){
error = true;
}
assertTrue(error);
}
public void testSetOptionsAgain(){
RouterAddress addr = new RouterAddress();
Properties options = new Properties();
options.setProperty("hostname", "localhost");
options.setProperty("portnum", "1234");
addr.setOptions(options);
options.setProperty("portnum", "2345");
boolean error = false;
try{
addr.setOptions(options);
}catch(IllegalStateException dfe){
error = true;
}
assertTrue(error);
}
public void testBadWrite() throws Exception{
RouterAddress addr = new RouterAddress();
boolean error = false;
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));
assertFalse(addr.equals(""));
}
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");
String ret = addr.toString();
assertEquals("[RouterAddress: \n\tTransportStyle: Blah\n\tCost: 42\n\tExpiration: Fri Jan 02 00:00:00 UTC 1970\n\tOptions: #: 2\n\t\t[hostname] = [localhost]\n\t\t[portnum] = [1234]]", ret);
}
}

View File

@ -1,110 +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.ByteArrayOutputStream;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class RouterIdentityTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
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);
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();
}
}

View File

@ -1,73 +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.HashSet;
import java.util.Properties;
import net.i2p.crypto.KeyGenerator;
import net.i2p.util.Log;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class RouterInfoTest extends StructureTest {
private final static Log _log = new Log(RouterInfoTest.class);
public DataStructure createDataStructure() throws DataFormatException {
RouterInfo info = new RouterInfo();
HashSet addresses = new HashSet();
DataStructure structure = (new RouterAddressTest()).createDataStructure();
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);
info.setIdentity(ident);
Properties options = new Properties();
for (int i = 0; i < 16; i++) {
options.setProperty("option." + i, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890$:." + i);
}
options.setProperty("netConnectionSpeed", "OC12");
info.setOptions(options);
HashSet peers = new HashSet();
structure = (new HashTest()).createDataStructure();
peers.add(structure);
info.setPeers(peers);
info.setPublished(System.currentTimeMillis());
//info.setVersion(69);
info.sign(signingPrivKey);
return info;
}
public DataStructure createStructureToRead() { return new RouterInfo(); }
}

View File

@ -1,27 +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.
*
*/
/**
* Test harness for loading / storing SessionKey objects
*
* @author jrandom
*/
public class SessionKeyTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SessionKey key = new SessionKey();
byte data[] = new byte[SessionKey.KEYSIZE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
key.setData(data);
return key;
}
public DataStructure createStructureToRead() { return new SessionKey(); }
}

View File

@ -1,27 +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.
*
*/
/**
* Test harness for loading / storing Signature objects
*
* @author jrandom
*/
public class SignatureTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
Signature sig = new Signature();
byte data[] = new byte[Signature.SIGNATURE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
sig.setData(data);
return sig;
}
public DataStructure createStructureToRead() { return new Signature(); }
}

View File

@ -1,95 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Test harness for loading / storing SigningPrivateKey objects
*
* @author jrandom
*/
public class SigningPrivateKeyTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
byte data[] = new byte[SigningPrivateKey.KEYSIZE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
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);
boolean error = false;
try{
signingPrivateKey.setData(data);
signingPrivateKey.writeBytes(new ByteArrayOutputStream());
}catch(DataFormatException dfe){
error = true;
}catch(IllegalArgumentException exc) {
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);
}
}

View File

@ -1,95 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Test harness for loading / storing PublicKey objects
*
* @author jrandom
*/
public class SigningPublicKeyTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SigningPublicKey publicKey = new SigningPublicKey();
byte data[] = new byte[SigningPublicKey.KEYSIZE_BYTES];
for (int i = 0; i < data.length; i++)
data[i] = (byte)(i%16);
publicKey.setData(data);
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);
boolean error = false;
try{
publicKey.setData(data);
publicKey.writeBytes(new ByteArrayOutputStream());
}catch(DataFormatException dfe){
error = true;
}catch(IllegalArgumentException exc) {
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);
}
}

View File

@ -1,96 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
/**
* Test harness for the simple data structure
*
* @author welterde
*/
public class SimpleDataStructureTest extends TestCase {
public void testSetDataImmutable() throws Exception {
// create new test subject
TestStruct struct = new TestStruct();
// try to set null object.. should not fail..
struct.setData(null);
// set data to something
struct.setData(new byte[3]);
// now setting it to null should fail
try {
struct.setData(null);
fail("Should not have allowed us to change this..");
} catch(RuntimeException exc) {
// all good
}
// setting it to something non-null should fail as well.
try {
struct.setData(new byte[3]);
fail("Should not have allowed us to change this..");
} catch(RuntimeException exc) {
// all good
}
}
public void testReadBytesImmutable() throws Exception {
// create new test subject
TestStruct struct = new TestStruct();
// load some data using setData
struct.setData(new byte[3]);
// now try to load via readBytes
try {
struct.readBytes(null);
fail("blah blah blah..");
} catch(RuntimeException exc) {
// all good
}
}
public void testToBase64Safe() throws Exception {
// create new test subject
TestStruct struct = new TestStruct();
// now try to get the Base64.. should not throw an exception, but should not be an empty string either
assertNull(struct.toBase64());
}
public void testCalculateHashSafe() throws Exception {
// create new test subject
TestStruct struct = new TestStruct();
// now try to get the hash.. should not throw an exception
assertNull(struct.calculateHash());
}
public void testHashCodeSafe() throws Exception {
// create new test subject
TestStruct struct = new TestStruct();
// just make sure it doesn't explode in our face
struct.hashCode();
}
public class TestStruct extends SimpleDataStructure {
public int length() {
return 3;
}
}
}

View File

@ -1,40 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
/**
* Test harness for the date structure
*
* @author jrandom
*/
public class StringTest extends TestCase{
public void testString() throws Exception{
byte[] temp = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeString(baos, "Hello, I2P");
temp = baos.toByteArray();
String s = null;
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
s = DataHelper.readString(bais);
assertEquals(s, "Hello, I2P");
}
}

View File

@ -1,48 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
/**
* Utility class for wrapping data structure tests
*
* @author jrandom
*/
public abstract class StructureTest extends TestCase{
public abstract DataStructure createDataStructure() throws DataFormatException;
public abstract DataStructure createStructureToRead();
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);
assertEquals(orig, ds);
}
}

View File

@ -1,24 +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.
*
*/
/**
* Test harness for loading / storing TunnelId objects
*
* @author jrandom
*/
public class TunnelIdTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
TunnelId id = new TunnelId();
id.setTunnelId(42);
return id;
}
public DataStructure createStructureToRead() { return new TunnelId(); }
}

View File

@ -1,39 +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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
/**
* Test harness for the date structure
*
* @author jrandom
*/
public class UnsignedIntegerTest extends TestCase{
public void testLong() throws Exception{
byte[] temp = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeLong(baos, 4, 42);
temp = baos.toByteArray();
long l;
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
l = DataHelper.readLong(bais, 4);
assertEquals(42, l);
}
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class AbuseReasonTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
AbuseReason res = new AbuseReason();
res.setReason("Because they're mean");
return res;
}
public DataStructure createStructureToRead() { return new AbuseReason(); }
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class AbuseSeverityTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
AbuseSeverity sev = new AbuseSeverity();
sev.setSeverity(64);
return sev;
}
public DataStructure createStructureToRead() { return new AbuseSeverity(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing BandwidthLimitsMessage objects
*
* @author str4d
*/
public class BandwidthLimitsMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
BandwidthLimitsMessage msg = new BandwidthLimitsMessage(10240, 1024);
return msg;
}
public DataStructure createStructureToRead() { return new BandwidthLimitsMessage(); }
}

View File

@ -1,36 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.PrivateKey;
import net.i2p.data.PrivateKeyTest;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPrivateKeyTest;
import net.i2p.data.LeaseSet;
import net.i2p.data.LeaseSetTest;
/**
* Test harness for loading / storing CreateLeaseSetMessage objects
*
* @author jrandom
*/
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.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new CreateLeaseSetMessage(); }
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class CreateSessionMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
CreateSessionMessage msg = new CreateSessionMessage();
msg.setSessionConfig((SessionConfig)(new SessionConfigTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new CreateSessionMessage(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing DestLookupMessage objects
*
* @author str4d
*/
public class DestLookupMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
DestLookupMessage msg = new DestLookupMessage();
return msg;
}
public DataStructure createStructureToRead() { return new DestLookupMessage(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing DestReplyMessage objects
*
* @author str4d
*/
public class DestReplyMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
DestReplyMessage msg = new DestReplyMessage();
return msg;
}
public DataStructure createStructureToRead() { return new DestReplyMessage(); }
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class DestroySessionMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
DestroySessionMessage msg = new DestroySessionMessage();
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new DestroySessionMessage(); }
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class DisconnectMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
DisconnectMessage msg = new DisconnectMessage();
msg.setReason("Because I say so");
return msg;
}
public DataStructure createStructureToRead() { return new DisconnectMessage(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing GetBandwidthLimitsMessage objects
*
* @author str4d
*/
public class GetBandwidthLimitsMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
GetBandwidthLimitsMessage msg = new GetBandwidthLimitsMessage();
return msg;
}
public DataStructure createStructureToRead() { return new GetBandwidthLimitsMessage(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing GetDateMessage objects
*
* @author str4d
*/
public class GetDateMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
GetDateMessage msg = new GetDateMessage("0.8.13-0");
return msg;
}
public DataStructure createStructureToRead() { return new GetDateMessage(); }
}

View File

@ -1,40 +0,0 @@
package net.i2p.data.i2cp;
import junit.framework.Test;
import junit.framework.TestSuite;
public class I2CPTestSuite {
public static Test suite() {
TestSuite suite = new TestSuite("net.i2p.data.i2cp.I2CPTestSuite");
suite.addTestSuite(AbuseReasonTest.class);
suite.addTestSuite(AbuseSeverityTest.class);
suite.addTestSuite(BandwidthLimitsMessageTest.class);
suite.addTestSuite(CreateLeaseSetMessageTest.class);
suite.addTestSuite(CreateSessionMessageTest.class);
suite.addTestSuite(DestLookupMessageTest.class);
suite.addTestSuite(DestReplyMessageTest.class);
suite.addTestSuite(DestroySessionMessageTest.class);
suite.addTestSuite(DisconnectMessageTest.class);
suite.addTestSuite(GetBandwidthLimitsMessageTest.class);
suite.addTestSuite(GetDateMessageTest.class);
suite.addTestSuite(MessageIdTest.class);
suite.addTestSuite(MessagePayloadMessageTest.class);
suite.addTestSuite(MessageStatusMessageTest.class);
suite.addTestSuite(ReceiveMessageBeginMessageTest.class);
suite.addTestSuite(ReceiveMessageEndMessageTest.class);
suite.addTestSuite(ReconfigureSessionMessageTest.class);
suite.addTestSuite(ReportAbuseMessageTest.class);
suite.addTestSuite(RequestLeaseSetMessageTest.class);
suite.addTestSuite(SendMessageExpiresMessageTest.class);
suite.addTestSuite(SendMessageMessageTest.class);
suite.addTestSuite(SessionConfigTest.class);
suite.addTestSuite(SessionIdTest.class);
suite.addTestSuite(SessionStatusMessageTest.class);
suite.addTestSuite(SetDateMessageTest.class);
return suite;
}
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class MessageIdTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
MessageId id = new MessageId();
id.setMessageId(101);
return id;
}
public DataStructure createStructureToRead() { return new MessageId(); }
}

View File

@ -1,55 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.data.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.Payload;
import net.i2p.data.PayloadTest;
/**
* Test harness for loading / storing SendMessageMessage objects
*
* @author jrandom
*/
public class MessagePayloadMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
MessagePayloadMessage msg = new MessagePayloadMessage();
msg.setMessageId(123);
msg.setPayload((Payload)(new PayloadTest()).createDataStructure());
msg.setSessionId(321);
return msg;
}
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);
}
}

View File

@ -1,31 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing MessageStatusMessage objects
*
* @author jrandom
*/
public class MessageStatusMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
MessageStatusMessage msg = new MessageStatusMessage();
msg.setSessionId(42);
msg.setMessageId(41);
msg.setSize(1024*1024*42L);
msg.setStatus(MessageStatusMessage.STATUS_AVAILABLE);
msg.setNonce(1);
return msg;
}
public DataStructure createStructureToRead() { return new MessageStatusMessage(); }
}

View File

@ -1,28 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class ReceiveMessageBeginMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
ReceiveMessageBeginMessage msg = new ReceiveMessageBeginMessage();
msg.setSessionId(321);
msg.setMessageId(123);
return msg;
}
public DataStructure createStructureToRead() { return new ReceiveMessageBeginMessage(); }
}

View File

@ -1,28 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class ReceiveMessageEndMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
ReceiveMessageEndMessage msg = new ReceiveMessageEndMessage();
msg.setSessionId(321);
msg.setMessageId(123);
return msg;
}
public DataStructure createStructureToRead() { return new ReceiveMessageEndMessage(); }
}

View File

@ -1,28 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing ReconfigureSessionMessage objects
*
* @author str4d
*/
public class ReconfigureSessionMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
ReconfigureSessionMessage msg = new ReconfigureSessionMessage();
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
msg.setSessionConfig((SessionConfig)(new SessionConfigTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new ReconfigureSessionMessage(); }
}

View File

@ -1,30 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class ReportAbuseMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
ReportAbuseMessage msg = new ReportAbuseMessage();
msg.setMessageId((MessageId)(new MessageIdTest()).createDataStructure());
msg.setReason((AbuseReason)(new AbuseReasonTest()).createDataStructure());
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
msg.setSeverity((AbuseSeverity)(new AbuseSeverityTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new ReportAbuseMessage(); }
}

View File

@ -1,35 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.Date;
import net.i2p.data.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.Hash;
import net.i2p.data.TunnelId;
import net.i2p.data.TunnelIdTest;
/**
* Test harness for loading / storing RequestLeaseSetMessage objects
*
* @author jrandom
*/
public class RequestLeaseSetMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
RequestLeaseSetMessage msg = new RequestLeaseSetMessage();
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
msg.setEndDate(new Date(1000*60*60*12));
byte h[] = new byte[Hash.HASH_LENGTH];
msg.addEndpoint(new Hash(h), (TunnelId)(new TunnelIdTest()).createDataStructure());
return msg;
}
public DataStructure createStructureToRead() { return new RequestLeaseSetMessage(); }
}

View File

@ -1,67 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.data.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.data.DestinationTest;
import net.i2p.data.Payload;
import net.i2p.data.PayloadTest;
import net.i2p.data.DateAndFlags;
import net.i2p.data.DateAndFlagsTest;
/**
* Test harness for loading / storing SendMessageExpiresMessage objects
*
* @author str4d
*/
public class SendMessageExpiresMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SendMessageExpiresMessage msg = new SendMessageExpiresMessage();
msg.setDestination((Destination)(new DestinationTest()).createDataStructure());
msg.setPayload((Payload)(new PayloadTest()).createDataStructure());
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
msg.setNonce(1);
DateAndFlags daf = (DateAndFlags)(new DateAndFlagsTest()).createDataStructure();
msg.setExpiration(daf.getDate());
msg.setFlags(daf.getFlags());
return msg;
}
public DataStructure createStructureToRead() { return new SendMessageExpiresMessage(); }
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);
((SendMessageExpiresMessage)ds).getPayload().setUnencryptedData(((SendMessageExpiresMessage)ds).getPayload().getEncryptedData());
assertEquals(orig, ds);
}
}

View File

@ -1,62 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.data.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.data.DestinationTest;
import net.i2p.data.Payload;
import net.i2p.data.PayloadTest;
/**
* Test harness for loading / storing SendMessageMessage objects
*
* @author jrandom
*/
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 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);
}
}

View File

@ -1,41 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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 net.i2p.data.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.data.DestinationTest;
import net.i2p.data.Signature;
import net.i2p.data.SignatureTest;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPrivateKeyTest;
/**
* Test harness for loading / storing Hash objects
*
* @author jrandom
*/
public class SessionConfigTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SessionConfig cfg = new SessionConfig((Destination)(new DestinationTest()).createDataStructure());
cfg.setSignature((Signature)(new SignatureTest()).createDataStructure());
Properties options = new Properties();
options.setProperty("routerHost", "localhost");
options.setProperty("routerPort", "54321");
options.setProperty("routerSecret", "blah");
cfg.setOptions(options);
cfg.signSessionConfig((SigningPrivateKey)(new SigningPrivateKeyTest()).createDataStructure());
return cfg;
}
public DataStructure createStructureToRead() { return new SessionConfig(); }
}

View File

@ -1,27 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing SessionId objects
*
* @author jrandom
*/
public class SessionIdTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SessionId id = new SessionId();
id.setSessionId(7);
return id;
}
public DataStructure createStructureToRead() { return new SessionId(); }
}

View File

@ -1,28 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing SessionStatusMessage objects
*
* @author jrandom
*/
public class SessionStatusMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SessionStatusMessage msg = new SessionStatusMessage();
msg.setSessionId((SessionId)(new SessionIdTest()).createDataStructure());
msg.setStatus(SessionStatusMessage.STATUS_CREATED);
return msg;
}
public DataStructure createStructureToRead() { return new SessionStatusMessage(); }
}

View File

@ -1,26 +0,0 @@
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by str4d in 2012 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.StructureTest;
import net.i2p.data.DataStructure;
import net.i2p.data.DataFormatException;
/**
* Test harness for loading / storing SetDateMessage objects
*
* @author str4d
*/
public class SetDateMessageTest extends StructureTest {
public DataStructure createDataStructure() throws DataFormatException {
SetDateMessage msg = new SetDateMessage("0.8.13-0");
return msg;
}
public DataStructure createStructureToRead() { return new SetDateMessage(); }
}

View File

@ -1,57 +0,0 @@
package net.i2p.stat;
import java.util.Properties;
import junit.framework.TestCase;
public class RateStatTest extends TestCase {
public void testGettersEtc() throws Exception{
long emptyArray[] = new long[0];
RateStat rs = new RateStat("test", "test RateStat getters etc", "tests", emptyArray);
// Test basic getters
assertEquals("test", rs.getName());
assertEquals("tests", rs.getGroupName());
assertEquals("test RateStat getters etc", rs.getDescription());
// There should be no periods, so other getters should return defaults
// TODO: Fix this so it checks that the array is empty rather than comparing objects
//assertEquals(rs.getPeriods(), emptyArray);
assertEquals(0.0, rs.getLifetimeAverageValue());
assertEquals(0, rs.getLifetimeEventCount());
assertNull(rs.getRate(2000));
// Test adding and removing a period
assertFalse(rs.containsRate(1000));
rs.addRate(1000);
assertTrue(rs.containsRate(1000));
rs.removeRate(1000);
assertFalse(rs.containsRate(1000));
}
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);
}
}

View File

@ -1,29 +0,0 @@
package net.i2p.stat;
import java.io.ByteArrayInputStream;
import java.util.Properties;
import junit.framework.TestCase;
public class RateTest extends TestCase {
public void testRate() throws Exception{
Rate rate = new Rate(5000);
for (int i = 0; i < 50; i++) {
Thread.sleep(20);
rate.addData(i * 100, 20);
}
rate.coalesce();
StringBuilder buf = new StringBuilder(1024);
rate.store("rate.test", buf);
byte data[] = buf.toString().getBytes();
Properties props = new Properties();
props.load(new ByteArrayInputStream(data));
Rate r = new Rate(props, "rate.test", true);
assertEquals(r, rate);
}
}

View File

@ -1,65 +0,0 @@
package net.i2p.stat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import net.i2p.I2PAppContext;
import net.i2p.util.Log;
public class SimpleStatDumper {
private final static Log _log = new Log(SimpleStatDumper.class);
public static void dumpStats(I2PAppContext context, int logLevel) {
if (!_log.shouldLog(logLevel)) return;
StringBuilder buf = new StringBuilder(4 * 1024);
dumpFrequencies(context, buf);
dumpRates(context, buf);
_log.log(logLevel, buf.toString());
}
private static void dumpFrequencies(I2PAppContext ctx, StringBuilder buf) {
Set frequencies = new TreeSet(ctx.statManager().getFrequencyNames());
for (Iterator iter = frequencies.iterator(); iter.hasNext();) {
String name = (String) iter.next();
FrequencyStat freq = ctx.statManager().getFrequency(name);
buf.append('\n');
buf.append(freq.getGroupName()).append('.').append(freq.getName()).append(": ")
.append(freq.getDescription()).append('\n');
long periods[] = freq.getPeriods();
Arrays.sort(periods);
for (int i = 0; i < periods.length; i++) {
buf.append('\t').append(periods[i]).append(':');
Frequency curFreq = freq.getFrequency(periods[i]);
buf.append(" average interval: ").append(curFreq.getAverageInterval());
buf.append(" min average interval: ").append(curFreq.getMinAverageInterval());
buf.append('\n');
}
}
}
private static void dumpRates(I2PAppContext ctx, StringBuilder buf) {
Set rates = new TreeSet(ctx.statManager().getRateNames());
for (Iterator iter = rates.iterator(); iter.hasNext();) {
String name = (String) iter.next();
RateStat rate = ctx.statManager().getRate(name);
buf.append('\n');
buf.append(rate.getGroupName()).append('.').append(rate.getName()).append(": ")
.append(rate.getDescription()).append('\n');
long periods[] = rate.getPeriods();
Arrays.sort(periods);
for (int i = 0; i < periods.length; i++) {
buf.append('\t').append(periods[i]).append(':');
Rate curRate = rate.getRate(periods[i]);
dumpRate(curRate, buf);
buf.append('\n');
}
}
}
static void dumpRate(Rate curRate, StringBuilder buf) {
buf.append(curRate.toString());
}
}

View File

@ -1,58 +0,0 @@
package net.i2p.stat;
public class SizeMeasure {
public static void main(String args[]) {
testRateSize(100); //117KB
testRateSize(100000); // 4.5MB
testRateSize(440000); // 44MB
//testFrequencySize(100); // 114KB
//testFrequencySize(100000); // 5.3MB
//testFrequencySize(1000000); // 52MB
}
private static void testRateSize(int num) {
Runtime.getRuntime().gc();
Rate rate[] = new Rate[num];
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long usedPer = used / num;
System.out
.println(num + ": create array - Used: " + used + " bytes (or " + usedPer + " bytes per array entry)");
int i = 0;
try {
for (; i < num; i++)
rate[i] = new Rate(1234);
} catch (OutOfMemoryError oom) {
rate = null;
Runtime.getRuntime().gc();
System.out.println("Ran out of memory when creating rate " + i);
return;
}
Runtime.getRuntime().gc();
long usedObjects = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
usedPer = usedObjects / num;
System.out.println(num + ": create objects - Used: " + usedObjects + " bytes (or " + usedPer
+ " bytes per rate)");
rate = null;
Runtime.getRuntime().gc();
}
private static void testFrequencySize(int num) {
Runtime.getRuntime().gc();
Frequency freq[] = new Frequency[num];
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long usedPer = used / num;
System.out
.println(num + ": create array - Used: " + used + " bytes (or " + usedPer + " bytes per array entry)");
for (int i = 0; i < num; i++)
freq[i] = new Frequency(1234);
Runtime.getRuntime().gc();
long usedObjects = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
usedPer = usedObjects / num;
System.out.println(num + ": create objects - Used: " + usedObjects + " bytes (or " + usedPer
+ " bytes per frequency)");
freq = null;
Runtime.getRuntime().gc();
}
}

View File

@ -1,76 +0,0 @@
package net.i2p.stat;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Simple CLI to splot the stat logs into per-stat files containing
* #seconds since beginning and the value (ready for loading into your
* favorite plotting tool)
*/
public class StatLogSplitter {
private static final String DATE_FORMAT = "yyyyMMdd HH:mm:ss.SSS";
private static SimpleDateFormat _fmt = new SimpleDateFormat(DATE_FORMAT);
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Usage: StatLogSplitter filename");
return;
}
splitLog(args[0]);
}
private static void splitLog(String filename) {
Map outputFiles = new HashMap(4);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
long first = 0;
while ( (line = in.readLine()) != null) {
String date = line.substring(0, DATE_FORMAT.length()).trim();
int endGroup = line.indexOf(' ', DATE_FORMAT.length()+1);
int endStat = line.indexOf(' ', endGroup+1);
int endValue = line.indexOf(' ', endStat+1);
String group = line.substring(DATE_FORMAT.length()+1, endGroup).trim();
String stat = line.substring(endGroup, endStat).trim();
String value = line.substring(endStat, endValue).trim();
String duration = line.substring(endValue).trim();
//System.out.println(date + " " + group + " " + stat + " " + value + " " + duration);
try {
Date when = _fmt.parse(date);
if (first <= 0) first = when.getTime();
long val = Long.parseLong(value);
long time = Long.parseLong(duration);
if (!outputFiles.containsKey(stat)) {
outputFiles.put(stat, new FileWriter(stat + ".dat"));
System.out.println("Including data to " + stat + ".dat");
}
FileWriter out = (FileWriter)outputFiles.get(stat);
double s = (when.getTime()-first)/1000.0;
//long s = when.getTime();
out.write(s + " " + val + " [" + line + "]\n");
out.flush();
} catch (ParseException pe) {
continue;
} catch (NumberFormatException nfe){
continue;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
for (Iterator iter = outputFiles.values().iterator(); iter.hasNext(); ) {
FileWriter out = (FileWriter)iter.next();
try { out.close(); } catch (IOException ioe) {}
}
}
}

View File

@ -1,27 +0,0 @@
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;
}
}

View File

@ -1,292 +0,0 @@
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.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.Properties;
import junit.framework.TestCase;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
/**
* @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);
try {
log.debug("DEBUG" + ": debug");
log.info("DEBUG" + ": info");
log.warn("DEBUG" + ": warn");
log.error("DEBUG" + ": error");
log.log(Log.CRIT, "DEBUG" + ": crit");
// Wait for the LogWriter to flush, then write extra stuff so
// the test doesn't hang on failure
try { Thread.sleep(12*1000); } catch (InterruptedException ie) {}
for (int i = 0; i < 5; i++)
pout.println("");
pout.flush();
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")
);
} finally {
System.setOut(systemOut);
pout.close();
}
}
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);
try {
log.debug("INFO" + ": debug");
log.info("INFO" + ": info");
log.warn("INFO" + ": warn");
log.error("INFO" + ": error");
log.log(Log.CRIT, "INFO" + ": crit");
// Wait for the LogWriter to flush, then write extra stuff so
// the test doesn't hang on failure
try { Thread.sleep(12*1000); } catch (InterruptedException ie) {}
for (int i = 0; i < 4; i++)
pout.println("");
pout.flush();
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")
);
} finally {
System.setOut(systemOut);
pout.close();
}
}
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);
try {
log.debug("WARN" + ": debug");
log.info("WARN" + ": info");
log.warn("WARN" + ": warn");
log.error("WARN" + ": error");
log.log(Log.CRIT, "WARN" + ": crit");
// Wait for the LogWriter to flush, then write extra stuff so
// the test doesn't hang on failure
try { Thread.sleep(12*1000); } catch (InterruptedException ie) {}
for (int i = 0; i < 3; i++)
pout.println("");
pout.flush();
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")
);
} finally {
System.setOut(systemOut);
pout.close();
}
}
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);
try {
log.debug("ERROR" + ": debug");
log.info("ERROR" + ": info");
log.warn("ERROR" + ": warn");
log.error("ERROR" + ": error");
log.log(Log.CRIT, "ERROR" + ": crit");
// Wait for the LogWriter to flush, then write extra stuff so
// the test doesn't hang on failure
try { Thread.sleep(12*1000); } catch (InterruptedException ie) {}
for (int i = 0; i < 2; i++)
pout.println("");
pout.flush();
String l1 = in.readLine();
String l2 = in.readLine();
assertTrue(
l1.matches(".*ERROR: error") &&
l2.matches(".*ERROR: crit")
);
} finally {
System.setOut(systemOut);
pout.close();
}
}
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);
try {
log.debug("CRIT" + ": debug");
log.info("CRIT" + ": info");
log.warn("CRIT" + ": warn");
log.error("CRIT" + ": error");
log.log(Log.CRIT, "CRIT" + ": crit");
// Wait for the LogWriter to flush, then write extra stuff so
// the test doesn't hang on failure
try { Thread.sleep(12*1000); } catch (InterruptedException ie) {}
pout.println("");
pout.flush();
String l1 = in.readLine();
assertTrue(
l1.matches(".*CRIT: crit")
);
} finally {
System.setOut(systemOut);
pout.close();
}
}
}

View File

@ -1,49 +0,0 @@
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 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)]);
}
}
}

View File

@ -1,67 +0,0 @@
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.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;
import junit.framework.TestCase;
import net.i2p.data.DataHelper;
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());
}
}

View File

@ -1,44 +0,0 @@
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.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import junit.framework.TestCase;
import net.i2p.data.DataHelper;
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));
}
}

View File

@ -1,64 +0,0 @@
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.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import junit.framework.TestCase;
import net.i2p.data.DataHelper;
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));
}
}
}

View File

@ -1,60 +0,0 @@
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.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import junit.framework.TestCase;
import net.i2p.data.DataHelper;
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));
}
}
}

View File

@ -1,25 +0,0 @@
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;
}
}