Static imports.

This commit is contained in:
akwizgran
2018-11-23 12:28:11 +00:00
parent b342759e06
commit ad9191b076
200 changed files with 781 additions and 681 deletions

View File

@@ -17,11 +17,13 @@ import java.util.logging.Logger;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Logger.getLogger;
class AndroidAccountManager extends AccountManagerImpl class AndroidAccountManager extends AccountManagerImpl
implements AccountManager { implements AccountManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidAccountManager.class.getName()); getLogger(AndroidAccountManager.class.getName());
private static final String PREF_DB_KEY = "key"; private static final String PREF_DB_KEY = "key";

View File

@@ -37,13 +37,14 @@ import static android.os.PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED;
import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@ParametersNotNullByDefault @ParametersNotNullByDefault
class AndroidNetworkManager implements NetworkManager, Service { class AndroidNetworkManager implements NetworkManager, Service {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidNetworkManager.class.getName()); getLogger(AndroidNetworkManager.class.getName());
// See android.net.wifi.WifiManager // See android.net.wifi.WifiManager
private static final String WIFI_AP_STATE_CHANGED_ACTION = private static final String WIFI_AP_STATE_CHANGED_ACTION =

View File

@@ -51,6 +51,7 @@ import static android.bluetooth.BluetoothDevice.EXTRA_DEVICE;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress; import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@@ -58,7 +59,7 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> { class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidBluetoothPlugin.class.getName()); getLogger(AndroidBluetoothPlugin.class.getName());
private static final int MAX_DISCOVERY_MS = 10_000; private static final int MAX_DISCOVERY_MS = 10_000;

View File

@@ -32,17 +32,18 @@ import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION.SDK_INT;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault @NotNullByDefault
class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener { class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
private static final Logger LOG =
getLogger(AndroidLanTcpPlugin.class.getName());
private static final byte[] WIFI_AP_ADDRESS_BYTES = private static final byte[] WIFI_AP_ADDRESS_BYTES =
{(byte) 192, (byte) 168, 43, 1}; {(byte) 192, (byte) 168, 43, 1};
private static final InetAddress WIFI_AP_ADDRESS; private static final InetAddress WIFI_AP_ADDRESS;
private static final Logger LOG =
Logger.getLogger(AndroidLanTcpPlugin.class.getName());
static { static {
try { try {
WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES); WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES);

View File

@@ -26,12 +26,14 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import static java.util.logging.Logger.getLogger;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
public class AndroidTorPluginFactory implements DuplexPluginFactory { public class AndroidTorPluginFactory implements DuplexPluginFactory {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidTorPluginFactory.class.getName()); getLogger(AndroidTorPluginFactory.class.getName());
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds

View File

@@ -15,12 +15,13 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static android.content.Context.TELEPHONY_SERVICE; import static android.content.Context.TELEPHONY_SERVICE;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault @NotNullByDefault
class AndroidLocationUtils implements LocationUtils { class AndroidLocationUtils implements LocationUtils {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidLocationUtils.class.getName()); getLogger(AndroidLocationUtils.class.getName());
private final Context appContext; private final Context appContext;

View File

@@ -14,6 +14,7 @@ import java.util.List;
import static android.content.Context.MODE_PRIVATE; import static android.content.Context.MODE_PRIVATE;
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION.SDK_INT;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
public class AndroidUtils { public class AndroidUtils {
@@ -49,7 +50,7 @@ public class AndroidUtils {
} }
private static boolean isValidBluetoothAddress(String address) { private static boolean isValidBluetoothAddress(String address) {
return !StringUtils.isNullOrEmpty(address) return !isNullOrEmpty(address)
&& BluetoothAdapter.checkBluetoothAddress(address) && BluetoothAdapter.checkBluetoothAddress(address)
&& !address.equals(FAKE_BLUETOOTH_ADDRESS); && !address.equals(FAKE_BLUETOOTH_ADDRESS);
} }

View File

@@ -14,13 +14,14 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@ThreadSafe @ThreadSafe
@NotNullByDefault @NotNullByDefault
public class RenewableWakeLock { public class RenewableWakeLock {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(RenewableWakeLock.class.getName()); getLogger(RenewableWakeLock.class.getName());
/** /**
* Automatically release the lock this many milliseconds after it's due * Automatically release the lock this many milliseconds after it's due

View File

@@ -1,13 +1,14 @@
package org.briarproject.bramble.api; package org.briarproject.bramble.api;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import static org.briarproject.bramble.util.StringUtils.toHexString;
/** /**
* A wrapper around a byte array, to allow it to be stored in maps etc. * A wrapper around a byte array, to allow it to be stored in maps etc.
*/ */
@@ -56,8 +57,7 @@ public class Bytes implements Comparable<Bytes> {
@Override @Override
public String toString() { public String toString() {
return getClass().getSimpleName() + return getClass().getSimpleName() + "(" + toHexString(getBytes()) + ")";
"(" + StringUtils.toHexString(getBytes()) + ")";
} }
public static class BytesComparator implements Comparator<Bytes> { public static class BytesComparator implements Comparator<Bytes> {

View File

@@ -16,6 +16,7 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE;
@Immutable @Immutable
@@ -23,7 +24,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOC
public abstract class BdfMessageValidator implements MessageValidator { public abstract class BdfMessageValidator implements MessageValidator {
protected static final Logger LOG = protected static final Logger LOG =
Logger.getLogger(BdfMessageValidator.class.getName()); getLogger(BdfMessageValidator.class.getName());
protected final ClientHelper clientHelper; protected final ClientHelper clientHelper;
protected final MetadataEncoder metadataEncoder; protected final MetadataEncoder metadataEncoder;

View File

@@ -2,12 +2,12 @@ package org.briarproject.bramble.api.identity;
import org.briarproject.bramble.api.Nameable; import org.briarproject.bramble.api.Nameable;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH; import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH; import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* A pseudonym for a user. * A pseudonym for a user.
@@ -28,7 +28,7 @@ public class Author implements Nameable {
public Author(AuthorId id, int formatVersion, String name, public Author(AuthorId id, int formatVersion, String name,
byte[] publicKey) { byte[] publicKey) {
int nameLength = StringUtils.toUtf8(name).length; int nameLength = toUtf8(name).length;
if (nameLength == 0 || nameLength > MAX_AUTHOR_NAME_LENGTH) if (nameLength == 0 || nameLength > MAX_AUTHOR_NAME_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
if (publicKey.length == 0 || publicKey.length > MAX_PUBLIC_KEY_LENGTH) if (publicKey.length == 0 || publicKey.length > MAX_PUBLIC_KEY_LENGTH)

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.api.plugin; package org.briarproject.bramble.api.plugin;
import org.briarproject.bramble.util.StringUtils; import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* Type-safe wrapper for a namespaced string that uniquely identifies a * Type-safe wrapper for a namespaced string that uniquely identifies a
@@ -16,7 +16,7 @@ public class TransportId {
private final String id; private final String id;
public TransportId(String id) { public TransportId(String id) {
int length = StringUtils.toUtf8(id).length; int length = toUtf8(id).length;
if (length == 0 || length > MAX_TRANSPORT_ID_LENGTH) if (length == 0 || length > MAX_TRANSPORT_ID_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
this.id = id; this.id = id;

View File

@@ -1,10 +1,11 @@
package org.briarproject.bramble.api.sync; package org.briarproject.bramble.api.sync;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* Type-safe wrapper for a namespaced string that uniquely identifies a sync * Type-safe wrapper for a namespaced string that uniquely identifies a sync
* client. * client.
@@ -21,7 +22,7 @@ public class ClientId implements Comparable<ClientId> {
private final String id; private final String id;
public ClientId(String id) { public ClientId(String id) {
int length = StringUtils.toUtf8(id).length; int length = toUtf8(id).length;
if (length == 0 || length > MAX_CLIENT_ID_LENGTH) if (length == 0 || length > MAX_CLIENT_ID_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
this.id = id; this.id = id;

View File

@@ -16,12 +16,13 @@ import java.util.logging.Logger;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@NotNullByDefault @NotNullByDefault
public class IoUtils { public class IoUtils {
private static final Logger LOG = Logger.getLogger(IoUtils.class.getName()); private static final Logger LOG = getLogger(IoUtils.class.getName());
public static void deleteFileOrDir(File f) { public static void deleteFileOrDir(File f) {
if (f.isFile()) { if (f.isFile()) {

View File

@@ -7,13 +7,15 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@NotNullByDefault @NotNullByDefault
public class ValidationUtils { public class ValidationUtils {
public static void checkLength(@Nullable String s, int minLength, public static void checkLength(@Nullable String s, int minLength,
int maxLength) throws FormatException { int maxLength) throws FormatException {
if (s != null) { if (s != null) {
int length = StringUtils.toUtf8(s).length; int length = toUtf8(s).length;
if (length < minLength) throw new FormatException(); if (length < minLength) throw new FormatException();
if (length > maxLength) throw new FormatException(); if (length > maxLength) throw new FormatException();
} }
@@ -21,7 +23,7 @@ public class ValidationUtils {
public static void checkLength(@Nullable String s, int length) public static void checkLength(@Nullable String s, int length)
throws FormatException { throws FormatException {
if (s != null && StringUtils.toUtf8(s).length != length) if (s != null && toUtf8(s).length != length)
throw new FormatException(); throw new FormatException();
} }

View File

@@ -10,6 +10,7 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.GuardedBy;
import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINE;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
/** /**
@@ -42,7 +43,7 @@ public class PoliteExecutor implements Executor {
int maxConcurrentTasks) { int maxConcurrentTasks) {
this.delegate = delegate; this.delegate = delegate;
this.maxConcurrentTasks = maxConcurrentTasks; this.maxConcurrentTasks = maxConcurrentTasks;
log = Logger.getLogger(tag); log = getLogger(tag);
} }
@Override @Override

View File

@@ -9,6 +9,7 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINE;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
@NotNullByDefault @NotNullByDefault
@@ -22,7 +23,7 @@ public class TimeLoggingExecutor extends ThreadPoolExecutor {
RejectedExecutionHandler handler) { RejectedExecutionHandler handler) {
super(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, super(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue,
handler); handler);
log = Logger.getLogger(tag); log = getLogger(tag);
} }
@Override @Override

View File

@@ -22,6 +22,7 @@ import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.StringUtils.fromHexString; import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString; import static org.briarproject.bramble.util.StringUtils.toHexString;
@@ -31,7 +32,7 @@ import static org.briarproject.bramble.util.StringUtils.toHexString;
class AccountManagerImpl implements AccountManager { class AccountManagerImpl implements AccountManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AccountManagerImpl.class.getName()); getLogger(AccountManagerImpl.class.getName());
private static final String DB_KEY_FILENAME = "db.key"; private static final String DB_KEY_FILENAME = "db.key";
private static final String DB_KEY_BACKUP_FILENAME = "db.key.bak"; private static final String DB_KEY_BACKUP_FILENAME = "db.key.bak";

View File

@@ -43,6 +43,7 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.contact.RecordTypes.CONTACT_INFO; import static org.briarproject.bramble.api.contact.RecordTypes.CONTACT_INFO;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH; import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@@ -54,7 +55,7 @@ import static org.briarproject.bramble.util.ValidationUtils.checkSize;
class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask { class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ContactExchangeTaskImpl.class.getName()); getLogger(ContactExchangeTaskImpl.class.getName());
private static final String SIGNING_LABEL_EXCHANGE = private static final String SIGNING_LABEL_EXCHANGE =
"org.briarproject.briar.contact/EXCHANGE"; "org.briarproject.briar.contact/EXCHANGE";

View File

@@ -2,13 +2,15 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.FormatException; import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
@NotNullByDefault @NotNullByDefault
class AsciiArmour { class AsciiArmour {
static String wrap(byte[] b, int lineLength) { static String wrap(byte[] b, int lineLength) {
String wrapped = StringUtils.toHexString(b); String wrapped = toHexString(b);
StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder();
int length = wrapped.length(); int length = wrapped.length();
for (int i = 0; i < length; i += lineLength) { for (int i = 0; i < length; i += lineLength) {
@@ -21,7 +23,7 @@ class AsciiArmour {
static byte[] unwrap(String s) throws FormatException { static byte[] unwrap(String s) throws FormatException {
try { try {
return StringUtils.fromHexString(s.replaceAll("[^0-9a-fA-F]", "")); return fromHexString(s.replaceAll("[^0-9a-fA-F]", ""));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new FormatException(); throw new FormatException();
} }

View File

@@ -12,8 +12,6 @@ import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.SecureRandomProvider; import org.briarproject.bramble.api.system.SecureRandomProvider;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.StringUtils;
import org.spongycastle.crypto.CryptoException; import org.spongycastle.crypto.CryptoException;
import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.digests.Blake2bDigest; import org.spongycastle.crypto.digests.Blake2bDigest;
@@ -31,15 +29,19 @@ import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint32;
import static org.briarproject.bramble.util.ByteUtils.writeUint32;
import static org.briarproject.bramble.util.LogUtils.logDuration; import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@NotNullByDefault @NotNullByDefault
class CryptoComponentImpl implements CryptoComponent { class CryptoComponentImpl implements CryptoComponent {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(CryptoComponentImpl.class.getName()); getLogger(CryptoComponentImpl.class.getName());
private static final int SIGNATURE_KEY_PAIR_BITS = 256; private static final int SIGNATURE_KEY_PAIR_BITS = 256;
private static final int STORAGE_IV_BYTES = 24; // 196 bits private static final int STORAGE_IV_BYTES = 24; // 196 bits
@@ -216,26 +218,26 @@ class CryptoComponentImpl implements CryptoComponent {
private void updateSignature(Signature signature, String label, private void updateSignature(Signature signature, String label,
byte[] toSign) throws GeneralSecurityException { byte[] toSign) throws GeneralSecurityException {
byte[] labelBytes = StringUtils.toUtf8(label); byte[] labelBytes = toUtf8(label);
byte[] length = new byte[INT_32_BYTES]; byte[] length = new byte[INT_32_BYTES];
ByteUtils.writeUint32(labelBytes.length, length, 0); writeUint32(labelBytes.length, length, 0);
signature.update(length); signature.update(length);
signature.update(labelBytes); signature.update(labelBytes);
ByteUtils.writeUint32(toSign.length, length, 0); writeUint32(toSign.length, length, 0);
signature.update(length); signature.update(length);
signature.update(toSign); signature.update(toSign);
} }
@Override @Override
public byte[] hash(String label, byte[]... inputs) { public byte[] hash(String label, byte[]... inputs) {
byte[] labelBytes = StringUtils.toUtf8(label); byte[] labelBytes = toUtf8(label);
Digest digest = new Blake2bDigest(256); Digest digest = new Blake2bDigest(256);
byte[] length = new byte[INT_32_BYTES]; byte[] length = new byte[INT_32_BYTES];
ByteUtils.writeUint32(labelBytes.length, length, 0); writeUint32(labelBytes.length, length, 0);
digest.update(length, 0, length.length); digest.update(length, 0, length.length);
digest.update(labelBytes, 0, labelBytes.length); digest.update(labelBytes, 0, labelBytes.length);
for (byte[] input : inputs) { for (byte[] input : inputs) {
ByteUtils.writeUint32(input.length, length, 0); writeUint32(input.length, length, 0);
digest.update(length, 0, length.length); digest.update(length, 0, length.length);
digest.update(input, 0, input.length); digest.update(input, 0, input.length);
} }
@@ -246,14 +248,14 @@ class CryptoComponentImpl implements CryptoComponent {
@Override @Override
public byte[] mac(String label, SecretKey macKey, byte[]... inputs) { public byte[] mac(String label, SecretKey macKey, byte[]... inputs) {
byte[] labelBytes = StringUtils.toUtf8(label); byte[] labelBytes = toUtf8(label);
Digest mac = new Blake2bDigest(macKey.getBytes(), 32, null, null); Digest mac = new Blake2bDigest(macKey.getBytes(), 32, null, null);
byte[] length = new byte[INT_32_BYTES]; byte[] length = new byte[INT_32_BYTES];
ByteUtils.writeUint32(labelBytes.length, length, 0); writeUint32(labelBytes.length, length, 0);
mac.update(length, 0, length.length); mac.update(length, 0, length.length);
mac.update(labelBytes, 0, labelBytes.length); mac.update(labelBytes, 0, labelBytes.length);
for (byte[] input : inputs) { for (byte[] input : inputs) {
ByteUtils.writeUint32(input.length, length, 0); writeUint32(input.length, length, 0);
mac.update(length, 0, length.length); mac.update(length, 0, length.length);
mac.update(input, 0, input.length); mac.update(input, 0, input.length);
} }
@@ -300,7 +302,7 @@ class CryptoComponentImpl implements CryptoComponent {
System.arraycopy(salt, 0, output, outputOff, salt.length); System.arraycopy(salt, 0, output, outputOff, salt.length);
outputOff += salt.length; outputOff += salt.length;
// Cost parameter // Cost parameter
ByteUtils.writeUint32(cost, output, outputOff); writeUint32(cost, output, outputOff);
outputOff += INT_32_BYTES; outputOff += INT_32_BYTES;
// IV // IV
System.arraycopy(iv, 0, output, outputOff, iv.length); System.arraycopy(iv, 0, output, outputOff, iv.length);
@@ -336,7 +338,7 @@ class CryptoComponentImpl implements CryptoComponent {
System.arraycopy(input, inputOff, salt, 0, salt.length); System.arraycopy(input, inputOff, salt, 0, salt.length);
inputOff += salt.length; inputOff += salt.length;
// Cost parameter // Cost parameter
long cost = ByteUtils.readUint32(input, inputOff); long cost = readUint32(input, inputOff);
inputOff += INT_32_BYTES; inputOff += INT_32_BYTES;
if (cost < 2 || cost > Integer.MAX_VALUE) if (cost < 2 || cost > Integer.MAX_VALUE)
return null; // Invalid cost parameter return null; // Invalid cost parameter

View File

@@ -1,13 +1,15 @@
package org.briarproject.bramble.crypto; package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_HEADER_PLAINTEXT_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_HEADER_PLAINTEXT_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_NONCE_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_NONCE_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_PAYLOAD_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_PAYLOAD_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
@NotNullByDefault @NotNullByDefault
class FrameEncoder { class FrameEncoder {
@@ -16,7 +18,7 @@ class FrameEncoder {
if (dest.length < FRAME_NONCE_LENGTH) if (dest.length < FRAME_NONCE_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
if (frameNumber < 0) throw new IllegalArgumentException(); if (frameNumber < 0) throw new IllegalArgumentException();
ByteUtils.writeUint64(frameNumber, dest, 0); writeUint64(frameNumber, dest, 0);
if (header) dest[0] |= 0x80; if (header) dest[0] |= 0x80;
for (int i = INT_64_BYTES; i < FRAME_NONCE_LENGTH; i++) dest[i] = 0; for (int i = INT_64_BYTES; i < FRAME_NONCE_LENGTH; i++) dest[i] = 0;
} }
@@ -29,8 +31,8 @@ class FrameEncoder {
if (paddingLength < 0) throw new IllegalArgumentException(); if (paddingLength < 0) throw new IllegalArgumentException();
if (payloadLength + paddingLength > MAX_PAYLOAD_LENGTH) if (payloadLength + paddingLength > MAX_PAYLOAD_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
ByteUtils.writeUint16(payloadLength, dest, 0); writeUint16(payloadLength, dest, 0);
ByteUtils.writeUint16(paddingLength, dest, INT_16_BYTES); writeUint16(paddingLength, dest, INT_16_BYTES);
if (finalFrame) dest[0] |= 0x80; if (finalFrame) dest[0] |= 0x80;
} }
@@ -43,12 +45,12 @@ class FrameEncoder {
static int getPayloadLength(byte[] header) { static int getPayloadLength(byte[] header) {
if (header.length < FRAME_HEADER_PLAINTEXT_LENGTH) if (header.length < FRAME_HEADER_PLAINTEXT_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
return ByteUtils.readUint16(header, 0) & 0x7FFF; return readUint16(header, 0) & 0x7FFF;
} }
static int getPaddingLength(byte[] header) { static int getPaddingLength(byte[] header) {
if (header.length < FRAME_HEADER_PLAINTEXT_LENGTH) if (header.length < FRAME_HEADER_PLAINTEXT_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
return ByteUtils.readUint16(header, INT_16_BYTES); return readUint16(header, INT_16_BYTES);
} }
} }

View File

@@ -5,7 +5,6 @@ import org.briarproject.bramble.api.crypto.KeyParser;
import org.briarproject.bramble.api.crypto.PrivateKey; import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey; import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import org.spongycastle.asn1.teletrust.TeleTrusTNamedCurves; import org.spongycastle.asn1.teletrust.TeleTrusTNamedCurves;
import org.spongycastle.asn1.x9.X9ECParameters; import org.spongycastle.asn1.x9.X9ECParameters;
import org.spongycastle.crypto.AsymmetricCipherKeyPair; import org.spongycastle.crypto.AsymmetricCipherKeyPair;
@@ -45,6 +44,9 @@ import java.util.Scanner;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
public class MessageEncrypter { public class MessageEncrypter {
@@ -210,11 +212,11 @@ public class MessageEncrypter {
MessageEncrypter encrypter = new MessageEncrypter(random); MessageEncrypter encrypter = new MessageEncrypter(random);
KeyPair keyPair = encrypter.generateKeyPair(); KeyPair keyPair = encrypter.generateKeyPair();
PrintStream out = new PrintStream(new FileOutputStream(publicKeyFile)); PrintStream out = new PrintStream(new FileOutputStream(publicKeyFile));
out.print(StringUtils.toHexString(keyPair.getPublic().getEncoded())); out.print(toHexString(keyPair.getPublic().getEncoded()));
out.flush(); out.flush();
out.close(); out.close();
out = new PrintStream(new FileOutputStream(privateKeyFile)); out = new PrintStream(new FileOutputStream(privateKeyFile));
out.print(StringUtils.toHexString(keyPair.getPrivate().getEncoded())); out.print(toHexString(keyPair.getPrivate().getEncoded()));
out.flush(); out.flush();
out.close(); out.close();
} }
@@ -223,7 +225,7 @@ public class MessageEncrypter {
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
MessageEncrypter encrypter = new MessageEncrypter(random); MessageEncrypter encrypter = new MessageEncrypter(random);
InputStream in = new FileInputStream(publicKeyFile); InputStream in = new FileInputStream(publicKeyFile);
byte[] keyBytes = StringUtils.fromHexString(readFully(in).trim()); byte[] keyBytes = fromHexString(readFully(in).trim());
PublicKey publicKey = PublicKey publicKey =
encrypter.getKeyParser().parsePublicKey(keyBytes); encrypter.getKeyParser().parsePublicKey(keyBytes);
String message = readFully(System.in); String message = readFully(System.in);
@@ -236,7 +238,7 @@ public class MessageEncrypter {
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
MessageEncrypter encrypter = new MessageEncrypter(random); MessageEncrypter encrypter = new MessageEncrypter(random);
InputStream in = new FileInputStream(privateKeyFile); InputStream in = new FileInputStream(privateKeyFile);
byte[] keyBytes = StringUtils.fromHexString(readFully(in).trim()); byte[] keyBytes = fromHexString(readFully(in).trim());
PrivateKey privateKey = PrivateKey privateKey =
encrypter.getKeyParser().parsePrivateKey(keyBytes); encrypter.getKeyParser().parsePrivateKey(keyBytes);
byte[] ciphertext = AsciiArmour.unwrap(readFully(System.in)); byte[] ciphertext = AsciiArmour.unwrap(readFully(System.in));

View File

@@ -2,7 +2,6 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.util.StringUtils;
import org.spongycastle.crypto.generators.SCrypt; import org.spongycastle.crypto.generators.SCrypt;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -10,13 +9,14 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logDuration; import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
class ScryptKdf implements PasswordBasedKdf { class ScryptKdf implements PasswordBasedKdf {
private static final Logger LOG = private static final Logger LOG = getLogger(ScryptKdf.class.getName());
Logger.getLogger(ScryptKdf.class.getName());
private static final int MIN_COST = 256; // Min parameter N private static final int MIN_COST = 256; // Min parameter N
private static final int MAX_COST = 1024 * 1024; // Max parameter N private static final int MAX_COST = 1024 * 1024; // Max parameter N
@@ -53,7 +53,7 @@ class ScryptKdf implements PasswordBasedKdf {
@Override @Override
public SecretKey deriveKey(String password, byte[] salt, int cost) { public SecretKey deriveKey(String password, byte[] salt, int cost) {
long start = now(); long start = now();
byte[] passwordBytes = StringUtils.toUtf8(password); byte[] passwordBytes = toUtf8(password);
SecretKey k = new SecretKey(SCrypt.generate(passwordBytes, salt, cost, SecretKey k = new SecretKey(SCrypt.generate(passwordBytes, salt, cost,
BLOCK_SIZE, PARALLELIZATION, SecretKey.LENGTH)); BLOCK_SIZE, PARALLELIZATION, SecretKey.LENGTH));
logDuration(LOG, "Deriving key from password", start); logDuration(LOG, "Deriving key from password", start);

View File

@@ -16,6 +16,7 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logDuration; import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
@@ -28,8 +29,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
@NotNullByDefault @NotNullByDefault
class Sec1KeyParser implements KeyParser { class Sec1KeyParser implements KeyParser {
private static final Logger LOG = private static final Logger LOG = getLogger(Sec1KeyParser.class.getName());
Logger.getLogger(Sec1KeyParser.class.getName());
private final ECDomainParameters params; private final ECDomainParameters params;
private final BigInteger modulus; private final BigInteger modulus;

View File

@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamDecrypter; import org.briarproject.bramble.api.crypto.StreamDecrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
@@ -26,6 +25,8 @@ import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_H
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_PLAINTEXT_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_PLAINTEXT_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
import static org.briarproject.bramble.util.ByteUtils.readUint64;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
@@ -145,12 +146,11 @@ class StreamDecrypterImpl implements StreamDecrypter {
throw new FormatException(); throw new FormatException();
} }
// Check the protocol version // Check the protocol version
int receivedProtocolVersion = int receivedProtocolVersion = readUint16(streamHeaderPlaintext, 0);
ByteUtils.readUint16(streamHeaderPlaintext, 0);
if (receivedProtocolVersion != PROTOCOL_VERSION) if (receivedProtocolVersion != PROTOCOL_VERSION)
throw new FormatException(); throw new FormatException();
// Check the stream number // Check the stream number
long receivedStreamNumber = ByteUtils.readUint64(streamHeaderPlaintext, long receivedStreamNumber = readUint64(streamHeaderPlaintext,
INT_16_BYTES); INT_16_BYTES);
if (receivedStreamNumber != streamNumber) throw new FormatException(); if (receivedStreamNumber != streamNumber) throw new FormatException();
// Extract the frame key // Extract the frame key

View File

@@ -3,7 +3,6 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamEncrypter; import org.briarproject.bramble.api.crypto.StreamEncrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -24,6 +23,8 @@ import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_H
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_PLAINTEXT_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_PLAINTEXT_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
@@ -118,9 +119,8 @@ class StreamEncrypterImpl implements StreamEncrypter {
private void writeStreamHeader() throws IOException { private void writeStreamHeader() throws IOException {
// The header contains the protocol version, stream number and frame key // The header contains the protocol version, stream number and frame key
byte[] streamHeaderPlaintext = new byte[STREAM_HEADER_PLAINTEXT_LENGTH]; byte[] streamHeaderPlaintext = new byte[STREAM_HEADER_PLAINTEXT_LENGTH];
ByteUtils.writeUint16(PROTOCOL_VERSION, streamHeaderPlaintext, 0); writeUint16(PROTOCOL_VERSION, streamHeaderPlaintext, 0);
ByteUtils.writeUint64(streamNumber, streamHeaderPlaintext, writeUint64(streamNumber, streamHeaderPlaintext, INT_16_BYTES);
INT_16_BYTES);
System.arraycopy(frameKey.getBytes(), 0, streamHeaderPlaintext, System.arraycopy(frameKey.getBytes(), 0, streamHeaderPlaintext,
INT_16_BYTES + INT_64_BYTES, SecretKey.LENGTH); INT_16_BYTES + INT_64_BYTES, SecretKey.LENGTH);
byte[] streamHeaderCiphertext = new byte[STREAM_HEADER_LENGTH]; byte[] streamHeaderCiphertext = new byte[STREAM_HEADER_LENGTH];

View File

@@ -7,8 +7,6 @@ import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.transport.IncomingKeys; import org.briarproject.bramble.api.transport.IncomingKeys;
import org.briarproject.bramble.api.transport.OutgoingKeys; import org.briarproject.bramble.api.transport.OutgoingKeys;
import org.briarproject.bramble.api.transport.TransportKeys; import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.StringUtils;
import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.digests.Blake2bDigest; import org.spongycastle.crypto.digests.Blake2bDigest;
@@ -24,6 +22,9 @@ import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED;
import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
class TransportCryptoImpl implements TransportCrypto { class TransportCryptoImpl implements TransportCrypto {
@@ -91,21 +92,21 @@ class TransportCryptoImpl implements TransportCrypto {
private SecretKey rotateKey(SecretKey k, long rotationPeriod) { private SecretKey rotateKey(SecretKey k, long rotationPeriod) {
byte[] period = new byte[INT_64_BYTES]; byte[] period = new byte[INT_64_BYTES];
ByteUtils.writeUint64(rotationPeriod, period, 0); writeUint64(rotationPeriod, period, 0);
return crypto.deriveKey(ROTATE_LABEL, k, period); return crypto.deriveKey(ROTATE_LABEL, k, period);
} }
private SecretKey deriveTagKey(SecretKey master, TransportId t, private SecretKey deriveTagKey(SecretKey master, TransportId t,
boolean alice) { boolean alice) {
String label = alice ? ALICE_TAG_LABEL : BOB_TAG_LABEL; String label = alice ? ALICE_TAG_LABEL : BOB_TAG_LABEL;
byte[] id = StringUtils.toUtf8(t.getString()); byte[] id = toUtf8(t.getString());
return crypto.deriveKey(label, master, id); return crypto.deriveKey(label, master, id);
} }
private SecretKey deriveHeaderKey(SecretKey master, TransportId t, private SecretKey deriveHeaderKey(SecretKey master, TransportId t,
boolean alice) { boolean alice) {
String label = alice ? ALICE_HEADER_LABEL : BOB_HEADER_LABEL; String label = alice ? ALICE_HEADER_LABEL : BOB_HEADER_LABEL;
byte[] id = StringUtils.toUtf8(t.getString()); byte[] id = toUtf8(t.getString());
return crypto.deriveKey(label, master, id); return crypto.deriveKey(label, master, id);
} }
@@ -125,10 +126,10 @@ class TransportCryptoImpl implements TransportCrypto {
// The input is the protocol version as a 16-bit integer, followed by // The input is the protocol version as a 16-bit integer, followed by
// the stream number as a 64-bit integer // the stream number as a 64-bit integer
byte[] protocolVersionBytes = new byte[INT_16_BYTES]; byte[] protocolVersionBytes = new byte[INT_16_BYTES];
ByteUtils.writeUint16(protocolVersion, protocolVersionBytes, 0); writeUint16(protocolVersion, protocolVersionBytes, 0);
prf.update(protocolVersionBytes, 0, protocolVersionBytes.length); prf.update(protocolVersionBytes, 0, protocolVersionBytes.length);
byte[] streamNumberBytes = new byte[INT_64_BYTES]; byte[] streamNumberBytes = new byte[INT_64_BYTES];
ByteUtils.writeUint64(streamNumber, streamNumberBytes, 0); writeUint64(streamNumber, streamNumberBytes, 0);
prf.update(streamNumberBytes, 0, streamNumberBytes.length); prf.update(streamNumberBytes, 0, streamNumberBytes.length);
byte[] mac = new byte[macLength]; byte[] mac = new byte[macLength];
prf.doFinal(mac, 0); prf.doFinal(mac, 0);

View File

@@ -73,6 +73,7 @@ import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE; import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED; import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED; import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
@@ -87,7 +88,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
class DatabaseComponentImpl<T> implements DatabaseComponent { class DatabaseComponentImpl<T> implements DatabaseComponent {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(DatabaseComponentImpl.class.getName()); getLogger(DatabaseComponentImpl.class.getName());
private final Database<T> db; private final Database<T> db;
private final Class<T> txnClass; private final Class<T> txnClass;

View File

@@ -7,7 +7,6 @@ import org.briarproject.bramble.api.db.MigrationListener;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.MessageFactory; import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.util.StringUtils;
import java.io.File; import java.io.File;
import java.sql.Connection; import java.sql.Connection;
@@ -23,6 +22,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger; import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.db.JdbcUtils.tryToClose; import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
import static org.briarproject.bramble.util.StringUtils.toHexString;
/** /**
* Contains all the H2-specific code for the database. * Contains all the H2-specific code for the database.
@@ -107,7 +107,7 @@ class H2Database extends JdbcDatabase {
Properties props = new Properties(); Properties props = new Properties();
props.setProperty("user", "user"); props.setProperty("user", "user");
// Separate the file password from the user password with a space // Separate the file password from the user password with a space
String hex = StringUtils.toHexString(key.getBytes()); String hex = toHexString(key.getBytes());
props.put("password", hex + " password"); props.put("password", hex + " password");
return DriverManager.getConnection(getUrl(), props); return DriverManager.getConnection(getUrl(), props);
} }

View File

@@ -7,7 +7,6 @@ import org.briarproject.bramble.api.db.MigrationListener;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.MessageFactory; import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.util.StringUtils;
import java.io.File; import java.io.File;
import java.sql.Connection; import java.sql.Connection;
@@ -22,6 +21,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger; import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.db.JdbcUtils.tryToClose; import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
import static org.briarproject.bramble.util.StringUtils.toHexString;
/** /**
* Contains all the HSQLDB-specific code for the database. * Contains all the HSQLDB-specific code for the database.
@@ -114,7 +114,7 @@ class HyperSqlDatabase extends JdbcDatabase {
protected Connection createConnection() throws SQLException { protected Connection createConnection() throws SQLException {
SecretKey key = this.key; SecretKey key = this.key;
if (key == null) throw new IllegalStateException(); if (key == null) throw new IllegalStateException();
String hex = StringUtils.toHexString(key.getBytes()); String hex = toHexString(key.getBytes());
return DriverManager.getConnection(url + ";crypt_key=" + hex); return DriverManager.getConnection(url + ";crypt_key=" + hex);
} }

View File

@@ -59,6 +59,7 @@ import static java.sql.Types.INTEGER;
import static java.sql.Types.VARCHAR; import static java.sql.Types.VARCHAR;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.db.Metadata.REMOVE; import static org.briarproject.bramble.api.db.Metadata.REMOVE;
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE; import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED; import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
@@ -309,8 +310,7 @@ abstract class JdbcDatabase implements Database<Connection> {
"CREATE INDEX IF NOT EXISTS statusesByContactIdTimestamp" "CREATE INDEX IF NOT EXISTS statusesByContactIdTimestamp"
+ " ON statuses (contactId, timestamp)"; + " ON statuses (contactId, timestamp)";
private static final Logger LOG = private static final Logger LOG = getLogger(JdbcDatabase.class.getName());
Logger.getLogger(JdbcDatabase.class.getName());
// Different database libraries use different names for certain types // Different database libraries use different names for certain types
private final MessageFactory messageFactory; private final MessageFactory messageFactory;

View File

@@ -8,12 +8,12 @@ import java.sql.Statement;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.db.JdbcUtils.tryToClose; import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
class Migration38_39 implements Migration<Connection> { class Migration38_39 implements Migration<Connection> {
private static final Logger LOG = private static final Logger LOG = getLogger(Migration38_39.class.getName());
Logger.getLogger(Migration38_39.class.getName());
@Override @Override
public int getStartVersion() { public int getStartVersion() {

View File

@@ -8,12 +8,12 @@ import java.sql.Statement;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.db.JdbcUtils.tryToClose; import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
class Migration39_40 implements Migration<Connection> { class Migration39_40 implements Migration<Connection> {
private static final Logger LOG = private static final Logger LOG = getLogger(Migration39_40.class.getName());
Logger.getLogger(Migration39_40.class.getName());
@Override @Override
public int getStartVersion() { public int getStartVersion() {

View File

@@ -7,8 +7,6 @@ import org.briarproject.bramble.api.identity.AuthorId;
import org.briarproject.bramble.api.identity.LocalAuthor; import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import javax.inject.Inject; import javax.inject.Inject;
@@ -16,6 +14,8 @@ import javax.inject.Inject;
import static org.briarproject.bramble.api.identity.Author.FORMAT_VERSION; import static org.briarproject.bramble.api.identity.Author.FORMAT_VERSION;
import static org.briarproject.bramble.api.identity.AuthorId.LABEL; import static org.briarproject.bramble.api.identity.AuthorId.LABEL;
import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint32;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
@@ -58,8 +58,8 @@ class AuthorFactoryImpl implements AuthorFactory {
private AuthorId getId(int formatVersion, String name, byte[] publicKey) { private AuthorId getId(int formatVersion, String name, byte[] publicKey) {
byte[] formatVersionBytes = new byte[INT_32_BYTES]; byte[] formatVersionBytes = new byte[INT_32_BYTES];
ByteUtils.writeUint32(formatVersion, formatVersionBytes, 0); writeUint32(formatVersion, formatVersionBytes, 0);
return new AuthorId(crypto.hash(LABEL, formatVersionBytes, return new AuthorId(crypto.hash(LABEL, formatVersionBytes,
StringUtils.toUtf8(name), publicKey)); toUtf8(name), publicKey));
} }
} }

View File

@@ -16,6 +16,7 @@ import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logDuration; import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
@@ -24,7 +25,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
class IdentityManagerImpl implements IdentityManager { class IdentityManagerImpl implements IdentityManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(IdentityManagerImpl.class.getName()); getLogger(IdentityManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final CryptoComponent crypto; private final CryptoComponent crypto;

View File

@@ -20,13 +20,14 @@ import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault @NotNullByDefault
@ThreadSafe @ThreadSafe
class ConnectionChooserImpl implements ConnectionChooser { class ConnectionChooserImpl implements ConnectionChooser {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ConnectionChooserImpl.class.getName()); getLogger(ConnectionChooserImpl.class.getName());
private final Clock clock; private final Clock clock;
private final Executor ioExecutor; private final Executor ioExecutor;

View File

@@ -30,6 +30,7 @@ import javax.annotation.Nullable;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.CONNECTION_TIMEOUT; import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.CONNECTION_TIMEOUT;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@@ -41,7 +42,7 @@ class KeyAgreementConnector {
} }
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(KeyAgreementConnector.class.getName()); getLogger(KeyAgreementConnector.class.getName());
private final Callbacks callbacks; private final Callbacks callbacks;
private final KeyAgreementCrypto keyAgreementCrypto; private final KeyAgreementCrypto keyAgreementCrypto;

View File

@@ -28,6 +28,7 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@@ -36,7 +37,7 @@ class KeyAgreementTaskImpl extends Thread implements KeyAgreementTask,
KeyAgreementProtocol.Callbacks, KeyAgreementConnector.Callbacks { KeyAgreementProtocol.Callbacks, KeyAgreementConnector.Callbacks {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(KeyAgreementTaskImpl.class.getName()); getLogger(KeyAgreementTaskImpl.class.getName());
private final CryptoComponent crypto; private final CryptoComponent crypto;
private final KeyAgreementCrypto keyAgreementCrypto; private final KeyAgreementCrypto keyAgreementCrypto;

View File

@@ -16,6 +16,7 @@ import java.io.OutputStream;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.keyagreement.RecordTypes.ABORT; import static org.briarproject.bramble.api.keyagreement.RecordTypes.ABORT;
import static org.briarproject.bramble.api.keyagreement.RecordTypes.CONFIRM; import static org.briarproject.bramble.api.keyagreement.RecordTypes.CONFIRM;
@@ -29,7 +30,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class KeyAgreementTransport { class KeyAgreementTransport {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(KeyAgreementTransport.class.getName()); getLogger(KeyAgreementTransport.class.getName());
private final KeyAgreementConnection kac; private final KeyAgreementConnection kac;
private final RecordReader reader; private final RecordReader reader;

View File

@@ -28,6 +28,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINE;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.COMPACTING_DATABASE; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.COMPACTING_DATABASE;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.MIGRATING_DATABASE; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.MIGRATING_DATABASE;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.RUNNING; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.RUNNING;
@@ -49,7 +50,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
class LifecycleManagerImpl implements LifecycleManager, MigrationListener { class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(LifecycleManagerImpl.class.getName()); getLogger(LifecycleManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final EventBus eventBus; private final EventBus eventBus;

View File

@@ -26,13 +26,14 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
class ConnectionManagerImpl implements ConnectionManager { class ConnectionManagerImpl implements ConnectionManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ConnectionManagerImpl.class.getName()); getLogger(ConnectionManagerImpl.class.getName());
private final Executor ioExecutor; private final Executor ioExecutor;
private final KeyManager keyManager; private final KeyManager keyManager;

View File

@@ -25,13 +25,14 @@ import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@ThreadSafe @ThreadSafe
@NotNullByDefault @NotNullByDefault
class ConnectionRegistryImpl implements ConnectionRegistry { class ConnectionRegistryImpl implements ConnectionRegistry {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ConnectionRegistryImpl.class.getName()); getLogger(ConnectionRegistryImpl.class.getName());
private final EventBus eventBus; private final EventBus eventBus;
private final Lock lock = new ReentrantLock(); private final Lock lock = new ReentrantLock();

View File

@@ -52,6 +52,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINE;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logDuration; import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.LogUtils.now; import static org.briarproject.bramble.util.LogUtils.now;
@@ -61,7 +62,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
class PluginManagerImpl implements PluginManager, Service { class PluginManagerImpl implements PluginManager, Service {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(PluginManagerImpl.class.getName()); getLogger(PluginManagerImpl.class.getName());
private final Executor ioExecutor; private final Executor ioExecutor;
private final ScheduledExecutorService scheduler; private final ScheduledExecutorService scheduler;

View File

@@ -41,13 +41,14 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@ThreadSafe @ThreadSafe
@NotNullByDefault @NotNullByDefault
class Poller implements EventListener { class Poller implements EventListener {
private static final Logger LOG = Logger.getLogger(Poller.class.getName()); private static final Logger LOG = getLogger(Poller.class.getName());
private final Executor ioExecutor; private final Executor ioExecutor;
private final ScheduledExecutorService scheduler; private final ScheduledExecutorService scheduler;

View File

@@ -13,6 +13,7 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@NotNullByDefault @NotNullByDefault
@@ -20,7 +21,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter { class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(BluetoothConnectionLimiterImpl.class.getName()); getLogger(BluetoothConnectionLimiterImpl.class.getName());
private final Object lock = new Object(); private final Object lock = new Object();
// The following are locking: lock // The following are locking: lock

View File

@@ -37,6 +37,7 @@ import javax.annotation.Nullable;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_BLUETOOTH; import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_BLUETOOTH;
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID; import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PREF_BT_ENABLE; import static org.briarproject.bramble.api.plugin.BluetoothConstants.PREF_BT_ENABLE;
@@ -54,7 +55,7 @@ import static org.briarproject.bramble.util.StringUtils.macToString;
abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener { abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(BluetoothPlugin.class.getName()); getLogger(BluetoothPlugin.class.getName());
final BluetoothConnectionLimiter connectionLimiter; final BluetoothConnectionLimiter connectionLimiter;

View File

@@ -14,6 +14,7 @@ import java.io.IOException;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.plugin.FileConstants.PROP_PATH; import static org.briarproject.bramble.api.plugin.FileConstants.PROP_PATH;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty; import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
@@ -21,8 +22,7 @@ import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
@NotNullByDefault @NotNullByDefault
abstract class FilePlugin implements SimplexPlugin { abstract class FilePlugin implements SimplexPlugin {
private static final Logger LOG = private static final Logger LOG = getLogger(FilePlugin.class.getName());
Logger.getLogger(FilePlugin.class.getName());
protected final SimplexPluginCallback callback; protected final SimplexPluginCallback callback;
protected final int maxLatency; protected final int maxLatency;

View File

@@ -8,13 +8,14 @@ import java.io.InputStream;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.tryToClose; import static org.briarproject.bramble.util.IoUtils.tryToClose;
@NotNullByDefault @NotNullByDefault
class FileTransportReader implements TransportConnectionReader { class FileTransportReader implements TransportConnectionReader {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(FileTransportReader.class.getName()); getLogger(FileTransportReader.class.getName());
private final File file; private final File file;
private final InputStream in; private final InputStream in;

View File

@@ -8,13 +8,14 @@ import java.io.OutputStream;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.tryToClose; import static org.briarproject.bramble.util.IoUtils.tryToClose;
@NotNullByDefault @NotNullByDefault
class FileTransportWriter implements TransportConnectionWriter { class FileTransportWriter implements TransportConnectionWriter {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(FileTransportWriter.class.getName()); getLogger(FileTransportWriter.class.getName());
private final File file; private final File file;
private final OutputStream out; private final OutputStream out;

View File

@@ -12,7 +12,6 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
import org.briarproject.bramble.api.properties.TransportProperties; import org.briarproject.bramble.api.properties.TransportProperties;
import org.briarproject.bramble.api.settings.Settings; import org.briarproject.bramble.api.settings.Settings;
import org.briarproject.bramble.util.IoUtils; import org.briarproject.bramble.util.IoUtils;
import org.briarproject.bramble.util.StringUtils;
import java.io.IOException; import java.io.IOException;
import java.net.Inet4Address; import java.net.Inet4Address;
@@ -23,26 +22,30 @@ import java.net.Socket;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.logging.Logger; import java.util.logging.Logger;
import static java.util.Collections.addAll;
import static java.util.Collections.emptyList;
import static java.util.Collections.sort;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN; import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN;
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID; import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_LAN_IP_PORTS; import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_LAN_IP_PORTS;
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_IP_PORTS; import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_IP_PORTS;
import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED;
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress; import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
import static org.briarproject.bramble.util.StringUtils.join;
@NotNullByDefault @NotNullByDefault
class LanTcpPlugin extends TcpPlugin { class LanTcpPlugin extends TcpPlugin {
private static final Logger LOG = private static final Logger LOG = getLogger(LanTcpPlugin.class.getName());
Logger.getLogger(LanTcpPlugin.class.getName());
private static final LanAddressComparator ADDRESS_COMPARATOR = private static final LanAddressComparator ADDRESS_COMPARATOR =
new LanAddressComparator(); new LanAddressComparator();
@@ -77,12 +80,12 @@ class LanTcpPlugin extends TcpPlugin {
locals.add(new InetSocketAddress(local, 0)); locals.add(new InetSocketAddress(local, 0));
} }
} }
Collections.sort(locals, ADDRESS_COMPARATOR); sort(locals, ADDRESS_COMPARATOR);
return locals; return locals;
} }
private List<InetSocketAddress> parseSocketAddresses(String ipPorts) { private List<InetSocketAddress> parseSocketAddresses(String ipPorts) {
if (StringUtils.isNullOrEmpty(ipPorts)) return Collections.emptyList(); if (isNullOrEmpty(ipPorts)) return emptyList();
String[] split = ipPorts.split(SEPARATOR); String[] split = ipPorts.split(SEPARATOR);
List<InetSocketAddress> addresses = new ArrayList<>(); List<InetSocketAddress> addresses = new ArrayList<>();
for (String ipPort : split) { for (String ipPort : split) {
@@ -98,24 +101,23 @@ class LanTcpPlugin extends TcpPlugin {
// Get the list of recently used addresses // Get the list of recently used addresses
String setting = callback.getSettings().get(PREF_LAN_IP_PORTS); String setting = callback.getSettings().get(PREF_LAN_IP_PORTS);
List<String> recent = new ArrayList<>(); List<String> recent = new ArrayList<>();
if (!StringUtils.isNullOrEmpty(setting)) if (!isNullOrEmpty(setting)) addAll(recent, setting.split(SEPARATOR));
Collections.addAll(recent, setting.split(SEPARATOR));
// Is the address already in the list? // Is the address already in the list?
if (recent.remove(ipPort)) { if (recent.remove(ipPort)) {
// Move the address to the start of the list // Move the address to the start of the list
recent.add(0, ipPort); recent.add(0, ipPort);
setting = StringUtils.join(recent, SEPARATOR); setting = join(recent, SEPARATOR);
} else { } else {
// Add the address to the start of the list // Add the address to the start of the list
recent.add(0, ipPort); recent.add(0, ipPort);
// Drop the least recently used address if the list is full // Drop the least recently used address if the list is full
if (recent.size() > MAX_ADDRESSES) if (recent.size() > MAX_ADDRESSES)
recent = recent.subList(0, MAX_ADDRESSES); recent = recent.subList(0, MAX_ADDRESSES);
setting = StringUtils.join(recent, SEPARATOR); setting = join(recent, SEPARATOR);
// Update the list of addresses shared with contacts // Update the list of addresses shared with contacts
List<String> shared = new ArrayList<>(recent); List<String> shared = new ArrayList<>(recent);
Collections.sort(shared); sort(shared);
String property = StringUtils.join(shared, SEPARATOR); String property = join(shared, SEPARATOR);
TransportProperties properties = new TransportProperties(); TransportProperties properties = new TransportProperties();
properties.put(PROP_IP_PORTS, property); properties.put(PROP_IP_PORTS, property);
callback.mergeLocalProperties(properties); callback.mergeLocalProperties(properties);

View File

@@ -17,6 +17,7 @@ import javax.xml.parsers.ParserConfigurationException;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.PrivacyUtils.scrubInetAddress; import static org.briarproject.bramble.util.PrivacyUtils.scrubInetAddress;
@@ -25,8 +26,7 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubInetAddress;
@ParametersNotNullByDefault @ParametersNotNullByDefault
class PortMapperImpl implements PortMapper { class PortMapperImpl implements PortMapper {
private static final Logger LOG = private static final Logger LOG = getLogger(PortMapperImpl.class.getName());
Logger.getLogger(PortMapperImpl.class.getName());
private final ShutdownManager shutdownManager; private final ShutdownManager shutdownManager;
private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicBoolean started = new AtomicBoolean(false);

View File

@@ -12,7 +12,6 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection; import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
import org.briarproject.bramble.api.properties.TransportProperties; import org.briarproject.bramble.api.properties.TransportProperties;
import org.briarproject.bramble.util.IoUtils; import org.briarproject.bramble.util.IoUtils;
import org.briarproject.bramble.util.StringUtils;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
@@ -41,17 +40,19 @@ import static java.util.Collections.emptyList;
import static java.util.Collections.list; import static java.util.Collections.list;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress; import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@ParametersNotNullByDefault @ParametersNotNullByDefault
abstract class TcpPlugin implements DuplexPlugin { abstract class TcpPlugin implements DuplexPlugin {
private static final Logger LOG = getLogger(TcpPlugin.class.getName());
private static final Pattern DOTTED_QUAD = private static final Pattern DOTTED_QUAD =
Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
private static final Logger LOG =
Logger.getLogger(TcpPlugin.class.getName());
protected final Executor ioExecutor, bindExecutor; protected final Executor ioExecutor, bindExecutor;
protected final Backoff backoff; protected final Backoff backoff;
@@ -263,7 +264,7 @@ abstract class TcpPlugin implements DuplexPlugin {
@Nullable @Nullable
InetSocketAddress parseSocketAddress(String ipPort) { InetSocketAddress parseSocketAddress(String ipPort) {
if (StringUtils.isNullOrEmpty(ipPort)) return null; if (isNullOrEmpty(ipPort)) return null;
String[] split = ipPort.split(":"); String[] split = ipPort.split(":");
if (split.length != 2) return null; if (split.length != 2) return null;
String addr = split[0], port = split[1]; String addr = split[0], port = split[1];

View File

@@ -60,6 +60,7 @@ import javax.net.SocketFactory;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static net.freehaven.tor.control.TorControlCommands.HS_ADDRESS; import static net.freehaven.tor.control.TorControlCommands.HS_ADDRESS;
import static net.freehaven.tor.control.TorControlCommands.HS_PRIVKEY; import static net.freehaven.tor.control.TorControlCommands.HS_PRIVKEY;
import static org.briarproject.bramble.api.plugin.TorConstants.CONTROL_PORT; import static org.briarproject.bramble.api.plugin.TorConstants.CONTROL_PORT;
@@ -73,6 +74,7 @@ import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_ONLY_WHE
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_PORT; import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_PORT;
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V2; import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V2;
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V3; import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V3;
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.PrivacyUtils.scrubOnion; import static org.briarproject.bramble.util.PrivacyUtils.scrubOnion;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty; import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
@@ -81,8 +83,7 @@ import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
@ParametersNotNullByDefault @ParametersNotNullByDefault
abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener { abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
private static final Logger LOG = private static final Logger LOG = getLogger(TorPlugin.class.getName());
Logger.getLogger(TorPlugin.class.getName());
private static final String[] EVENTS = { private static final String[] EVENTS = {
"CIRC", "ORCONN", "HS_DESC", "NOTICE", "WARN", "ERR" "CIRC", "ORCONN", "HS_DESC", "NOTICE", "WARN", "ERR"
@@ -284,23 +285,23 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
// Unzip the Tor binary to the filesystem // Unzip the Tor binary to the filesystem
in = getTorInputStream(); in = getTorInputStream();
out = new FileOutputStream(torFile); out = new FileOutputStream(torFile);
IoUtils.copyAndClose(in, out); copyAndClose(in, out);
// Make the Tor binary executable // Make the Tor binary executable
if (!torFile.setExecutable(true, true)) throw new IOException(); if (!torFile.setExecutable(true, true)) throw new IOException();
// Unzip the GeoIP database to the filesystem // Unzip the GeoIP database to the filesystem
in = getGeoIpInputStream(); in = getGeoIpInputStream();
out = new FileOutputStream(geoIpFile); out = new FileOutputStream(geoIpFile);
IoUtils.copyAndClose(in, out); copyAndClose(in, out);
// Unzip the Obfs4 proxy to the filesystem // Unzip the Obfs4 proxy to the filesystem
in = getObfs4InputStream(); in = getObfs4InputStream();
out = new FileOutputStream(obfs4File); out = new FileOutputStream(obfs4File);
IoUtils.copyAndClose(in, out); copyAndClose(in, out);
// Make the Obfs4 proxy executable // Make the Obfs4 proxy executable
if (!obfs4File.setExecutable(true, true)) throw new IOException(); if (!obfs4File.setExecutable(true, true)) throw new IOException();
// Copy the config file to the filesystem // Copy the config file to the filesystem
in = getConfigInputStream(); in = getConfigInputStream();
out = new FileOutputStream(configFile); out = new FileOutputStream(configFile);
IoUtils.copyAndClose(in, out); copyAndClose(in, out);
doneFile.createNewFile(); doneFile.createNewFile();
} catch (IOException e) { } catch (IOException e) {
IoUtils.tryToClose(in, LOG, WARNING); IoUtils.tryToClose(in, LOG, WARNING);

View File

@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.record.Record; import org.briarproject.bramble.api.record.Record;
import org.briarproject.bramble.api.record.RecordReader; import org.briarproject.bramble.api.record.RecordReader;
import org.briarproject.bramble.util.ByteUtils;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
@@ -14,6 +13,7 @@ import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES; import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES; import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
@@ -31,7 +31,7 @@ class RecordReaderImpl implements RecordReader {
in.readFully(header); in.readFully(header);
byte protocolVersion = header[0]; byte protocolVersion = header[0];
byte recordType = header[1]; byte recordType = header[1];
int payloadLength = ByteUtils.readUint16(header, 2); int payloadLength = readUint16(header, 2);
if (payloadLength < 0 || payloadLength > MAX_RECORD_PAYLOAD_BYTES) if (payloadLength < 0 || payloadLength > MAX_RECORD_PAYLOAD_BYTES)
throw new FormatException(); throw new FormatException();
byte[] payload = new byte[payloadLength]; byte[] payload = new byte[payloadLength];

View File

@@ -3,7 +3,6 @@ package org.briarproject.bramble.record;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.record.Record; import org.briarproject.bramble.api.record.Record;
import org.briarproject.bramble.api.record.RecordWriter; import org.briarproject.bramble.api.record.RecordWriter;
import org.briarproject.bramble.util.ByteUtils;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -11,6 +10,7 @@ import java.io.OutputStream;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES; import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
@@ -28,7 +28,7 @@ class RecordWriterImpl implements RecordWriter {
byte[] payload = r.getPayload(); byte[] payload = r.getPayload();
header[0] = r.getProtocolVersion(); header[0] = r.getProtocolVersion();
header[1] = r.getRecordType(); header[1] = r.getRecordType();
ByteUtils.writeUint16(payload.length, header, 2); writeUint16(payload.length, header, 2);
out.write(header); out.write(header);
out.write(payload); out.write(payload);
} }

View File

@@ -1,10 +1,12 @@
package org.briarproject.bramble.reliability; package org.briarproject.bramble.reliability;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
class Ack extends Frame { class Ack extends Frame {
@@ -23,10 +25,10 @@ class Ack extends Frame {
} }
int getWindowSize() { int getWindowSize() {
return ByteUtils.readUint16(buf, 5); return readUint16(buf, 5);
} }
void setWindowSize(int windowSize) { void setWindowSize(int windowSize) {
ByteUtils.writeUint16(windowSize, buf, 5); writeUint16(windowSize, buf, 5);
} }
} }

View File

@@ -1,10 +1,12 @@
package org.briarproject.bramble.reliability; package org.briarproject.bramble.reliability;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.util.ByteUtils.readUint32;
import static org.briarproject.bramble.util.ByteUtils.writeUint32;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
abstract class Frame { abstract class Frame {
@@ -26,11 +28,11 @@ abstract class Frame {
} }
long getChecksum() { long getChecksum() {
return ByteUtils.readUint32(buf, buf.length - 4); return readUint32(buf, buf.length - 4);
} }
void setChecksum(long checksum) { void setChecksum(long checksum) {
ByteUtils.writeUint32(checksum, buf, buf.length - 4); writeUint32(checksum, buf, buf.length - 4);
} }
long calculateChecksum() { long calculateChecksum() {
@@ -38,11 +40,11 @@ abstract class Frame {
} }
long getSequenceNumber() { long getSequenceNumber() {
return ByteUtils.readUint32(buf, 1); return readUint32(buf, 1);
} }
void setSequenceNumber(long sequenceNumber) { void setSequenceNumber(long sequenceNumber) {
ByteUtils.writeUint32(sequenceNumber, buf, 1); writeUint32(sequenceNumber, buf, 1);
} }
@Override @Override

View File

@@ -16,6 +16,7 @@ import java.util.logging.Logger;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@@ -25,7 +26,7 @@ class ReliabilityLayerImpl implements ReliabilityLayer, WriteHandler {
private static final int TICK_INTERVAL = 500; // Milliseconds private static final int TICK_INTERVAL = 500; // Milliseconds
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ReliabilityLayerImpl.class.getName()); getLogger(ReliabilityLayerImpl.class.getName());
private final Executor executor; private final Executor executor;
private final Clock clock; private final Clock clock;

View File

@@ -9,8 +9,6 @@ import org.briarproject.bramble.api.plugin.TorConstants;
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent; import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
import org.briarproject.bramble.api.reporting.DevConfig; import org.briarproject.bramble.api.reporting.DevConfig;
import org.briarproject.bramble.api.reporting.DevReporter; import org.briarproject.bramble.api.reporting.DevReporter;
import org.briarproject.bramble.util.IoUtils;
import org.briarproject.bramble.util.StringUtils;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -30,14 +28,18 @@ import javax.inject.Inject;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
import static org.briarproject.bramble.util.IoUtils.getOutputStream;
import static org.briarproject.bramble.util.IoUtils.tryToClose; import static org.briarproject.bramble.util.IoUtils.tryToClose;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
class DevReporterImpl implements DevReporter, EventListener { class DevReporterImpl implements DevReporter, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(DevReporterImpl.class.getName()); getLogger(DevReporterImpl.class.getName());
private static final int SOCKET_TIMEOUT = 30 * 1000; // 30 seconds private static final int SOCKET_TIMEOUT = 30 * 1000; // 30 seconds
private static final int LINE_LENGTH = 70; private static final int LINE_LENGTH = 70;
@@ -73,7 +75,7 @@ class DevReporterImpl implements DevReporter, EventListener {
public void encryptReportToFile(File reportDir, String filename, public void encryptReportToFile(File reportDir, String filename,
String report) throws FileNotFoundException { String report) throws FileNotFoundException {
LOG.info("Encrypting report to file"); LOG.info("Encrypting report to file");
byte[] plaintext = StringUtils.toUtf8(report); byte[] plaintext = toUtf8(report);
byte[] ciphertext = crypto.encryptToKey(devConfig.getDevPublicKey(), byte[] ciphertext = crypto.encryptToKey(devConfig.getDevPublicKey(),
plaintext); plaintext);
String armoured = crypto.asciiArmour(ciphertext, LINE_LENGTH); String armoured = crypto.asciiArmour(ciphertext, LINE_LENGTH);
@@ -112,9 +114,9 @@ class DevReporterImpl implements DevReporter, EventListener {
InputStream in = null; InputStream in = null;
try { try {
Socket s = connectToDevelopers(); Socket s = connectToDevelopers();
out = IoUtils.getOutputStream(s); out = getOutputStream(s);
in = new FileInputStream(f); in = new FileInputStream(f);
IoUtils.copyAndClose(in, out); copyAndClose(in, out);
f.delete(); f.delete();
} catch (IOException e) { } catch (IOException e) {
LOG.log(WARNING, "Failed to send reports", e); LOG.log(WARNING, "Failed to send reports", e);

View File

@@ -1,6 +1,5 @@
package org.briarproject.bramble.socks; package org.briarproject.bramble.socks;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.IoUtils; import org.briarproject.bramble.util.IoUtils;
import java.io.IOException; import java.io.IOException;
@@ -12,6 +11,8 @@ import java.net.Socket;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.Arrays; import java.util.Arrays;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
class SocksSocket extends Socket { class SocksSocket extends Socket {
private static final String[] ERRORS = { private static final String[] ERRORS = {
@@ -108,7 +109,7 @@ class SocksSocket extends Socket {
connectRequest[4] = (byte) host.length(); // Length of domain name connectRequest[4] = (byte) host.length(); // Length of domain name
for (int i = 0; i < host.length(); i++) for (int i = 0; i < host.length(); i++)
connectRequest[5 + i] = (byte) host.charAt(i); connectRequest[5 + i] = (byte) host.charAt(i);
ByteUtils.writeUint16(port, connectRequest, connectRequest.length - 2); writeUint16(port, connectRequest, connectRequest.length - 2);
out.write(connectRequest); out.write(connectRequest);
out.flush(); out.flush();
} }

View File

@@ -39,6 +39,7 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING;
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES; import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS; import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
@@ -55,7 +56,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class DuplexOutgoingSession implements SyncSession, EventListener { class DuplexOutgoingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(DuplexOutgoingSession.class.getName()); getLogger(DuplexOutgoingSession.class.getName());
private static final ThrowingRunnable<IOException> CLOSE = () -> { private static final ThrowingRunnable<IOException> CLOSE = () -> {
}; };

View File

@@ -6,8 +6,6 @@ import org.briarproject.bramble.api.sync.ClientId;
import org.briarproject.bramble.api.sync.Group; import org.briarproject.bramble.api.sync.Group;
import org.briarproject.bramble.api.sync.GroupFactory; import org.briarproject.bramble.api.sync.GroupFactory;
import org.briarproject.bramble.api.sync.GroupId; import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import javax.inject.Inject; import javax.inject.Inject;
@@ -15,6 +13,8 @@ import javax.inject.Inject;
import static org.briarproject.bramble.api.sync.Group.FORMAT_VERSION; import static org.briarproject.bramble.api.sync.Group.FORMAT_VERSION;
import static org.briarproject.bramble.api.sync.GroupId.LABEL; import static org.briarproject.bramble.api.sync.GroupId.LABEL;
import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint32;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
@@ -33,10 +33,9 @@ class GroupFactoryImpl implements GroupFactory {
@Override @Override
public Group createGroup(ClientId c, int majorVersion, byte[] descriptor) { public Group createGroup(ClientId c, int majorVersion, byte[] descriptor) {
byte[] majorVersionBytes = new byte[INT_32_BYTES]; byte[] majorVersionBytes = new byte[INT_32_BYTES];
ByteUtils.writeUint32(majorVersion, majorVersionBytes, 0); writeUint32(majorVersion, majorVersionBytes, 0);
byte[] hash = crypto.hash(LABEL, FORMAT_VERSION_BYTES, byte[] hash = crypto.hash(LABEL, FORMAT_VERSION_BYTES,
StringUtils.toUtf8(c.getString()), majorVersionBytes, toUtf8(c.getString()), majorVersionBytes, descriptor);
descriptor);
return new Group(new GroupId(hash), c, majorVersion, descriptor); return new Group(new GroupId(hash), c, majorVersion, descriptor);
} }
} }

View File

@@ -26,6 +26,7 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@@ -37,7 +38,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class IncomingSession implements SyncSession, EventListener { class IncomingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(IncomingSession.class.getName()); getLogger(IncomingSession.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor; private final Executor dbExecutor;

View File

@@ -7,7 +7,6 @@ import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.api.sync.Message; import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageFactory; import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId; import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.util.ByteUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import javax.inject.Inject; import javax.inject.Inject;
@@ -19,6 +18,8 @@ import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_BODY_L
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_LENGTH; import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH; import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint64;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
@@ -47,7 +48,7 @@ class MessageFactoryImpl implements MessageFactory {
// There's only one block, so the root hash is the hash of the block // There's only one block, so the root hash is the hash of the block
byte[] rootHash = crypto.hash(BLOCK_LABEL, FORMAT_VERSION_BYTES, body); byte[] rootHash = crypto.hash(BLOCK_LABEL, FORMAT_VERSION_BYTES, body);
byte[] timeBytes = new byte[INT_64_BYTES]; byte[] timeBytes = new byte[INT_64_BYTES];
ByteUtils.writeUint64(timestamp, timeBytes, 0); writeUint64(timestamp, timeBytes, 0);
byte[] idHash = crypto.hash(ID_LABEL, FORMAT_VERSION_BYTES, byte[] idHash = crypto.hash(ID_LABEL, FORMAT_VERSION_BYTES,
g.getBytes(), timeBytes, rootHash); g.getBytes(), timeBytes, rootHash);
return new MessageId(idHash); return new MessageId(idHash);
@@ -62,7 +63,7 @@ class MessageFactoryImpl implements MessageFactory {
byte[] groupId = new byte[UniqueId.LENGTH]; byte[] groupId = new byte[UniqueId.LENGTH];
System.arraycopy(raw, 0, groupId, 0, UniqueId.LENGTH); System.arraycopy(raw, 0, groupId, 0, UniqueId.LENGTH);
GroupId g = new GroupId(groupId); GroupId g = new GroupId(groupId);
long timestamp = ByteUtils.readUint64(raw, UniqueId.LENGTH); long timestamp = readUint64(raw, UniqueId.LENGTH);
byte[] body = new byte[raw.length - MESSAGE_HEADER_LENGTH]; byte[] body = new byte[raw.length - MESSAGE_HEADER_LENGTH];
System.arraycopy(raw, MESSAGE_HEADER_LENGTH, body, 0, body.length); System.arraycopy(raw, MESSAGE_HEADER_LENGTH, body, 0, body.length);
MessageId id = getMessageId(g, timestamp, body); MessageId id = getMessageId(g, timestamp, body);
@@ -74,7 +75,7 @@ class MessageFactoryImpl implements MessageFactory {
byte[] body = m.getBody(); byte[] body = m.getBody();
byte[] raw = new byte[MESSAGE_HEADER_LENGTH + body.length]; byte[] raw = new byte[MESSAGE_HEADER_LENGTH + body.length];
System.arraycopy(m.getGroupId().getBytes(), 0, raw, 0, UniqueId.LENGTH); System.arraycopy(m.getGroupId().getBytes(), 0, raw, 0, UniqueId.LENGTH);
ByteUtils.writeUint64(m.getTimestamp(), raw, UniqueId.LENGTH); writeUint64(m.getTimestamp(), raw, UniqueId.LENGTH);
System.arraycopy(body, 0, raw, MESSAGE_HEADER_LENGTH, body.length); System.arraycopy(body, 0, raw, MESSAGE_HEADER_LENGTH, body.length);
return raw; return raw;
} }

View File

@@ -29,6 +29,7 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING; import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING;
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES; import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS; import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
@@ -44,7 +45,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class SimplexOutgoingSession implements SyncSession, EventListener { class SimplexOutgoingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(SimplexOutgoingSession.class.getName()); getLogger(SimplexOutgoingSession.class.getName());
private static final ThrowingRunnable<IOException> CLOSE = () -> { private static final ThrowingRunnable<IOException> CLOSE = () -> {
}; };

View File

@@ -12,7 +12,6 @@ import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.Offer; import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.Request; import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.api.sync.SyncRecordReader; import org.briarproject.bramble.api.sync.SyncRecordReader;
import org.briarproject.bramble.util.ByteUtils;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
@@ -28,6 +27,7 @@ import static org.briarproject.bramble.api.sync.RecordTypes.OFFER;
import static org.briarproject.bramble.api.sync.RecordTypes.REQUEST; import static org.briarproject.bramble.api.sync.RecordTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH; import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.sync.SyncConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.util.ByteUtils.readUint64;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
@@ -127,7 +127,7 @@ class SyncRecordReaderImpl implements SyncRecordReader {
if (payload.length <= MESSAGE_HEADER_LENGTH) if (payload.length <= MESSAGE_HEADER_LENGTH)
throw new FormatException(); throw new FormatException();
// Validate timestamp // Validate timestamp
long timestamp = ByteUtils.readUint64(payload, UniqueId.LENGTH); long timestamp = readUint64(payload, UniqueId.LENGTH);
if (timestamp < 0) throw new FormatException(); if (timestamp < 0) throw new FormatException();
nextRecord = null; nextRecord = null;
return messageFactory.createMessage(payload); return messageFactory.createMessage(payload);

View File

@@ -40,6 +40,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED; import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
import static org.briarproject.bramble.api.sync.validation.MessageState.INVALID; import static org.briarproject.bramble.api.sync.validation.MessageState.INVALID;
import static org.briarproject.bramble.api.sync.validation.MessageState.PENDING; import static org.briarproject.bramble.api.sync.validation.MessageState.PENDING;
@@ -51,7 +52,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
EventListener { EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ValidationManagerImpl.class.getName()); getLogger(ValidationManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor, validationExecutor; private final Executor dbExecutor, validationExecutor;

View File

@@ -34,13 +34,13 @@ import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@ThreadSafe @ThreadSafe
@NotNullByDefault @NotNullByDefault
class KeyManagerImpl implements KeyManager, Service, EventListener { class KeyManagerImpl implements KeyManager, Service, EventListener {
private static final Logger LOG = private static final Logger LOG = getLogger(KeyManagerImpl.class.getName());
Logger.getLogger(KeyManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor; private final Executor dbExecutor;

View File

@@ -32,6 +32,7 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE;
import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
@@ -43,7 +44,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class TransportKeyManagerImpl implements TransportKeyManager { class TransportKeyManagerImpl implements TransportKeyManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(TransportKeyManagerImpl.class.getName()); getLogger(TransportKeyManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final TransportCrypto transportCrypto; private final TransportCrypto transportCrypto;

View File

@@ -23,7 +23,6 @@ import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId; import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.DbExpectations; import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.util.StringUtils;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.Mockery; import org.jmock.Mockery;
import org.junit.Test; import org.junit.Test;
@@ -74,7 +73,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
private final long timestamp = message.getTimestamp(); private final long timestamp = message.getTimestamp();
private final Metadata metadata = new Metadata(); private final Metadata metadata = new Metadata();
private final BdfList list = BdfList.of("Sign this!", getRandomBytes(42)); private final BdfList list = BdfList.of("Sign this!", getRandomBytes(42));
private final String label = StringUtils.getRandomString(5); private final String label = getRandomString(5);
private final Author author = getAuthor(); private final Author author = getAuthor();
private final ClientHelper clientHelper = new ClientHelperImpl(db, private final ClientHelper clientHelper = new ClientHelperImpl(db,

View File

@@ -1,12 +1,12 @@
package org.briarproject.bramble.crypto; package org.briarproject.bramble.crypto;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test; import org.junit.Test;
import org.spongycastle.crypto.digests.Blake2bDigest; import org.spongycastle.crypto.digests.Blake2bDigest;
import java.util.Random; import java.util.Random;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
public class Blake2bDigestTest extends BrambleTestCase { public class Blake2bDigestTest extends BrambleTestCase {
@@ -49,9 +49,9 @@ public class Blake2bDigestTest extends BrambleTestCase {
@Test @Test
public void testDigestWithKeyedTestVectors() { public void testDigestWithKeyedTestVectors() {
for (String[] keyedTestVector : KEYED_TEST_VECTORS) { for (String[] keyedTestVector : KEYED_TEST_VECTORS) {
byte[] input = StringUtils.fromHexString(keyedTestVector[0]); byte[] input = fromHexString(keyedTestVector[0]);
byte[] key = StringUtils.fromHexString(keyedTestVector[1]); byte[] key = fromHexString(keyedTestVector[1]);
byte[] expected = StringUtils.fromHexString(keyedTestVector[2]); byte[] expected = fromHexString(keyedTestVector[2]);
Blake2bDigest digest = new Blake2bDigest(key); Blake2bDigest digest = new Blake2bDigest(key);
digest.update(input, 0, input.length); digest.update(input, 0, input.length);
@@ -67,10 +67,10 @@ public class Blake2bDigestTest extends BrambleTestCase {
Random random = new Random(); Random random = new Random();
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
for (String[] keyedTestVector : KEYED_TEST_VECTORS) { for (String[] keyedTestVector : KEYED_TEST_VECTORS) {
byte[] input = StringUtils.fromHexString(keyedTestVector[0]); byte[] input = fromHexString(keyedTestVector[0]);
if (input.length == 0) continue; if (input.length == 0) continue;
byte[] key = StringUtils.fromHexString(keyedTestVector[1]); byte[] key = fromHexString(keyedTestVector[1]);
byte[] expected = StringUtils.fromHexString(keyedTestVector[2]); byte[] expected = fromHexString(keyedTestVector[2]);
Blake2bDigest digest = new Blake2bDigest(key); Blake2bDigest digest = new Blake2bDigest(key);
@@ -168,6 +168,6 @@ public class Blake2bDigestTest extends BrambleTestCase {
byte[] hash = new byte[32]; byte[] hash = new byte[32];
testDigest.doFinal(hash, 0); testDigest.doFinal(hash, 0);
assertArrayEquals(StringUtils.fromHexString(SELF_TEST_RESULT), hash); assertArrayEquals(fromHexString(SELF_TEST_RESULT), hash);
} }
} }

View File

@@ -3,12 +3,12 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.CryptoComponent; import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSecureRandomProvider; import org.briarproject.bramble.test.TestSecureRandomProvider;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -16,9 +16,9 @@ public class HashTest extends BrambleTestCase {
private final CryptoComponent crypto; private final CryptoComponent crypto;
private final String label = StringUtils.getRandomString(42); private final String label = getRandomString(42);
private final byte[] inputBytes = TestUtils.getRandomBytes(123); private final byte[] inputBytes = getRandomBytes(123);
private final byte[] inputBytes1 = TestUtils.getRandomBytes(234); private final byte[] inputBytes1 = getRandomBytes(234);
private final byte[] inputBytes2 = new byte[0]; private final byte[] inputBytes2 = new byte[0];
public HashTest() { public HashTest() {
@@ -41,7 +41,7 @@ public class HashTest extends BrambleTestCase {
@Test @Test
public void testDifferentLabelsProduceDifferentHashes() { public void testDifferentLabelsProduceDifferentHashes() {
String label2 = StringUtils.getRandomString(42); String label2 = getRandomString(42);
byte[] hash1 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2); byte[] hash1 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2);
byte[] hash2 = byte[] hash2 =
crypto.hash(label2, inputBytes, inputBytes1, inputBytes2); crypto.hash(label2, inputBytes, inputBytes1, inputBytes2);

View File

@@ -3,11 +3,11 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.system.SystemClock; import org.briarproject.bramble.system.SystemClock;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSecureRandomProvider; import org.briarproject.bramble.test.TestSecureRandomProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test; import org.junit.Test;
import java.util.Random; import java.util.Random;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@@ -19,7 +19,7 @@ public class PasswordBasedEncryptionTest extends BrambleTestCase {
@Test @Test
public void testEncryptionAndDecryption() { public void testEncryptionAndDecryption() {
byte[] input = TestUtils.getRandomBytes(1234); byte[] input = getRandomBytes(1234);
String password = "password"; String password = "password";
byte[] ciphertext = crypto.encryptWithPassword(input, password); byte[] ciphertext = crypto.encryptWithPassword(input, password);
byte[] output = crypto.decryptWithPassword(ciphertext, password); byte[] output = crypto.decryptWithPassword(ciphertext, password);
@@ -28,7 +28,7 @@ public class PasswordBasedEncryptionTest extends BrambleTestCase {
@Test @Test
public void testInvalidCiphertextReturnsNull() { public void testInvalidCiphertextReturnsNull() {
byte[] input = TestUtils.getRandomBytes(1234); byte[] input = getRandomBytes(1234);
String password = "password"; String password = "password";
byte[] ciphertext = crypto.encryptWithPassword(input, password); byte[] ciphertext = crypto.encryptWithPassword(input, password);
// Modify the ciphertext // Modify the ciphertext

View File

@@ -4,6 +4,7 @@ import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.system.SystemClock; import org.briarproject.bramble.system.SystemClock;
import org.briarproject.bramble.test.ArrayClock;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test; import org.junit.Test;
@@ -11,8 +12,6 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.assertTrue;
import org.briarproject.bramble.test.ArrayClock;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes; import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.util.StringUtils.getRandomString; import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@@ -4,13 +4,13 @@ import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair; import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSecureRandomProvider; import org.briarproject.bramble.test.TestSecureRandomProvider;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test; import org.junit.Test;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Arrays; import java.util.Arrays;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -20,8 +20,8 @@ public abstract class SignatureTest extends BrambleTestCase {
protected final CryptoComponent crypto; protected final CryptoComponent crypto;
private final byte[] publicKey, privateKey; private final byte[] publicKey, privateKey;
private final String label = StringUtils.getRandomString(42); private final String label = getRandomString(42);
private final byte[] inputBytes = TestUtils.getRandomBytes(123); private final byte[] inputBytes = getRandomBytes(123);
protected abstract KeyPair generateKeyPair(); protected abstract KeyPair generateKeyPair();
@@ -62,7 +62,7 @@ public abstract class SignatureTest extends BrambleTestCase {
public void testDifferentInputsProduceDifferentSignatures() public void testDifferentInputsProduceDifferentSignatures()
throws Exception { throws Exception {
// Generate a second input // Generate a second input
byte[] inputBytes2 = TestUtils.getRandomBytes(123); byte[] inputBytes2 = getRandomBytes(123);
// Calculate the signature with different inputs // Calculate the signature with different inputs
// the results should be different // the results should be different
byte[] sig1 = sign(label, inputBytes, privateKey); byte[] sig1 = sign(label, inputBytes, privateKey);
@@ -74,7 +74,7 @@ public abstract class SignatureTest extends BrambleTestCase {
public void testDifferentLabelsProduceDifferentSignatures() public void testDifferentLabelsProduceDifferentSignatures()
throws Exception { throws Exception {
// Generate a second label // Generate a second label
String label2 = StringUtils.getRandomString(42); String label2 = getRandomString(42);
// Calculate the signature with different inputs // Calculate the signature with different inputs
// the results should be different // the results should be different
byte[] sig1 = sign(label, inputBytes, privateKey); byte[] sig1 = sign(label, inputBytes, privateKey);
@@ -101,7 +101,7 @@ public abstract class SignatureTest extends BrambleTestCase {
@Test @Test
public void testDifferentInputFailsVerification() throws Exception { public void testDifferentInputFailsVerification() throws Exception {
// Generate a second input // Generate a second input
byte[] inputBytes2 = TestUtils.getRandomBytes(123); byte[] inputBytes2 = getRandomBytes(123);
// calculate the signature with different input, should fail to verify // calculate the signature with different input, should fail to verify
byte[] sig = sign(label, inputBytes, privateKey); byte[] sig = sign(label, inputBytes, privateKey);
assertFalse(verify(sig, label, inputBytes2, publicKey)); assertFalse(verify(sig, label, inputBytes2, publicKey));
@@ -110,7 +110,7 @@ public abstract class SignatureTest extends BrambleTestCase {
@Test @Test
public void testDifferentLabelFailsVerification() throws Exception { public void testDifferentLabelFailsVerification() throws Exception {
// Generate a second label // Generate a second label
String label2 = StringUtils.getRandomString(42); String label2 = getRandomString(42);
// calculate the signature with different label, should fail to verify // calculate the signature with different label, should fail to verify
byte[] sig = sign(label, inputBytes, privateKey); byte[] sig = sign(label, inputBytes, privateKey);
assertFalse(verify(sig, label2, inputBytes, publicKey)); assertFalse(verify(sig, label2, inputBytes, publicKey));

View File

@@ -2,8 +2,6 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -16,7 +14,11 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENG
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_PAYLOAD_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_NONCE_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_NONCE_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
public class StreamDecrypterImplTest extends BrambleTestCase { public class StreamDecrypterImplTest extends BrambleTestCase {
@@ -30,15 +32,14 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
public StreamDecrypterImplTest() { public StreamDecrypterImplTest() {
cipher = new TestAuthenticatedCipher(); // Null cipher cipher = new TestAuthenticatedCipher(); // Null cipher
streamHeaderKey = TestUtils.getSecretKey(); streamHeaderKey = getSecretKey();
frameKey = TestUtils.getSecretKey(); frameKey = getSecretKey();
streamHeaderNonce = streamHeaderNonce = getRandomBytes(STREAM_HEADER_NONCE_LENGTH);
TestUtils.getRandomBytes(STREAM_HEADER_NONCE_LENGTH);
protocolVersionBytes = new byte[2]; protocolVersionBytes = new byte[2];
ByteUtils.writeUint16(PROTOCOL_VERSION, protocolVersionBytes, 0); writeUint16(PROTOCOL_VERSION, protocolVersionBytes, 0);
streamNumberBytes = new byte[8]; streamNumberBytes = new byte[8];
ByteUtils.writeUint64(streamNumber, streamNumberBytes, 0); writeUint64(streamNumber, streamNumberBytes, 0);
payload = TestUtils.getRandomBytes(payloadLength); payload = getRandomBytes(payloadLength);
} }
@Test @Test
@@ -51,7 +52,7 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1, FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1,
paddingLength1); paddingLength1);
byte[] payload1 = TestUtils.getRandomBytes(payloadLength1); byte[] payload1 = getRandomBytes(payloadLength1);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderNonce); out.write(streamHeaderNonce);
@@ -88,8 +89,7 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
@Test(expected = IOException.class) @Test(expected = IOException.class)
public void testWrongProtocolVersionThrowsException() throws Exception { public void testWrongProtocolVersionThrowsException() throws Exception {
byte[] wrongProtocolVersionBytes = new byte[2]; byte[] wrongProtocolVersionBytes = new byte[2];
ByteUtils.writeUint16(PROTOCOL_VERSION + 1, wrongProtocolVersionBytes, writeUint16(PROTOCOL_VERSION + 1, wrongProtocolVersionBytes, 0);
0);
byte[] frameHeader = new byte[FRAME_HEADER_LENGTH]; byte[] frameHeader = new byte[FRAME_HEADER_LENGTH];
FrameEncoder.encodeHeader(frameHeader, false, payloadLength, FrameEncoder.encodeHeader(frameHeader, false, payloadLength,
@@ -99,7 +99,7 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1, FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1,
paddingLength1); paddingLength1);
byte[] payload1 = TestUtils.getRandomBytes(payloadLength1); byte[] payload1 = getRandomBytes(payloadLength1);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderNonce); out.write(streamHeaderNonce);
@@ -128,7 +128,7 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
@Test(expected = IOException.class) @Test(expected = IOException.class)
public void testWrongStreamNumberThrowsException() throws Exception { public void testWrongStreamNumberThrowsException() throws Exception {
byte[] wrongStreamNumberBytes = new byte[8]; byte[] wrongStreamNumberBytes = new byte[8];
ByteUtils.writeUint64(streamNumber + 1, wrongStreamNumberBytes, 0); writeUint64(streamNumber + 1, wrongStreamNumberBytes, 0);
byte[] frameHeader = new byte[FRAME_HEADER_LENGTH]; byte[] frameHeader = new byte[FRAME_HEADER_LENGTH];
FrameEncoder.encodeHeader(frameHeader, false, payloadLength, FrameEncoder.encodeHeader(frameHeader, false, payloadLength,
@@ -138,7 +138,7 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1, FrameEncoder.encodeHeader(frameHeader1, true, payloadLength1,
paddingLength1); paddingLength1);
byte[] payload1 = TestUtils.getRandomBytes(payloadLength1); byte[] payload1 = getRandomBytes(payloadLength1);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderNonce); out.write(streamHeaderNonce);
@@ -196,9 +196,9 @@ public class StreamDecrypterImplTest extends BrambleTestCase {
byte[] frameHeader = new byte[FRAME_HEADER_LENGTH]; byte[] frameHeader = new byte[FRAME_HEADER_LENGTH];
// The payload length plus padding length is invalid // The payload length plus padding length is invalid
int payloadLength = MAX_PAYLOAD_LENGTH - 1, paddingLength = 2; int payloadLength = MAX_PAYLOAD_LENGTH - 1, paddingLength = 2;
ByteUtils.writeUint16(payloadLength, frameHeader, 0); writeUint16(payloadLength, frameHeader, 0);
ByteUtils.writeUint16(paddingLength, frameHeader, INT_16_BYTES); writeUint16(paddingLength, frameHeader, INT_16_BYTES);
byte[] payload = TestUtils.getRandomBytes(payloadLength); byte[] payload = getRandomBytes(payloadLength);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(streamHeaderNonce); out.write(streamHeaderNonce);

View File

@@ -2,8 +2,6 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -16,6 +14,10 @@ import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_NONCE_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_NONCE_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -30,16 +32,15 @@ public class StreamEncrypterImplTest extends BrambleTestCase {
public StreamEncrypterImplTest() { public StreamEncrypterImplTest() {
cipher = new TestAuthenticatedCipher(); // Null cipher cipher = new TestAuthenticatedCipher(); // Null cipher
streamHeaderKey = TestUtils.getSecretKey(); streamHeaderKey = getSecretKey();
frameKey = TestUtils.getSecretKey(); frameKey = getSecretKey();
tag = TestUtils.getRandomBytes(TAG_LENGTH); tag = getRandomBytes(TAG_LENGTH);
streamHeaderNonce = streamHeaderNonce = getRandomBytes(STREAM_HEADER_NONCE_LENGTH);
TestUtils.getRandomBytes(STREAM_HEADER_NONCE_LENGTH);
protocolVersionBytes = new byte[2]; protocolVersionBytes = new byte[2];
ByteUtils.writeUint16(PROTOCOL_VERSION, protocolVersionBytes, 0); writeUint16(PROTOCOL_VERSION, protocolVersionBytes, 0);
streamNumberBytes = new byte[8]; streamNumberBytes = new byte[8];
ByteUtils.writeUint64(streamNumber, streamNumberBytes, 0); writeUint64(streamNumber, streamNumberBytes, 0);
payload = TestUtils.getRandomBytes(payloadLength); payload = getRandomBytes(payloadLength);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@@ -318,7 +319,7 @@ public class StreamEncrypterImplTest extends BrambleTestCase {
streamNumber, tag, streamHeaderNonce, streamHeaderKey, streamNumber, tag, streamHeaderNonce, streamHeaderKey,
frameKey); frameKey);
int payloadLength1 = 345, paddingLength1 = 456; int payloadLength1 = 345, paddingLength1 = 456;
byte[] payload1 = TestUtils.getRandomBytes(payloadLength1); byte[] payload1 = getRandomBytes(payloadLength1);
s.writeFrame(payload, payloadLength, paddingLength, false); s.writeFrame(payload, payloadLength, paddingLength, false);
s.writeFrame(payload1, payloadLength1, paddingLength1, true); s.writeFrame(payload1, payloadLength1, paddingLength1, true);

View File

@@ -2,12 +2,12 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test; import org.junit.Test;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Random; import java.util.Random;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -15,11 +15,11 @@ public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
// Test vectors from the NaCl paper // Test vectors from the NaCl paper
// http://cr.yp.to/highspeed/naclcrypto-20090310.pdf // http://cr.yp.to/highspeed/naclcrypto-20090310.pdf
private static final byte[] TEST_KEY = StringUtils.fromHexString( private static final byte[] TEST_KEY = fromHexString(
"1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389"); "1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389");
private static final byte[] TEST_IV = StringUtils.fromHexString( private static final byte[] TEST_IV = fromHexString(
"69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"); "69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37");
private static final byte[] TEST_PLAINTEXT = StringUtils.fromHexString( private static final byte[] TEST_PLAINTEXT = fromHexString(
"be075fc53c81f2d5cf141316" + "be075fc53c81f2d5cf141316" +
"ebeb0c7b5228c52a4c62cbd4" + "ebeb0c7b5228c52a4c62cbd4" +
"4b66849b64244ffce5ecbaaf" + "4b66849b64244ffce5ecbaaf" +
@@ -31,7 +31,7 @@ public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
"048977eb48f59ffd4924ca1c" + "048977eb48f59ffd4924ca1c" +
"60902e52f0a089bc76897040" + "60902e52f0a089bc76897040" +
"e082f937763848645e0705"); "e082f937763848645e0705");
private static final byte[] TEST_CIPHERTEXT = StringUtils.fromHexString( private static final byte[] TEST_CIPHERTEXT = fromHexString(
"f3ffc7703f9400e52a7dfb4b" + "f3ffc7703f9400e52a7dfb4b" +
"3d3305d98e993b9f48681273" + "3d3305d98e993b9f48681273" +
"c29650ba32fc76ce48332ea7" + "c29650ba32fc76ce48332ea7" +

View File

@@ -1,7 +1,6 @@
package org.briarproject.bramble.data; package org.briarproject.bramble.data;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -13,6 +12,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE; import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
public class BdfWriterImplTest extends BrambleTestCase { public class BdfWriterImplTest extends BrambleTestCase {
@@ -80,8 +82,8 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteString8() throws IOException { public void testWriteString8() throws IOException {
String longest = StringUtils.getRandomString(Byte.MAX_VALUE); String longest = getRandomString(Byte.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = toHexString(longest.getBytes("UTF-8"));
w.writeString("foo bar baz bam "); w.writeString("foo bar baz bam ");
w.writeString(longest); w.writeString(longest);
// STRING_8 tag, length 16, UTF-8 bytes, STRING_8 tag, length 127, // STRING_8 tag, length 16, UTF-8 bytes, STRING_8 tag, length 127,
@@ -92,10 +94,10 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteString16() throws IOException { public void testWriteString16() throws IOException {
String shortest = StringUtils.getRandomString(Byte.MAX_VALUE + 1); String shortest = getRandomString(Byte.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = toHexString(shortest.getBytes("UTF-8"));
String longest = StringUtils.getRandomString(Short.MAX_VALUE); String longest = getRandomString(Short.MAX_VALUE);
String longHex = StringUtils.toHexString(longest.getBytes("UTF-8")); String longHex = toHexString(longest.getBytes("UTF-8"));
w.writeString(shortest); w.writeString(shortest);
w.writeString(longest); w.writeString(longest);
// STRING_16 tag, length 128, UTF-8 bytes, STRING_16 tag, // STRING_16 tag, length 128, UTF-8 bytes, STRING_16 tag,
@@ -105,8 +107,8 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteString32() throws IOException { public void testWriteString32() throws IOException {
String shortest = StringUtils.getRandomString(Short.MAX_VALUE + 1); String shortest = getRandomString(Short.MAX_VALUE + 1);
String shortHex = StringUtils.toHexString(shortest.getBytes("UTF-8")); String shortHex = toHexString(shortest.getBytes("UTF-8"));
w.writeString(shortest); w.writeString(shortest);
// STRING_32 tag, length 2^15, UTF-8 bytes // STRING_32 tag, length 2^15, UTF-8 bytes
checkContents("44" + "00008000" + shortHex); checkContents("44" + "00008000" + shortHex);
@@ -115,7 +117,7 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteUtf8String() throws IOException { public void testWriteUtf8String() throws IOException {
String unicode = "\uFDD0\uFDD1\uFDD2\uFDD3"; String unicode = "\uFDD0\uFDD1\uFDD2\uFDD3";
String hex = StringUtils.toHexString(unicode.getBytes("UTF-8")); String hex = toHexString(unicode.getBytes("UTF-8"));
w.writeString(unicode); w.writeString(unicode);
// STRING_8 tag, length 12, UTF-8 bytes // STRING_8 tag, length 12, UTF-8 bytes
checkContents("41" + "0C" + hex); checkContents("41" + "0C" + hex);
@@ -124,7 +126,7 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteRaw8() throws IOException { public void testWriteRaw8() throws IOException {
byte[] longest = new byte[Byte.MAX_VALUE]; byte[] longest = new byte[Byte.MAX_VALUE];
String longHex = StringUtils.toHexString(longest); String longHex = toHexString(longest);
w.writeRaw(new byte[] {1, 2, 3}); w.writeRaw(new byte[] {1, 2, 3});
w.writeRaw(longest); w.writeRaw(longest);
// RAW_8 tag, length 3, bytes, RAW_8 tag, length 127, bytes // RAW_8 tag, length 3, bytes, RAW_8 tag, length 127, bytes
@@ -134,9 +136,9 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteRaw16() throws IOException { public void testWriteRaw16() throws IOException {
byte[] shortest = new byte[Byte.MAX_VALUE + 1]; byte[] shortest = new byte[Byte.MAX_VALUE + 1];
String shortHex = StringUtils.toHexString(shortest); String shortHex = toHexString(shortest);
byte[] longest = new byte[Short.MAX_VALUE]; byte[] longest = new byte[Short.MAX_VALUE];
String longHex = StringUtils.toHexString(longest); String longHex = toHexString(longest);
w.writeRaw(shortest); w.writeRaw(shortest);
w.writeRaw(longest); w.writeRaw(longest);
// RAW_16 tag, length 128, bytes, RAW_16 tag, length 2^15 - 1, bytes // RAW_16 tag, length 128, bytes, RAW_16 tag, length 2^15 - 1, bytes
@@ -146,7 +148,7 @@ public class BdfWriterImplTest extends BrambleTestCase {
@Test @Test
public void testWriteRaw32() throws IOException { public void testWriteRaw32() throws IOException {
byte[] shortest = new byte[Short.MAX_VALUE + 1]; byte[] shortest = new byte[Short.MAX_VALUE + 1];
String shortHex = StringUtils.toHexString(shortest); String shortHex = toHexString(shortest);
w.writeRaw(shortest); w.writeRaw(shortest);
// RAW_32 tag, length 2^15, bytes // RAW_32 tag, length 2^15, bytes
checkContents("54" + "00008000" + shortHex); checkContents("54" + "00008000" + shortHex);
@@ -233,8 +235,8 @@ public class BdfWriterImplTest extends BrambleTestCase {
private void checkContents(String hex) throws IOException { private void checkContents(String hex) throws IOException {
out.flush(); out.flush();
out.close(); out.close();
byte[] expected = StringUtils.fromHexString(hex); byte[] expected = fromHexString(hex);
assertArrayEquals(StringUtils.toHexString(out.toByteArray()), assertArrayEquals(toHexString(out.toByteArray()),
expected, out.toByteArray()); expected, out.toByteArray());
} }
} }

View File

@@ -1,8 +1,6 @@
package org.briarproject.bramble.db; package org.briarproject.bramble.db;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -19,6 +17,10 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import static java.sql.Types.BINARY; import static java.sql.Types.BINARY;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@@ -30,7 +32,7 @@ public abstract class BasicDatabaseTest extends BrambleTestCase {
private static final int BATCH_SIZE = 100; private static final int BATCH_SIZE = 100;
private final File testDir = TestUtils.getTestDirectory(); private final File testDir = getTestDirectory();
private final File db = new File(testDir, "db"); private final File db = new File(testDir, "db");
protected abstract String getBinaryType(); protected abstract String getBinaryType();
@@ -56,9 +58,9 @@ public abstract class BasicDatabaseTest extends BrambleTestCase {
// Create the table // Create the table
createTable(connection); createTable(connection);
// Generate an ID and two names // Generate an ID and two names
byte[] id = TestUtils.getRandomId(); byte[] id = getRandomId();
String oldName = StringUtils.getRandomString(50); String oldName = getRandomString(50);
String newName = StringUtils.getRandomString(50); String newName = getRandomString(50);
// Insert the ID and old name into the table // Insert the ID and old name into the table
insertRow(connection, id, oldName); insertRow(connection, id, oldName);
// Check that the old name can be retrieved using the ID // Check that the old name can be retrieved using the ID
@@ -92,9 +94,9 @@ public abstract class BasicDatabaseTest extends BrambleTestCase {
String[] oldNames = new String[BATCH_SIZE]; String[] oldNames = new String[BATCH_SIZE];
String[] newNames = new String[BATCH_SIZE]; String[] newNames = new String[BATCH_SIZE];
for (int i = 0; i < BATCH_SIZE; i++) { for (int i = 0; i < BATCH_SIZE; i++) {
ids[i] = TestUtils.getRandomId(); ids[i] = getRandomId();
oldNames[i] = StringUtils.getRandomString(50); oldNames[i] = getRandomString(50);
newNames[i] = StringUtils.getRandomString(50); newNames[i] = getRandomString(50);
} }
// Insert the IDs and old names into the table as a batch // Insert the IDs and old names into the table as a batch
insertBatch(connection, ids, oldNames); insertBatch(connection, ids, oldNames);
@@ -374,7 +376,7 @@ public abstract class BasicDatabaseTest extends BrambleTestCase {
} }
@After @After
public void tearDown() throws Exception { public void tearDown() {
TestUtils.deleteTestDirectory(testDir); deleteTestDirectory(testDir);
} }
} }

View File

@@ -1,8 +1,6 @@
package org.briarproject.bramble.db; package org.briarproject.bramble.db;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import java.io.File; import java.io.File;
import java.sql.Connection; import java.sql.Connection;
@@ -10,9 +8,12 @@ import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.util.StringUtils.toHexString;
public class BasicH2Test extends BasicDatabaseTest { public class BasicH2Test extends BasicDatabaseTest {
private final SecretKey key = TestUtils.getSecretKey(); private final SecretKey key = getSecretKey();
@Override @Override
protected String getBinaryType() { protected String getBinaryType() {
@@ -32,7 +33,7 @@ public class BasicH2Test extends BasicDatabaseTest {
props.setProperty("user", "user"); props.setProperty("user", "user");
if (encrypt) { if (encrypt) {
url += ";CIPHER=AES"; url += ";CIPHER=AES";
String hex = StringUtils.toHexString(key.getBytes()); String hex = toHexString(key.getBytes());
props.setProperty("password", hex + " password"); props.setProperty("password", hex + " password");
} }
return DriverManager.getConnection(url, props); return DriverManager.getConnection(url, props);

View File

@@ -1,8 +1,6 @@
package org.briarproject.bramble.db; package org.briarproject.bramble.db;
import org.briarproject.bramble.api.crypto.SecretKey; import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import java.io.File; import java.io.File;
import java.sql.Connection; import java.sql.Connection;
@@ -10,9 +8,12 @@ import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.util.StringUtils.toHexString;
public class BasicHyperSqlTest extends BasicDatabaseTest { public class BasicHyperSqlTest extends BasicDatabaseTest {
private final SecretKey key = TestUtils.getSecretKey(); private final SecretKey key = getSecretKey();
@Override @Override
protected String getBinaryType() { protected String getBinaryType() {
@@ -30,7 +31,7 @@ public class BasicHyperSqlTest extends BasicDatabaseTest {
String url = "jdbc:hsqldb:file:" + db.getAbsolutePath() + String url = "jdbc:hsqldb:file:" + db.getAbsolutePath() +
";sql.enforce_size=false;allow_empty_batch=true"; ";sql.enforce_size=false;allow_empty_batch=true";
if (encrypt) { if (encrypt) {
String hex = StringUtils.toHexString(key.getBytes()); String hex = toHexString(key.getBytes());
url += ";encrypt_lobs=true;crypt_type=AES;crypt_key=" + hex; url += ";encrypt_lobs=true;crypt_type=AES;crypt_key=" + hex;
} }
return DriverManager.getConnection(url); return DriverManager.getConnection(url);

View File

@@ -13,7 +13,6 @@ import org.briarproject.bramble.system.SystemClock;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.TestDatabaseConfig; import org.briarproject.bramble.test.TestDatabaseConfig;
import org.briarproject.bramble.test.TestMessageFactory; import org.briarproject.bramble.test.TestMessageFactory;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -29,7 +28,9 @@ import static java.util.Collections.singletonList;
import static org.briarproject.bramble.db.DatabaseConstants.DB_SETTINGS_NAMESPACE; import static org.briarproject.bramble.db.DatabaseConstants.DB_SETTINGS_NAMESPACE;
import static org.briarproject.bramble.db.DatabaseConstants.SCHEMA_VERSION_KEY; import static org.briarproject.bramble.db.DatabaseConstants.SCHEMA_VERSION_KEY;
import static org.briarproject.bramble.db.JdbcDatabase.CODE_SCHEMA_VERSION; import static org.briarproject.bramble.db.JdbcDatabase.CODE_SCHEMA_VERSION;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getSecretKey; import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -37,7 +38,7 @@ import static org.junit.Assert.assertTrue;
@NotNullByDefault @NotNullByDefault
public abstract class DatabaseMigrationTest extends BrambleMockTestCase { public abstract class DatabaseMigrationTest extends BrambleMockTestCase {
private final File testDir = TestUtils.getTestDirectory(); private final File testDir = getTestDirectory();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private final Migration<Connection> migration = private final Migration<Connection> migration =
context.mock(Migration.class, "migration"); context.mock(Migration.class, "migration");
@@ -61,7 +62,7 @@ public abstract class DatabaseMigrationTest extends BrambleMockTestCase {
@After @After
public void tearDown() { public void tearDown() {
TestUtils.deleteTestDirectory(testDir); deleteTestDirectory(testDir);
} }
@Test @Test

View File

@@ -29,9 +29,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.logging.Logger;
import static java.util.logging.Level.OFF; import static java.util.logging.Level.OFF;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS; import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED; import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory; import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
@@ -119,7 +119,7 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
DatabasePerformanceTest() { DatabasePerformanceTest() {
// Disable logging // Disable logging
Logger.getLogger("").setLevel(OFF); getLogger("").setLevel(OFF);
} }
@Before @Before

View File

@@ -8,7 +8,6 @@ import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.system.SystemClock; import org.briarproject.bramble.system.SystemClock;
import org.briarproject.bramble.test.TestDatabaseConfig; import org.briarproject.bramble.test.TestDatabaseConfig;
import org.briarproject.bramble.test.TestMessageFactory; import org.briarproject.bramble.test.TestMessageFactory;
import org.briarproject.bramble.util.IoUtils;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -20,6 +19,7 @@ import javax.annotation.Nullable;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory; import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getSecretKey; import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
public abstract class DatabaseTraceTest extends DatabasePerformanceTest { public abstract class DatabaseTraceTest extends DatabasePerformanceTest {
@@ -58,7 +58,6 @@ public abstract class DatabaseTraceTest extends DatabasePerformanceTest {
if (!src.exists()) return; if (!src.exists()) return;
String filename = getTestName() + "." + name + ".trace.txt"; String filename = getTestName() + "." + name + ".trace.txt";
File dest = new File(testDir.getParentFile(), filename); File dest = new File(testDir.getParentFile(), filename);
IoUtils.copyAndClose(new FileInputStream(src), copyAndClose(new FileInputStream(src), new FileOutputStream(dest));
new FileOutputStream(dest));
} }
} }

View File

@@ -1,7 +1,6 @@
package org.briarproject.bramble.db; package org.briarproject.bramble.db;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -14,6 +13,8 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -32,7 +33,7 @@ public class H2TransactionIsolationTest extends BrambleTestCase {
private static final String SET_COUNTER = private static final String SET_COUNTER =
"UPDATE foo SET counter = ? WHERE key = 1"; "UPDATE foo SET counter = ? WHERE key = 1";
private final File testDir = TestUtils.getTestDirectory(); private final File testDir = getTestDirectory();
private final File db = new File(testDir, "db"); private final File db = new File(testDir, "db");
private final String withMvcc = "jdbc:h2:split:" + db.getAbsolutePath() private final String withMvcc = "jdbc:h2:split:" + db.getAbsolutePath()
+ ";MV_STORE=TRUE;MVCC=TRUE"; + ";MV_STORE=TRUE;MVCC=TRUE";
@@ -47,7 +48,7 @@ public class H2TransactionIsolationTest extends BrambleTestCase {
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
TestUtils.deleteTestDirectory(testDir); deleteTestDirectory(testDir);
} }
@Test @Test

View File

@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.record.Record; import org.briarproject.bramble.api.record.Record;
import org.briarproject.bramble.api.record.RecordReader; import org.briarproject.bramble.api.record.RecordReader;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -12,6 +11,7 @@ import java.io.EOFException;
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES; import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES; import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -36,7 +36,7 @@ public class RecordReaderImplTest extends BrambleTestCase {
// Version 1, type 2, payload length MAX_RECORD_PAYLOAD_BYTES // Version 1, type 2, payload length MAX_RECORD_PAYLOAD_BYTES
record[0] = 1; record[0] = 1;
record[1] = 2; record[1] = 2;
ByteUtils.writeUint16(MAX_RECORD_PAYLOAD_BYTES, record, 2); writeUint16(MAX_RECORD_PAYLOAD_BYTES, record, 2);
ByteArrayInputStream in = new ByteArrayInputStream(record); ByteArrayInputStream in = new ByteArrayInputStream(record);
RecordReader reader = new RecordReaderImpl(in); RecordReader reader = new RecordReaderImpl(in);
reader.readRecord(); reader.readRecord();
@@ -57,7 +57,7 @@ public class RecordReaderImplTest extends BrambleTestCase {
throws Exception { throws Exception {
// Version 1, type 2, payload length MAX_RECORD_PAYLOAD_BYTES + 1 // Version 1, type 2, payload length MAX_RECORD_PAYLOAD_BYTES + 1
byte[] header = new byte[] {1, 2, 0, 0}; byte[] header = new byte[] {1, 2, 0, 0};
ByteUtils.writeUint16(MAX_RECORD_PAYLOAD_BYTES + 1, header, 2); writeUint16(MAX_RECORD_PAYLOAD_BYTES + 1, header, 2);
ByteArrayInputStream in = new ByteArrayInputStream(header); ByteArrayInputStream in = new ByteArrayInputStream(header);
RecordReader reader = new RecordReaderImpl(in); RecordReader reader = new RecordReaderImpl(in);
reader.readRecord(); reader.readRecord();

View File

@@ -3,7 +3,6 @@ package org.briarproject.bramble.record;
import org.briarproject.bramble.api.record.Record; import org.briarproject.bramble.api.record.Record;
import org.briarproject.bramble.api.record.RecordWriter; import org.briarproject.bramble.api.record.RecordWriter;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -11,6 +10,7 @@ import java.io.ByteArrayOutputStream;
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES; import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES; import static org.briarproject.bramble.api.record.Record.RECORD_HEADER_BYTES;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes; import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -40,7 +40,7 @@ public class RecordWriterImplTest extends BrambleTestCase {
assertEquals(RECORD_HEADER_BYTES + payloadLength, written.length); assertEquals(RECORD_HEADER_BYTES + payloadLength, written.length);
assertEquals(protocolVersion, written[0]); assertEquals(protocolVersion, written[0]);
assertEquals(recordType, written[1]); assertEquals(recordType, written[1]);
assertEquals(payloadLength, ByteUtils.readUint16(written, 2)); assertEquals(payloadLength, readUint16(written, 2));
byte[] writtenPayload = new byte[payloadLength]; byte[] writtenPayload = new byte[payloadLength];
System.arraycopy(written, RECORD_HEADER_BYTES, writtenPayload, 0, System.arraycopy(written, RECORD_HEADER_BYTES, writtenPayload, 0,
payloadLength); payloadLength);

View File

@@ -22,7 +22,6 @@ import org.briarproject.bramble.api.transport.StreamReaderFactory;
import org.briarproject.bramble.api.transport.StreamWriter; import org.briarproject.bramble.api.transport.StreamWriter;
import org.briarproject.bramble.api.transport.StreamWriterFactory; import org.briarproject.bramble.api.transport.StreamWriterFactory;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -37,6 +36,7 @@ import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPT
import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getClientId; import static org.briarproject.bramble.test.TestUtils.getClientId;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTransportId; import static org.briarproject.bramble.test.TestUtils.getTransportId;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -76,8 +76,8 @@ public class SyncIntegrationTest extends BrambleTestCase {
contactId = new ContactId(234); contactId = new ContactId(234);
transportId = getTransportId(); transportId = getTransportId();
// Create the transport keys // Create the transport keys
tagKey = TestUtils.getSecretKey(); tagKey = getSecretKey();
headerKey = TestUtils.getSecretKey(); headerKey = getSecretKey();
streamNumber = 123; streamNumber = 123;
// Create a group // Create a group
ClientId clientId = getClientId(); ClientId clientId = getClientId();

View File

@@ -2,7 +2,6 @@ package org.briarproject.bramble.system;
import org.briarproject.bramble.api.Bytes; import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.IoUtils; import org.briarproject.bramble.util.IoUtils;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -15,6 +14,7 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory; import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getTestDirectory; import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
import static org.briarproject.bramble.util.OsUtils.isLinux; import static org.briarproject.bramble.util.OsUtils.isLinux;
import static org.briarproject.bramble.util.OsUtils.isMac; import static org.briarproject.bramble.util.OsUtils.isMac;
@@ -56,7 +56,7 @@ public class UnixSecureRandomSpiTest extends BrambleTestCase {
assertTrue(urandom.createNewFile()); assertTrue(urandom.createNewFile());
assertEquals(0, urandom.length()); assertEquals(0, urandom.length());
// Generate a seed // Generate a seed
byte[] seed = TestUtils.getRandomBytes(SEED_BYTES); byte[] seed = getRandomBytes(SEED_BYTES);
// Check that the engine writes the seed to the file // Check that the engine writes the seed to the file
UnixSecureRandomSpi engine = new UnixSecureRandomSpi(RANDOM_DEVICE, UnixSecureRandomSpi engine = new UnixSecureRandomSpi(RANDOM_DEVICE,
urandom); urandom);
@@ -72,7 +72,7 @@ public class UnixSecureRandomSpiTest extends BrambleTestCase {
@Test @Test
public void testEngineNextBytesReadsFromRandomDevice() throws Exception { public void testEngineNextBytesReadsFromRandomDevice() throws Exception {
// Generate some entropy // Generate some entropy
byte[] entropy = TestUtils.getRandomBytes(SEED_BYTES); byte[] entropy = getRandomBytes(SEED_BYTES);
// Write the entropy to a file // Write the entropy to a file
File urandom = new File(testDir, "urandom"); File urandom = new File(testDir, "urandom");
if (urandom.exists()) assertTrue(urandom.delete()); if (urandom.exists()) assertTrue(urandom.delete());
@@ -93,7 +93,7 @@ public class UnixSecureRandomSpiTest extends BrambleTestCase {
@Test @Test
public void testEngineGenerateSeedReadsFromRandomDevice() throws Exception { public void testEngineGenerateSeedReadsFromRandomDevice() throws Exception {
// Generate some entropy // Generate some entropy
byte[] entropy = TestUtils.getRandomBytes(SEED_BYTES); byte[] entropy = getRandomBytes(SEED_BYTES);
// Write the entropy to a file // Write the entropy to a file
File urandom = new File(testDir, "urandom"); File urandom = new File(testDir, "urandom");
if (urandom.exists()) assertTrue(urandom.delete()); if (urandom.exists()) assertTrue(urandom.delete());

View File

@@ -1,7 +1,6 @@
package org.briarproject.bramble.transport; package org.briarproject.bramble.transport;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.transport.ReorderingWindow.Change; import org.briarproject.bramble.transport.ReorderingWindow.Change;
import org.junit.Test; import org.junit.Test;
@@ -9,6 +8,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE; import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -19,7 +19,7 @@ public class ReorderingWindowTest extends BrambleTestCase {
@Test @Test
public void testBitmapConversion() { public void testBitmapConversion() {
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
byte[] bitmap = TestUtils.getRandomBytes(BITMAP_BYTES); byte[] bitmap = getRandomBytes(BITMAP_BYTES);
ReorderingWindow window = new ReorderingWindow(0L, bitmap); ReorderingWindow window = new ReorderingWindow(0L, bitmap);
assertArrayEquals(bitmap, window.getBitmap()); assertArrayEquals(bitmap, window.getBitmap());
} }

View File

@@ -3,7 +3,6 @@ package org.briarproject.bramble.transport;
import org.briarproject.bramble.api.crypto.StreamDecrypter; import org.briarproject.bramble.api.crypto.StreamDecrypter;
import org.briarproject.bramble.api.crypto.StreamEncrypter; import org.briarproject.bramble.api.crypto.StreamEncrypter;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -16,6 +15,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_HE
import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -24,10 +24,10 @@ public class StreamReaderWriterIntegrationTest extends BrambleTestCase {
@Test @Test
public void testWriteAndRead() throws Exception { public void testWriteAndRead() throws Exception {
// Generate a random tag // Generate a random tag
byte[] tag = TestUtils.getRandomBytes(TAG_LENGTH); byte[] tag = getRandomBytes(TAG_LENGTH);
// Generate two frames with random payloads // Generate two frames with random payloads
byte[] payload1 = TestUtils.getRandomBytes(123); byte[] payload1 = getRandomBytes(123);
byte[] payload2 = TestUtils.getRandomBytes(321); byte[] payload2 = getRandomBytes(321);
// Write the tag and the frames // Write the tag and the frames
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamEncrypter encrypter = new TestStreamEncrypter(out, tag); StreamEncrypter encrypter = new TestStreamEncrypter(out, tag);

View File

@@ -2,7 +2,6 @@ package org.briarproject.bramble.transport;
import org.briarproject.bramble.api.crypto.StreamDecrypter; import org.briarproject.bramble.api.crypto.StreamDecrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
@@ -13,6 +12,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENG
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_FRAME_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_FRAME_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
@NotNullByDefault @NotNullByDefault
class TestStreamDecrypter implements StreamDecrypter { class TestStreamDecrypter implements StreamDecrypter {
@@ -38,8 +38,8 @@ class TestStreamDecrypter implements StreamDecrypter {
offset += read; offset += read;
} }
finalFrame = (frame[0] & 0x80) == 0x80; finalFrame = (frame[0] & 0x80) == 0x80;
int payloadLength = ByteUtils.readUint16(frame, 0) & 0x7FFF; int payloadLength = readUint16(frame, 0) & 0x7FFF;
int paddingLength = ByteUtils.readUint16(frame, INT_16_BYTES); int paddingLength = readUint16(frame, INT_16_BYTES);
int frameLength = FRAME_HEADER_LENGTH + payloadLength + paddingLength int frameLength = FRAME_HEADER_LENGTH + payloadLength + paddingLength
+ MAC_LENGTH; + MAC_LENGTH;
while (offset < frameLength) { while (offset < frameLength) {

View File

@@ -2,7 +2,6 @@ package org.briarproject.bramble.transport;
import org.briarproject.bramble.api.crypto.StreamEncrypter; import org.briarproject.bramble.api.crypto.StreamEncrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -11,6 +10,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.FRAME_HE
import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.MAC_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_HEADER_LENGTH;
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES; import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
@NotNullByDefault @NotNullByDefault
class TestStreamEncrypter implements StreamEncrypter { class TestStreamEncrypter implements StreamEncrypter {
@@ -30,8 +30,8 @@ class TestStreamEncrypter implements StreamEncrypter {
int paddingLength, boolean finalFrame) throws IOException { int paddingLength, boolean finalFrame) throws IOException {
if (writeTagAndHeader) writeTagAndHeader(); if (writeTagAndHeader) writeTagAndHeader();
byte[] frameHeader = new byte[FRAME_HEADER_LENGTH]; byte[] frameHeader = new byte[FRAME_HEADER_LENGTH];
ByteUtils.writeUint16(payloadLength, frameHeader, 0); writeUint16(payloadLength, frameHeader, 0);
ByteUtils.writeUint16(paddingLength, frameHeader, INT_16_BYTES); writeUint16(paddingLength, frameHeader, INT_16_BYTES);
if (finalFrame) frameHeader[0] |= 0x80; if (finalFrame) frameHeader[0] |= 0x80;
out.write(frameHeader); out.write(frameHeader);
out.write(payload, 0, payloadLength); out.write(payload, 0, payloadLength);

View File

@@ -16,7 +16,6 @@ import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations; import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.test.RunAction; import org.briarproject.bramble.test.RunAction;
import org.briarproject.bramble.test.TestUtils;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.api.Action; import org.jmock.api.Action;
@@ -37,6 +36,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOC
import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION; import static org.briarproject.bramble.api.transport.TransportConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE; import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTransportId; import static org.briarproject.bramble.test.TestUtils.getTransportId;
import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -62,9 +62,9 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
private final ContactId contactId1 = new ContactId(234); private final ContactId contactId1 = new ContactId(234);
private final KeySetId keySetId = new KeySetId(345); private final KeySetId keySetId = new KeySetId(345);
private final KeySetId keySetId1 = new KeySetId(456); private final KeySetId keySetId1 = new KeySetId(456);
private final SecretKey tagKey = TestUtils.getSecretKey(); private final SecretKey tagKey = getSecretKey();
private final SecretKey headerKey = TestUtils.getSecretKey(); private final SecretKey headerKey = getSecretKey();
private final SecretKey masterKey = TestUtils.getSecretKey(); private final SecretKey masterKey = getSecretKey();
private final Random random = new Random(); private final Random random = new Random();
@Test @Test

View File

@@ -5,6 +5,15 @@ import org.junit.Test;
import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED;
import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED; import static org.briarproject.bramble.util.ByteUtils.MAX_32_BIT_UNSIGNED;
import static org.briarproject.bramble.util.ByteUtils.readUint;
import static org.briarproject.bramble.util.ByteUtils.readUint16;
import static org.briarproject.bramble.util.ByteUtils.readUint32;
import static org.briarproject.bramble.util.ByteUtils.readUint64;
import static org.briarproject.bramble.util.ByteUtils.writeUint16;
import static org.briarproject.bramble.util.ByteUtils.writeUint32;
import static org.briarproject.bramble.util.ByteUtils.writeUint64;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -12,107 +21,107 @@ public class ByteUtilsTest extends BrambleTestCase {
@Test @Test
public void testReadUint16() { public void testReadUint16() {
byte[] b = StringUtils.fromHexString("00000000"); byte[] b = fromHexString("00000000");
assertEquals(0, ByteUtils.readUint16(b, 1)); assertEquals(0, readUint16(b, 1));
b = StringUtils.fromHexString("00000100"); b = fromHexString("00000100");
assertEquals(1, ByteUtils.readUint16(b, 1)); assertEquals(1, readUint16(b, 1));
b = StringUtils.fromHexString("007FFF00"); b = fromHexString("007FFF00");
assertEquals(Short.MAX_VALUE, ByteUtils.readUint16(b, 1)); assertEquals(Short.MAX_VALUE, readUint16(b, 1));
b = StringUtils.fromHexString("00FFFF00"); b = fromHexString("00FFFF00");
assertEquals(65535, ByteUtils.readUint16(b, 1)); assertEquals(65535, readUint16(b, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint16ValidatesArguments1() { public void testReadUint16ValidatesArguments1() {
ByteUtils.readUint16(new byte[1], 0); readUint16(new byte[1], 0);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint16ValidatesArguments2() { public void testReadUint16ValidatesArguments2() {
ByteUtils.readUint16(new byte[2], 1); readUint16(new byte[2], 1);
} }
@Test @Test
public void testReadUint32() { public void testReadUint32() {
byte[] b = StringUtils.fromHexString("000000000000"); byte[] b = fromHexString("000000000000");
assertEquals(0, ByteUtils.readUint32(b, 1)); assertEquals(0, readUint32(b, 1));
b = StringUtils.fromHexString("000000000100"); b = fromHexString("000000000100");
assertEquals(1, ByteUtils.readUint32(b, 1)); assertEquals(1, readUint32(b, 1));
b = StringUtils.fromHexString("007FFFFFFF00"); b = fromHexString("007FFFFFFF00");
assertEquals(Integer.MAX_VALUE, ByteUtils.readUint32(b, 1)); assertEquals(Integer.MAX_VALUE, readUint32(b, 1));
b = StringUtils.fromHexString("00FFFFFFFF00"); b = fromHexString("00FFFFFFFF00");
assertEquals(4294967295L, ByteUtils.readUint32(b, 1)); assertEquals(4294967295L, readUint32(b, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint32ValidatesArguments1() { public void testReadUint32ValidatesArguments1() {
ByteUtils.readUint32(new byte[3], 0); readUint32(new byte[3], 0);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint32ValidatesArguments2() { public void testReadUint32ValidatesArguments2() {
ByteUtils.readUint32(new byte[4], 1); readUint32(new byte[4], 1);
} }
@Test @Test
public void testReadUint64() { public void testReadUint64() {
byte[] b = StringUtils.fromHexString("00000000000000000000"); byte[] b = fromHexString("00000000000000000000");
assertEquals(0L, ByteUtils.readUint64(b, 1)); assertEquals(0L, readUint64(b, 1));
b = StringUtils.fromHexString("00000000000000000100"); b = fromHexString("00000000000000000100");
assertEquals(1L, ByteUtils.readUint64(b, 1)); assertEquals(1L, readUint64(b, 1));
b = StringUtils.fromHexString("007FFFFFFFFFFFFFFF00"); b = fromHexString("007FFFFFFFFFFFFFFF00");
assertEquals(Long.MAX_VALUE, ByteUtils.readUint64(b, 1)); assertEquals(Long.MAX_VALUE, readUint64(b, 1));
b = StringUtils.fromHexString("00800000000000000000"); b = fromHexString("00800000000000000000");
assertEquals(Long.MIN_VALUE, ByteUtils.readUint64(b, 1)); assertEquals(Long.MIN_VALUE, readUint64(b, 1));
b = StringUtils.fromHexString("00FFFFFFFFFFFFFFFF00"); b = fromHexString("00FFFFFFFFFFFFFFFF00");
assertEquals(-1L, ByteUtils.readUint64(b, 1)); assertEquals(-1L, readUint64(b, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint64ValidatesArguments1() { public void testReadUint64ValidatesArguments1() {
ByteUtils.readUint64(new byte[7], 0); readUint64(new byte[7], 0);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testReadUint64ValidatesArguments2() { public void testReadUint64ValidatesArguments2() {
ByteUtils.readUint64(new byte[8], 1); readUint64(new byte[8], 1);
} }
@Test @Test
public void testWriteUint16() { public void testWriteUint16() {
byte[] b = new byte[4]; byte[] b = new byte[4];
ByteUtils.writeUint16(0, b, 1); writeUint16(0, b, 1);
assertEquals("00000000", StringUtils.toHexString(b)); assertEquals("00000000", toHexString(b));
ByteUtils.writeUint16(1, b, 1); writeUint16(1, b, 1);
assertEquals("00000100", StringUtils.toHexString(b)); assertEquals("00000100", toHexString(b));
ByteUtils.writeUint16(Short.MAX_VALUE, b, 1); writeUint16(Short.MAX_VALUE, b, 1);
assertEquals("007FFF00", StringUtils.toHexString(b)); assertEquals("007FFF00", toHexString(b));
ByteUtils.writeUint16(MAX_16_BIT_UNSIGNED, b, 1); writeUint16(MAX_16_BIT_UNSIGNED, b, 1);
assertEquals("00FFFF00", StringUtils.toHexString(b)); assertEquals("00FFFF00", toHexString(b));
} }
@Test @Test
public void testWriteUint16ValidatesArguments() { public void testWriteUint16ValidatesArguments() {
try { try {
ByteUtils.writeUint16(0, new byte[1], 0); writeUint16(0, new byte[1], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint16(0, new byte[2], 1); writeUint16(0, new byte[2], 1);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint16(-1, new byte[2], 0); writeUint16(-1, new byte[2], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint16(MAX_16_BIT_UNSIGNED + 1, new byte[2], 0); writeUint16(MAX_16_BIT_UNSIGNED + 1, new byte[2], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
@@ -122,38 +131,38 @@ public class ByteUtilsTest extends BrambleTestCase {
@Test @Test
public void testWriteUint32() { public void testWriteUint32() {
byte[] b = new byte[6]; byte[] b = new byte[6];
ByteUtils.writeUint32(0, b, 1); writeUint32(0, b, 1);
assertEquals("000000000000", StringUtils.toHexString(b)); assertEquals("000000000000", toHexString(b));
ByteUtils.writeUint32(1, b, 1); writeUint32(1, b, 1);
assertEquals("000000000100", StringUtils.toHexString(b)); assertEquals("000000000100", toHexString(b));
ByteUtils.writeUint32(Integer.MAX_VALUE, b, 1); writeUint32(Integer.MAX_VALUE, b, 1);
assertEquals("007FFFFFFF00", StringUtils.toHexString(b)); assertEquals("007FFFFFFF00", toHexString(b));
ByteUtils.writeUint32(MAX_32_BIT_UNSIGNED, b, 1); writeUint32(MAX_32_BIT_UNSIGNED, b, 1);
assertEquals("00FFFFFFFF00", StringUtils.toHexString(b)); assertEquals("00FFFFFFFF00", toHexString(b));
} }
@Test @Test
public void testWriteUint32ValidatesArguments() { public void testWriteUint32ValidatesArguments() {
try { try {
ByteUtils.writeUint32(0, new byte[3], 0); writeUint32(0, new byte[3], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint32(0, new byte[4], 1); writeUint32(0, new byte[4], 1);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint32(-1, new byte[4], 0); writeUint32(-1, new byte[4], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint32(MAX_32_BIT_UNSIGNED + 1, new byte[4], 0); writeUint32(MAX_32_BIT_UNSIGNED + 1, new byte[4], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
@@ -163,30 +172,30 @@ public class ByteUtilsTest extends BrambleTestCase {
@Test @Test
public void testWriteUint64() { public void testWriteUint64() {
byte[] b = new byte[10]; byte[] b = new byte[10];
ByteUtils.writeUint64(0, b, 1); writeUint64(0, b, 1);
assertEquals("00000000000000000000", StringUtils.toHexString(b)); assertEquals("00000000000000000000", toHexString(b));
ByteUtils.writeUint64(1, b, 1); writeUint64(1, b, 1);
assertEquals("00000000000000000100", StringUtils.toHexString(b)); assertEquals("00000000000000000100", toHexString(b));
ByteUtils.writeUint64(Long.MAX_VALUE, b, 1); writeUint64(Long.MAX_VALUE, b, 1);
assertEquals("007FFFFFFFFFFFFFFF00", StringUtils.toHexString(b)); assertEquals("007FFFFFFFFFFFFFFF00", toHexString(b));
} }
@Test @Test
public void testWriteUint64ValidatesArguments() { public void testWriteUint64ValidatesArguments() {
try { try {
ByteUtils.writeUint64(0, new byte[7], 0); writeUint64(0, new byte[7], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint64(0, new byte[8], 1); writeUint64(0, new byte[8], 1);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
} }
try { try {
ByteUtils.writeUint64(-1, new byte[8], 0); writeUint64(-1, new byte[8], 0);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
// Expected // Expected
@@ -198,13 +207,13 @@ public class ByteUtilsTest extends BrambleTestCase {
byte[] b = new byte[1]; byte[] b = new byte[1];
b[0] = (byte) 128; b[0] = (byte) 128;
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
assertEquals(1 << i, ByteUtils.readUint(b, i + 1)); assertEquals(1 << i, readUint(b, i + 1));
} }
b = new byte[2]; b = new byte[2];
for (int i = 0; i < 65535; i++) { for (int i = 0; i < 65535; i++) {
ByteUtils.writeUint16(i, b, 0); writeUint16(i, b, 0);
assertEquals(i, ByteUtils.readUint(b, 16)); assertEquals(i, readUint(b, 16));
assertEquals(i >> 1, ByteUtils.readUint(b, 15)); assertEquals(i >> 1, readUint(b, 15));
} }
} }
} }

View File

@@ -3,6 +3,13 @@ package org.briarproject.bramble.util;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test; import org.junit.Test;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.fromUtf8;
import static org.briarproject.bramble.util.StringUtils.macToBytes;
import static org.briarproject.bramble.util.StringUtils.macToString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
import static org.briarproject.bramble.util.StringUtils.truncateUtf8;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@@ -16,22 +23,22 @@ public class StringUtilsTest extends BrambleTestCase {
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF
}; };
String expected = "000102037F800A0B0C0D0EFF"; String expected = "000102037F800A0B0C0D0EFF";
assertEquals(expected, StringUtils.toHexString(b)); assertEquals(expected, toHexString(b));
} }
@Test @Test
public void testToHexStringEmptyInput() { public void testToHexStringEmptyInput() {
assertEquals("", StringUtils.toHexString(new byte[0])); assertEquals("", toHexString(new byte[0]));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testFromHexStringRejectsInvalidLength() { public void testFromHexStringRejectsInvalidLength() {
StringUtils.fromHexString("12345"); fromHexString("12345");
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testFromHexStringRejectsInvalidCharacter() { public void testFromHexStringRejectsInvalidCharacter() {
StringUtils.fromHexString("ABCDEFGH"); fromHexString("ABCDEFGH");
} }
@Test @Test
@@ -41,7 +48,7 @@ public class StringUtilsTest extends BrambleTestCase {
0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80, 0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF
}; };
assertArrayEquals(expected, StringUtils.fromHexString(s)); assertArrayEquals(expected, fromHexString(s));
} }
@Test @Test
@@ -51,12 +58,12 @@ public class StringUtilsTest extends BrambleTestCase {
0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80, 0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, (byte) 0xFF
}; };
assertArrayEquals(expected, StringUtils.fromHexString(s)); assertArrayEquals(expected, fromHexString(s));
} }
@Test @Test
public void testFromHexStringEmptyInput() { public void testFromHexStringEmptyInput() {
assertArrayEquals(new byte[0], StringUtils.fromHexString("")); assertArrayEquals(new byte[0], fromHexString(""));
} }
@Test @Test
@@ -64,7 +71,7 @@ public class StringUtilsTest extends BrambleTestCase {
// The Unicode null character should be encoded as a single null byte, // The Unicode null character should be encoded as a single null byte,
// not as two bytes as in CESU-8 and modified UTF-8 // not as two bytes as in CESU-8 and modified UTF-8
String s = "\u0000"; String s = "\u0000";
assertArrayEquals(new byte[1], StringUtils.toUtf8(s)); assertArrayEquals(new byte[1], toUtf8(s));
} }
@Test @Test
@@ -77,18 +84,18 @@ public class StringUtilsTest extends BrambleTestCase {
(byte) 0xC8, (byte) 0x85, // U+0205 (byte) 0xC8, (byte) 0x85, // U+0205
(byte) 0xF0, (byte) 0x90, (byte) 0x90, (byte) 0x80 // U+10400 (byte) 0xF0, (byte) 0x90, (byte) 0x90, (byte) 0x80 // U+10400
}; };
assertArrayEquals(expected, StringUtils.toUtf8(s)); assertArrayEquals(expected, toUtf8(s));
} }
@Test @Test
public void testToUtf8EmptyInput() { public void testToUtf8EmptyInput() {
assertArrayEquals(new byte[0], StringUtils.toUtf8("")); assertArrayEquals(new byte[0], toUtf8(""));
} }
@Test @Test
public void testFromUtf8AcceptsNullCharacterUsingStandardUtf8() { public void testFromUtf8AcceptsNullCharacterUsingStandardUtf8() {
// The UTF-8 encoding of the null character is valid // The UTF-8 encoding of the null character is valid
assertEquals("\u0000", StringUtils.fromUtf8(new byte[1])); assertEquals("\u0000", fromUtf8(new byte[1]));
} }
@Test @Test
@@ -100,7 +107,7 @@ public class StringUtilsTest extends BrambleTestCase {
}; };
// Conversion should ignore the invalid character and return the rest // Conversion should ignore the invalid character and return the rest
String expected = "\u0205"; String expected = "\u0205";
assertEquals(expected, StringUtils.fromUtf8(b)); assertEquals(expected, fromUtf8(b));
} }
@Test @Test
@@ -112,7 +119,7 @@ public class StringUtilsTest extends BrambleTestCase {
(byte) 0xC8, (byte) 0x85 // U+0205 (byte) 0xC8, (byte) 0x85 // U+0205
}; };
String expected = "\uD801\uDC00\u0205"; // Surrogate pair String expected = "\uD801\uDC00\u0205"; // Surrogate pair
assertEquals(expected, StringUtils.fromUtf8(b)); assertEquals(expected, fromUtf8(b));
} }
@Test @Test
@@ -126,102 +133,102 @@ public class StringUtilsTest extends BrambleTestCase {
}; };
// Conversion should ignore the invalid character and return the rest // Conversion should ignore the invalid character and return the rest
String expected = "\u0205"; String expected = "\u0205";
assertEquals(expected, StringUtils.fromUtf8(b)); assertEquals(expected, fromUtf8(b));
} }
@Test @Test
public void testFromUtf8EmptyInput() { public void testFromUtf8EmptyInput() {
assertEquals("", StringUtils.fromUtf8(new byte[0])); assertEquals("", fromUtf8(new byte[0]));
} }
@Test @Test
public void testTruncateUtf8ReturnsArgumentIfNotTruncated() { public void testTruncateUtf8ReturnsArgumentIfNotTruncated() {
String s = "Hello"; String s = "Hello";
assertSame(s, StringUtils.truncateUtf8(s, 5)); assertSame(s, truncateUtf8(s, 5));
} }
@Test @Test
public void testTruncateUtf8ChecksUtf8LengthNotStringLength() { public void testTruncateUtf8ChecksUtf8LengthNotStringLength() {
String s = "H\u0205llo"; String s = "H\u0205llo";
assertEquals(5, s.length()); assertEquals(5, s.length());
assertEquals(6, StringUtils.toUtf8(s).length); assertEquals(6, toUtf8(s).length);
String expected = "H\u0205ll"; // Sixth byte removed String expected = "H\u0205ll"; // Sixth byte removed
assertEquals(expected, StringUtils.truncateUtf8(s, 5)); assertEquals(expected, truncateUtf8(s, 5));
} }
@Test @Test
public void testTruncateUtf8RemovesTruncatedCharacter() { public void testTruncateUtf8RemovesTruncatedCharacter() {
String s = "\u0205\u0205"; // String requires four bytes String s = "\u0205\u0205"; // String requires four bytes
String expected = "\u0205"; // Partial character removed String expected = "\u0205"; // Partial character removed
String truncated = StringUtils.truncateUtf8(s, 3); String truncated = truncateUtf8(s, 3);
assertEquals(expected, truncated); assertEquals(expected, truncated);
// Converting the truncated string should not exceed the max length // Converting the truncated string should not exceed the max length
assertEquals(2, StringUtils.toUtf8(truncated).length); assertEquals(2, toUtf8(truncated).length);
} }
@Test @Test
public void testTruncateUtf8RemovesTruncatedSurrogatePair() { public void testTruncateUtf8RemovesTruncatedSurrogatePair() {
String s = "\u0205\uD801\uDC00"; // String requires six bytes String s = "\u0205\uD801\uDC00"; // String requires six bytes
String expected = "\u0205"; // Partial character removed String expected = "\u0205"; // Partial character removed
String truncated = StringUtils.truncateUtf8(s, 3); String truncated = truncateUtf8(s, 3);
assertEquals(expected, truncated); assertEquals(expected, truncated);
// Converting the truncated string should not exceed the max length // Converting the truncated string should not exceed the max length
assertEquals(2, StringUtils.toUtf8(truncated).length); assertEquals(2, toUtf8(truncated).length);
} }
@Test @Test
public void testTruncateUtf8EmptyInput() { public void testTruncateUtf8EmptyInput() {
assertEquals("", StringUtils.truncateUtf8("", 123)); assertEquals("", truncateUtf8("", 123));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToBytesRejectsShortMac() { public void testMacToBytesRejectsShortMac() {
StringUtils.macToBytes("00:00:00:00:00"); macToBytes("00:00:00:00:00");
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToBytesRejectsLongMac() { public void testMacToBytesRejectsLongMac() {
StringUtils.macToBytes("00:00:00:00:00:00:00"); macToBytes("00:00:00:00:00:00:00");
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToBytesRejectsInvalidCharacter() { public void testMacToBytesRejectsInvalidCharacter() {
StringUtils.macToBytes("00:00:00:00:00:0g"); macToBytes("00:00:00:00:00:0g");
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToBytesRejectsInvalidFormat() { public void testMacToBytesRejectsInvalidFormat() {
StringUtils.macToBytes("0:000:00:00:00:00"); macToBytes("0:000:00:00:00:00");
} }
@Test @Test
public void testMacToBytesUpperCase() { public void testMacToBytesUpperCase() {
byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F}; byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F};
String mac = "0A:1B:2C:3D:4E:5F"; String mac = "0A:1B:2C:3D:4E:5F";
assertArrayEquals(expected, StringUtils.macToBytes(mac)); assertArrayEquals(expected, macToBytes(mac));
} }
@Test @Test
public void testMacToBytesLowerCase() { public void testMacToBytesLowerCase() {
byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F}; byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F};
String mac = "0a:1b:2c:3d:4e:5f"; String mac = "0a:1b:2c:3d:4e:5f";
assertArrayEquals(expected, StringUtils.macToBytes(mac)); assertArrayEquals(expected, macToBytes(mac));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToStringRejectsShortMac() { public void testMacToStringRejectsShortMac() {
StringUtils.macToString(new byte[5]); macToString(new byte[5]);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMacToStringRejectsLongMac() { public void testMacToStringRejectsLongMac() {
StringUtils.macToString(new byte[7]); macToString(new byte[7]);
} }
@Test @Test
public void testMacToString() { public void testMacToString() {
byte[] mac = new byte[] {0x0a, 0x1b, 0x2c, 0x3d, 0x4e, 0x5f}; byte[] mac = new byte[] {0x0a, 0x1b, 0x2c, 0x3d, 0x4e, 0x5f};
String expected = "0A:1B:2C:3D:4E:5F"; String expected = "0A:1B:2C:3D:4E:5F";
assertEquals(expected, StringUtils.macToString(mac)); assertEquals(expected, macToString(mac));
} }
} }

View File

@@ -27,6 +27,7 @@ import javax.annotation.concurrent.ThreadSafe;
import static com.sun.jna.Library.OPTION_FUNCTION_MAPPER; import static com.sun.jna.Library.OPTION_FUNCTION_MAPPER;
import static com.sun.jna.Library.OPTION_TYPE_MAPPER; import static com.sun.jna.Library.OPTION_TYPE_MAPPER;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.OsUtils.isWindows; import static org.briarproject.bramble.util.OsUtils.isWindows;
@@ -35,7 +36,7 @@ import static org.briarproject.bramble.util.OsUtils.isWindows;
class WindowsShutdownManagerImpl extends ShutdownManagerImpl { class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(WindowsShutdownManagerImpl.class.getName()); getLogger(WindowsShutdownManagerImpl.class.getName());
private static final int WM_QUERYENDSESSION = 17; private static final int WM_QUERYENDSESSION = 17;
private static final int GWL_WNDPROC = -4; private static final int GWL_WNDPROC = -4;

View File

@@ -16,6 +16,7 @@ import static java.net.NetworkInterface.getNetworkInterfaces;
import static java.util.Collections.list; import static java.util.Collections.list;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@MethodsNotNullByDefault @MethodsNotNullByDefault
@@ -23,7 +24,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class JavaNetworkManager implements NetworkManager { class JavaNetworkManager implements NetworkManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(JavaNetworkManager.class.getName()); getLogger(JavaNetworkManager.class.getName());
@Inject @Inject
JavaNetworkManager() { JavaNetworkManager() {

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