Build: Move SSU HMAC implementation from core to router

This commit is contained in:
zzz
2019-07-12 18:40:46 +00:00
parent 1be569db7a
commit 6adc665fd3
16 changed files with 270 additions and 242 deletions

View File

@ -1619,7 +1619,7 @@ class PacketBuilder {
int hmacLen = totalSize + UDPPacket.IV_SIZE + 2;
//Hash hmac = _context.hmac().calculate(macKey, data, hmacOff, hmacLen);
byte[] ba = SimpleByteCache.acquire(Hash.HASH_LENGTH);
_context.hmac().calculate(macKey, data, hmacOff, hmacLen, ba, 0);
_transport.getHMAC().calculate(macKey, data, hmacOff, hmacLen, ba, 0);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Authenticating " + pkt.getLength() +

View File

@ -10,6 +10,7 @@ import net.i2p.router.RouterContext;
import net.i2p.router.util.CoDelBlockingQueue;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
import net.i2p.util.I2PThread;
import net.i2p.util.LHMCache;
import net.i2p.util.Log;
@ -181,6 +182,13 @@ class PacketHandler {
return rv;
}
/**
* @since 0.9.42
*/
private boolean validate(UDPPacket packet, SessionKey key) {
return packet.validate(key, _transport.getHMAC());
}
/** the packet is from a peer we are establishing an outbound con to, but failed validation, so fallback */
private static final short OUTBOUND_FALLBACK = 1;
/** the packet is from a peer we are establishing an inbound con to, but failed validation, so fallback */
@ -325,17 +333,17 @@ class PacketHandler {
private void receivePacket(UDPPacketReader reader, UDPPacket packet, PeerState state) {
_state = 17;
AuthType auth = AuthType.NONE;
boolean isValid = packet.validate(state.getCurrentMACKey());
boolean isValid = validate(packet, state.getCurrentMACKey());
if (!isValid) {
_state = 18;
if (state.getNextMACKey() != null)
isValid = packet.validate(state.getNextMACKey());
isValid = validate(packet, state.getNextMACKey());
if (!isValid) {
_state = 19;
if (_log.shouldLog(Log.INFO))
_log.info("Failed validation with existing con, trying as new con: " + packet);
isValid = packet.validate(_transport.getIntroKey());
isValid = validate(packet, _transport.getIntroKey());
if (isValid) {
_state = 20;
// this is a stray packet from an inbound establishment
@ -388,7 +396,7 @@ class PacketHandler {
*/
private void receivePacket(UDPPacketReader reader, UDPPacket packet, short peerType) {
_state = 27;
boolean isValid = packet.validate(_transport.getIntroKey());
boolean isValid = validate(packet, _transport.getIntroKey());
if (!isValid) {
// Note that the vast majority of these are NOT corrupted packets, but
// packets for which we don't have the PeerState (i.e. SessionKey)
@ -425,7 +433,7 @@ class PacketHandler {
}
if (ps.getRemotePort() == newPort) {
foundSamePort = true;
} else if (packet.validate(ps.getCurrentMACKey())) {
} else if (validate(packet, ps.getCurrentMACKey())) {
packet.decrypt(ps.getCurrentCipherKey());
reader.initialize(packet);
if (_log.shouldLog(Log.WARN))
@ -513,7 +521,7 @@ class PacketHandler {
}
boolean isValid = false;
if (state.getMACKey() != null) {
isValid = packet.validate(state.getMACKey());
isValid = validate(packet, state.getMACKey());
if (isValid) {
if (_log.shouldLog(Log.INFO))
_log.info("Valid introduction packet received for inbound con: " + packet);
@ -558,7 +566,7 @@ class PacketHandler {
boolean isValid = false;
if (state.getMACKey() != null) {
_state = 36;
isValid = packet.validate(state.getMACKey());
isValid = validate(packet, state.getMACKey());
if (isValid) {
// this should be the Session Confirmed packet
if (_log.shouldLog(Log.INFO))
@ -572,7 +580,7 @@ class PacketHandler {
}
// keys not yet exchanged, lets try it with the peer's intro key
isValid = packet.validate(state.getIntroKey());
isValid = validate(packet, state.getIntroKey());
if (isValid) {
if (_log.shouldLog(Log.INFO))
_log.info("Valid packet received for " + state + " with Bob's intro key: " + packet);

View File

@ -0,0 +1,185 @@
package net.i2p.router.transport.udp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;
// following are for main() tests
//import java.security.InvalidKeyException;
//import java.security.Key;
//import java.security.NoSuchAlgorithmException;
//import javax.crypto.spec.SecretKeySpec;
//import net.i2p.data.Base64;
import net.i2p.crypto.HMACGenerator;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.util.SimpleByteCache;
import org.bouncycastle.oldcrypto.macs.I2PHMac;
/**
* Calculate the HMAC-MD5-128 of a key+message. All the good stuff occurs
* in {@link org.bouncycastle.oldcrypto.macs.I2PHMac}
*
* Keys are always 32 bytes.
* This is used only by UDP.
* Use deprecated outside the router, this may move to router.jar.
*
* NOTE THIS IS NOT COMPATIBLE with javax.crypto.Mac.getInstance("HmacMD5")
* as we tell I2PHMac that the digest length is 32 bytes, so it generates
* a different result.
*
* Quote jrandom:
* "The HMAC is hardcoded to use SHA256 digest size
* for backwards compatability. next time we have a backwards
* incompatible change, we should update this."
*
* Does this mean he intended it to be compatible with MD5?
* See also 2005-07-05 status notes.
*
* @since 0.9.42 moved from net.i2p.crypto.HMACGenerator
*/
class SSUHMACGenerator extends HMACGenerator {
/** set of available HMAC instances for calculate */
private final LinkedBlockingQueue<I2PHMac> _available;
public SSUHMACGenerator() {
super();
_available = new LinkedBlockingQueue<I2PHMac>(32);
}
/**
* Calculate the HMAC of the data with the given key
*
* @param target out parameter the first 16 bytes contain the HMAC, the last 16 bytes are zero
* @param targetOffset offset into target to put the hmac
* @throws IllegalArgumentException for bad key or target too small
*/
public void calculate(SessionKey key, byte data[], int offset, int length, byte target[], int targetOffset) {
if ((key == null) || (key.getData() == null) || (data == null))
throw new NullPointerException("Null arguments for HMAC");
I2PHMac mac = acquire();
mac.init(key.getData());
mac.update(data, offset, length);
mac.doFinal(target, targetOffset);
release(mac);
}
/**
* Verify the MAC inline, reducing some unnecessary memory churn.
*
* @param key session key to verify the MAC with
* @param curData MAC to verify
* @param curOffset index into curData to MAC
* @param curLength how much data in curData do we want to run the HMAC over
* @param origMAC what do we expect the MAC of curData to equal
* @param origMACOffset index into origMAC
* @param origMACLength how much of the MAC do we want to verify
* @throws IllegalArgumentException for bad key
*/
public boolean verify(SessionKey key, byte curData[], int curOffset, int curLength,
byte origMAC[], int origMACOffset, int origMACLength) {
if ((key == null) || (key.getData() == null) || (curData == null))
throw new NullPointerException("Null arguments for HMAC");
I2PHMac mac = acquire();
mac.init(key.getData());
mac.update(curData, curOffset, curLength);
byte rv[] = acquireTmp();
mac.doFinal(rv, 0);
release(mac);
boolean eq = DataHelper.eqCT(rv, 0, origMAC, origMACOffset, origMACLength);
releaseTmp(rv);
return eq;
}
private I2PHMac acquire() {
I2PHMac rv = _available.poll();
if (rv != null)
return rv;
// the HMAC is hardcoded to use SHA256 digest size
// for backwards compatability. next time we have a backwards
// incompatible change, we should update this by removing ", 32"
// SEE NOTES ABOVE
try {
MessageDigest md = MessageDigest.getInstance("MD5");
return new I2PHMac(md, 32);
} catch (NoSuchAlgorithmException nsae) {
throw new UnsupportedOperationException("MD5");
}
}
private void release(I2PHMac mac) {
_available.offer(mac);
}
/**
* @since 0.9.42
*/
public void clearCache() {
_available.clear();
}
//private static final int RUNS = 100000;
/**
* Test the BC and the JVM's implementations for speed
*/
/**** All this did was prove that we aren't compatible with standard HmacMD5
public static void main(String args[]) {
if (args.length != 2) {
System.err.println("Usage: HMACGenerator keySeedString dataString");
return;
}
byte[] rand = SHA256Generator.getInstance().calculateHash(args[0].getBytes()).getData();
byte[] data = args[1].getBytes();
Key keyObj = new SecretKeySpec(rand, "HmacMD5");
byte[] keyBytes = keyObj.getEncoded();
System.out.println("key bytes (" + keyBytes.length + ") is [" + Base64.encode(keyBytes) + "]");
SessionKey key = new SessionKey(keyBytes);
System.out.println("session key is [" + key);
System.out.println("key object is [" + keyObj);
HMACGenerator gen = new HMACGenerator(I2PAppContext.getGlobalContext());
byte[] result = new byte[16];
long start = System.currentTimeMillis();
for (int i = 0; i < RUNS; i++) {
gen.calculate(key, data, 0, data.length, result, 0);
if (i == 0)
System.out.println("MAC [" + Base64.encode(result) + "]");
}
long time = System.currentTimeMillis() - start;
System.out.println("Time for " + RUNS + " HMAC-MD5 computations:");
System.out.println("BC time (ms): " + time);
start = System.currentTimeMillis();
javax.crypto.Mac mac;
try {
mac = javax.crypto.Mac.getInstance("HmacMD5");
} catch (NoSuchAlgorithmException e) {
System.err.println("Fatal: " + e);
return;
}
for (int i = 0; i < RUNS; i++) {
try {
mac.init(keyObj);
} catch (InvalidKeyException e) {
System.err.println("Fatal: " + e);
}
byte[] sha = mac.doFinal(data);
if (i == 0)
System.out.println("MAC [" + Base64.encode(sha) + "]");
}
time = System.currentTimeMillis() - start;
System.out.println("JVM time (ms): " + time);
}
****/
}

View File

@ -6,6 +6,7 @@ import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import net.i2p.crypto.HMACGenerator;
import net.i2p.data.Base64;
import net.i2p.data.DataHelper;
import net.i2p.data.SessionKey;
@ -225,7 +226,7 @@ class UDPPacket implements CDQEntry {
* MAC matches, false otherwise.
*
*/
public synchronized boolean validate(SessionKey macKey) {
public synchronized boolean validate(SessionKey macKey, HMACGenerator hmac) {
verifyNotReleased();
//_beforeValidate = _context.clock().now();
boolean eq = false;
@ -244,14 +245,14 @@ class UDPPacket implements CDQEntry {
DataHelper.toLong(_validateBuf, off, 2, payloadLength /* ^ PacketBuilder.PROTOCOL_VERSION */ );
off += 2;
eq = _context.hmac().verify(macKey, _validateBuf, 0, off, _data, _packet.getOffset(), MAC_SIZE);
eq = hmac.verify(macKey, _validateBuf, 0, off, _data, _packet.getOffset(), MAC_SIZE);
if (!eq) {
// this is relatively frequent, as you can get old keys in PacketHandler.
Log log = _context.logManager().getLog(UDPPacket.class);
if (log.shouldLog(Log.INFO)) {
byte[] calc = new byte[32];
_context.hmac().calculate(macKey, _validateBuf, 0, off, calc, 0);
hmac.calculate(macKey, _validateBuf, 0, off, calc, 0);
StringBuilder str = new StringBuilder(512);
str.append("Bad HMAC:\n\t");
str.append(_packet.getLength()).append(" byte pkt, ");

View File

@ -20,6 +20,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import net.i2p.crypto.HMACGenerator;
import net.i2p.crypto.SigType;
import net.i2p.data.DatabaseEntry;
import net.i2p.data.DataHelper;
@ -87,6 +88,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
private long _introducersSelectedOn;
private long _lastInboundReceivedOn;
private final DHSessionKeyBuilder.Factory _dhFactory;
private final SSUHMACGenerator _hmac;
private int _mtu;
private int _mtu_ipv6;
private boolean _mismatchLogged;
@ -272,6 +274,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
_introManager = new IntroductionManager(_context, this);
_introducersSelectedOn = -1;
_lastInboundReceivedOn = -1;
_hmac = new SSUHMACGenerator();
_mtu = PeerState.LARGE_MTU;
_mtu_ipv6 = PeerState.MIN_IPV6_MTU;
setupPort();
@ -614,6 +617,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
UDPPacket.clearCache();
UDPAddress.clearCache();
_lastInboundIPv6 = 0;
_hmac.clearCache();
}
/**
@ -2748,6 +2752,14 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
return _dhFactory;
}
/**
* @return the SSU HMAC
* @since 0.9.42
*/
HMACGenerator getHMAC() {
return _hmac;
}
/**
* Does nothing
* @deprecated as of 0.9.31

View File

@ -0,0 +1,99 @@
package org.bouncycastle.oldcrypto;
/*
* Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle
* (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
/**
* The base interface for implementations of message authentication codes (MACs).
*
* modified by jrandom to use the session key byte array directly
*
* Not a public API - Not for external use!
*/
public interface Mac
{
/**
* Initialise the MAC.
*
* @param key the key required by the MAC.
* @throws IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(byte key[])
throws IllegalArgumentException;
/**
* Return the name of the algorithm the MAC implements.
*
* @return the name of the algorithm the MAC implements.
*/
public String getAlgorithmName();
/**
* Return the block size for this cipher (in bytes).
*
* @return the block size for this cipher in bytes.
*/
public int getMacSize();
/**
* add a single byte to the mac for processing.
*
* @param in the byte to be processed.
* @throws IllegalStateException if the MAC is not initialised.
*/
public void update(byte in)
throws IllegalStateException;
/**
* @param in the array containing the input.
* @param inOff the index in the array the data begins at.
* @param len the length of the input starting at inOff.
* @throws IllegalStateException if the MAC is not initialised.
*/
public void update(byte[] in, int inOff, int len)
throws IllegalStateException;
/**
* Compute the final statge of the MAC writing the output to the out
* parameter.
* <p>
* doFinal leaves the MAC in the same state it was after the last init.
*
* @param out the array the MAC is to be output to.
* @param outOff the offset into the out buffer the output is to start at.
* @throws IllegalStateException if the MAC is not initialised.
*/
public int doFinal(byte[] out, int outOff)
throws IllegalStateException;
/**
* Reset the MAC. At the end of resetting the MAC should be in the
* in the same state it was after the last init (if there was one).
*/
public void reset();
}

View File

@ -0,0 +1,200 @@
package org.bouncycastle.oldcrypto.macs;
/*
* Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle
* (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
//import org.bouncycastle.crypto.CipherParameters;
import java.security.DigestException;
import java.security.MessageDigest;
import java.util.Arrays;
import net.i2p.util.SimpleByteCache;
import org.bouncycastle.oldcrypto.Mac;
/**
* HMAC implementation based on RFC2104
*
* H(K XOR opad, H(K XOR ipad, text))
*
* modified by jrandom to use the session key byte array directly and to cache
* a frequently used buffer (called on doFinal). changes released into the public
* domain in 2005.
*
* This is renamed from HMac because the constructor HMac(digest, sz) does not exist
* in the standard bouncycastle library, thus it conflicts in JVMs that contain the
* standard library (Android).
*
* As of 0.9.12, refactored to use standard MessageDigest.
*
* Deprecated - Do not use outside of router or Syndie.
* Not a public API - Not for external use!
*/
public class I2PHMac
implements Mac
{
private final static int BLOCK_LENGTH = 64;
private final static byte IPAD = (byte)0x36;
private final static byte OPAD = (byte)0x5C;
private final MessageDigest digest;
private final int digestSize;
private final byte[] inputPad = new byte[BLOCK_LENGTH];
private final byte[] outputPad = new byte[BLOCK_LENGTH];
/**
* Standard HMAC, size == digest size.
* @deprecated Use javax.crypto.Mac
*/
@Deprecated
public I2PHMac(MessageDigest digest) {
this(digest, digest.getDigestLength());
}
/**
* @param sz override the digest's size, nonstandard if different.
* SEE NOTES in HMACGenerator about why this isn't compatible with standard HmacMD5
*/
public I2PHMac(MessageDigest digest, int sz) {
this.digest = digest;
this.digestSize = sz;
}
public String getAlgorithmName()
{
return digest.getAlgorithm() + "/HMAC";
}
public MessageDigest getUnderlyingDigest()
{
return digest;
}
//public void init(
// CipherParameters params)
//{
public void init(byte key[])
{
digest.reset();
//byte[] key = ((KeyParameter)params).getKey();
if (key.length > BLOCK_LENGTH)
{
digest.update(key, 0, key.length);
try {
digest.digest(inputPad, 0, digestSize);
} catch (DigestException de) {
digest.reset();
throw new IllegalArgumentException(de);
}
for (int i = digestSize; i < inputPad.length; i++)
{
inputPad[i] = 0;
}
}
else
{
System.arraycopy(key, 0, inputPad, 0, key.length);
for (int i = key.length; i < inputPad.length; i++)
{
inputPad[i] = 0;
}
}
// why reallocate? it hasn't changed sizes, and the arraycopy
// below fills it completely...
//outputPad = new byte[inputPad.length];
System.arraycopy(inputPad, 0, outputPad, 0, inputPad.length);
for (int i = 0; i < inputPad.length; i++)
{
inputPad[i] ^= IPAD;
}
for (int i = 0; i < outputPad.length; i++)
{
outputPad[i] ^= OPAD;
}
digest.update(inputPad, 0, inputPad.length);
}
public int getMacSize() {
return digestSize;
}
public void update(byte in) {
digest.update(in);
}
public void update(byte[] in, int inOff, int len) {
digest.update(in, inOff, len);
}
public int doFinal(byte[] out, int outOff) {
byte[] tmp = acquireTmp(digestSize);
//byte[] tmp = new byte[digestSize];
try {
digest.digest(tmp, 0, digestSize);
digest.update(outputPad, 0, outputPad.length);
digest.update(tmp, 0, tmp.length);
return digest.digest(out, outOff, digestSize);
} catch (DigestException de) {
throw new IllegalArgumentException(de);
} finally {
releaseTmp(tmp);
reset();
}
}
private static byte[] acquireTmp(int sz) {
byte[] rv = SimpleByteCache.acquire(sz);
Arrays.fill(rv, (byte)0x0);
return rv;
}
private static void releaseTmp(byte buf[]) {
SimpleByteCache.release(buf);
}
/**
* Reset the mac generator.
*/
public void reset()
{
/*
* reset the underlying digest.
*/
digest.reset();
/*
* reinitialize the digest.
*/
digest.update(inputPad, 0, inputPad.length);
}
}

View File

@ -0,0 +1,17 @@
<html>
<body>
<p>
This is from some very old version of bouncycastle, part of package org.bouncycastle.crypto.
Android bundled something similar in pre-Gingerbread, but upgraded to a later, incompatible version
in Gingerbread. As of Java 1.4 these are in javax.crypto - more or less.
To avoid having to make two different versions of our Android app, we rename to org.bouncycastle.oldcrypto.
</p><p>
Ref: <a href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/package-summary.html">javax.crypto</a>
and
<a href="http://code.google.com/p/android/issues/detail?id=3280">this android issue</a>.
</p><p>
Moved from i2p.jar to router.jar as of 0.9.42.
Not a public API! Not for external use!
</p>
</body>
</html>

View File

@ -0,0 +1,17 @@
<html>
<body>
<p>
This is from some very old version of bouncycastle, part of package org.bouncycastle.crypto.
Android bundled something similar in pre-Gingerbread, but upgraded to a later, incompatible version
in Gingerbread. As of Java 1.4 these are in javax.crypto - more or less.
To avoid having to make two different versions of our Android app, we rename to org.bouncycastle.oldcrypto.
</p><p>
Ref: <a href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/package-summary.html">javax.crypto</a>
and
<a href="http://code.google.com/p/android/issues/detail?id=3280">this android issue</a>.
</p><p>
Moved from i2p.jar to router.jar as of 0.9.42.
Not a public API! Not for external use!
</p>
</body>
</html>

View File

@ -0,0 +1,124 @@
package net.i2p.router.transport.udp;
/*
* 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.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
/**
* Warning, misnamed, this tests the SSU HMAC,
* not net.i2p.crypto.HMAC256Generator
*/
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();
byte[] output = new byte[32];
SSUHMACGenerator hmac = new SSUHMACGenerator();
hmac.calculate(key, "qwerty".getBytes(), 0, 6, output, 0);
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 = "abc".getBytes();
StringBuilder buf = new StringBuilder();
for (int x = 0; x < 2*1024; x++) {
buf.append("a");
}
byte[] mmess = DataHelper.getASCII(buf.toString()); // new String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq").getBytes();
buf = new StringBuilder();
for (int x = 0; x < 10000; x++) {
buf.append("a");
}
byte[] lmess = DataHelper.getASCII(buf.toString());
// warm up the engines
hmac.calculate(key, smess, 0, smess.length, output, 0);
hmac.calculate(key, mmess, 0, mmess.length, output, 0);
hmac.calculate(key, lmess, 0, lmess.length, output, 0);
long before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
hmac.calculate(key, smess, 0, smess.length, output, 0);
long after = System.currentTimeMillis();
display(times, before, after, smess.length, "3 byte");
before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
hmac.calculate(key, mmess, 0, mmess.length, output, 0);
after = System.currentTimeMillis();
display(times, before, after, mmess.length, "2KB");
before = System.currentTimeMillis();
for (int x = 0; x < times; x++)
hmac.calculate(key, lmess, 0, lmess.length, output, 0);
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

@ -0,0 +1,40 @@
package net.i2p.router.transport.udp;
/*
* 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;
/**
* Warning, misnamed, this tests the SSU HMAC,
* not net.i2p.crypto.HMAC256Generator
*/
public class HMACSHA256Test extends TestCase{
private I2PAppContext _context;
protected void setUp() {
_context = I2PAppContext.getGlobalContext();
}
public void testMultiple(){
SSUHMACGenerator hmac = new SSUHMACGenerator();
int size = 1;
for(int i = 0; i < 16; i++){
SessionKey key = _context.keyGenerator().generateSessionKey();
byte[] message = new byte[size];
size*=2;
_context.random().nextBytes(message);
byte[] output = new byte[32];
hmac.calculate(key, message, 0, message.length, output, 0);
}
}
}