Use PublicKey and PrivateKey everywhere.

This commit is contained in:
akwizgran
2019-04-23 13:31:09 +01:00
parent 0e77a47cc1
commit de8a60ea21
55 changed files with 558 additions and 463 deletions

View File

@@ -3,6 +3,9 @@ package org.briarproject.bramble.client;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyParser;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.data.BdfList;
import org.briarproject.bramble.api.data.BdfReader;
@@ -305,14 +308,15 @@ class ClientHelperImpl implements ClientHelper {
}
@Override
public byte[] sign(String label, BdfList toSign, byte[] privateKey)
public byte[] sign(String label, BdfList toSign, PrivateKey privateKey)
throws FormatException, GeneralSecurityException {
return crypto.sign(label, toByteArray(toSign), privateKey);
}
@Override
public void verifySignature(byte[] signature, String label, BdfList signed,
byte[] publicKey) throws FormatException, GeneralSecurityException {
PublicKey publicKey)
throws FormatException, GeneralSecurityException {
if (!crypto.verifySignature(signature, label, toByteArray(signed),
publicKey)) {
throw new GeneralSecurityException("Invalid signature");
@@ -327,11 +331,29 @@ class ClientHelperImpl implements ClientHelper {
if (formatVersion != FORMAT_VERSION) throw new FormatException();
String name = author.getString(1);
checkLength(name, 1, MAX_AUTHOR_NAME_LENGTH);
byte[] publicKey = author.getRaw(2);
checkLength(publicKey, 1, MAX_PUBLIC_KEY_LENGTH);
byte[] publicKeyBytes = author.getRaw(2);
checkLength(publicKeyBytes, 1, MAX_PUBLIC_KEY_LENGTH);
KeyParser parser = crypto.getSignatureKeyParser();
PublicKey publicKey;
try {
publicKey = parser.parsePublicKey(publicKeyBytes);
} catch (GeneralSecurityException e) {
throw new FormatException();
}
return authorFactory.createAuthor(formatVersion, name, publicKey);
}
@Override
public PublicKey parseAndValidateAgreementPublicKey(byte[] publicKeyBytes)
throws FormatException {
KeyParser parser = crypto.getAgreementKeyParser();
try {
return parser.parsePublicKey(publicKeyBytes);
} catch (GeneralSecurityException e) {
throw new FormatException();
}
}
@Override
public TransportProperties parseAndValidateTransportProperties(
BdfDictionary properties) throws FormatException {

View File

@@ -39,8 +39,8 @@ class PendingContactFactoryImpl implements PendingContactFactory {
PublicKey publicKey = parseHandshakeLink(link);
PendingContactId id = getPendingContactId(publicKey);
long timestamp = clock.currentTimeMillis();
return new PendingContact(id, publicKey.getEncoded(), alias,
WAITING_FOR_CONNECTION, timestamp);
return new PendingContact(id, publicKey, alias, WAITING_FOR_CONNECTION,
timestamp);
}
private PublicKey parseHandshakeLink(String link) throws FormatException {

View File

@@ -36,6 +36,7 @@ import javax.inject.Inject;
import static java.util.logging.Level.INFO;
import static org.briarproject.bramble.api.crypto.CryptoConstants.KEY_TYPE_AGREEMENT;
import static org.briarproject.bramble.api.crypto.CryptoConstants.KEY_TYPE_SIGNATURE;
import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES;
import static org.briarproject.bramble.util.LogUtils.logDuration;
import static org.briarproject.bramble.util.LogUtils.now;
@@ -200,21 +201,22 @@ class CryptoComponentImpl implements CryptoComponent {
}
@Override
public byte[] sign(String label, byte[] toSign, byte[] privateKey)
public byte[] sign(String label, byte[] toSign, PrivateKey privateKey)
throws GeneralSecurityException {
PrivateKey key = signatureKeyParser.parsePrivateKey(privateKey);
Signature sig = new EdSignature();
sig.initSign(key);
sig.initSign(privateKey);
updateSignature(sig, label, toSign);
return sig.sign();
}
@Override
public boolean verifySignature(byte[] signature, String label,
byte[] signed, byte[] publicKey) throws GeneralSecurityException {
PublicKey key = signatureKeyParser.parsePublicKey(publicKey);
byte[] signed, PublicKey publicKey)
throws GeneralSecurityException {
if (!publicKey.getKeyType().equals(KEY_TYPE_SIGNATURE))
throw new IllegalArgumentException();
Signature sig = new EdSignature();
sig.initVerify(key);
sig.initVerify(publicKey);
updateSignature(sig, label, signed);
return sig.verify(signature);
}

View File

@@ -5,6 +5,8 @@ import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.PendingContact;
import org.briarproject.bramble.api.contact.PendingContactId;
import org.briarproject.bramble.api.contact.PendingContactState;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DataTooNewException;
import org.briarproject.bramble.api.db.DataTooOldException;
@@ -689,8 +691,8 @@ interface Database<T> {
/**
* Sets the handshake key pair for the identity with the given ID.
*/
void setHandshakeKeyPair(T txn, AuthorId local, byte[] publicKey,
byte[] privateKey) throws DbException;
void setHandshakeKeyPair(T txn, AuthorId local, PublicKey publicKey,
PrivateKey privateKey) throws DbException;
/**
* Marks the given message as shared.

View File

@@ -7,6 +7,8 @@ import org.briarproject.bramble.api.contact.PendingContactId;
import org.briarproject.bramble.api.contact.event.ContactAddedEvent;
import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
import org.briarproject.bramble.api.contact.event.ContactVerifiedEvent;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.CommitAction;
import org.briarproject.bramble.api.db.CommitAction.Visitor;
@@ -1037,7 +1039,7 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
@Override
public void setHandshakeKeyPair(Transaction transaction, AuthorId local,
byte[] publicKey, byte[] privateKey) throws DbException {
PublicKey publicKey, PrivateKey privateKey) throws DbException {
if (transaction.isReadOnly()) throw new IllegalArgumentException();
T txn = unbox(transaction);
if (!db.containsIdentity(txn, local))

View File

@@ -5,7 +5,13 @@ import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.PendingContact;
import org.briarproject.bramble.api.contact.PendingContactId;
import org.briarproject.bramble.api.contact.PendingContactState;
import org.briarproject.bramble.api.crypto.AgreementPrivateKey;
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.SignaturePrivateKey;
import org.briarproject.bramble.api.crypto.SignaturePublicKey;
import org.briarproject.bramble.api.db.DataTooNewException;
import org.briarproject.bramble.api.db.DataTooOldException;
import org.briarproject.bramble.api.db.DbClosedException;
@@ -677,7 +683,7 @@ abstract class JdbcDatabase implements Database<Connection> {
ps.setBytes(1, remote.getId().getBytes());
ps.setInt(2, remote.getFormatVersion());
ps.setString(3, remote.getName());
ps.setBytes(4, remote.getPublicKey());
ps.setBytes(4, remote.getPublicKey().getEncoded());
ps.setBytes(5, local.getBytes());
ps.setBoolean(6, verified);
int affected = ps.executeUpdate();
@@ -887,12 +893,12 @@ abstract class JdbcDatabase implements Database<Connection> {
ps.setBytes(1, local.getId().getBytes());
ps.setInt(2, local.getFormatVersion());
ps.setString(3, local.getName());
ps.setBytes(4, local.getPublicKey());
ps.setBytes(5, local.getPrivateKey());
ps.setBytes(4, local.getPublicKey().getEncoded());
ps.setBytes(5, local.getPrivateKey().getEncoded());
if (i.getHandshakePublicKey() == null) ps.setNull(6, BINARY);
else ps.setBytes(6, i.getHandshakePublicKey());
else ps.setBytes(6, i.getHandshakePublicKey().getEncoded());
if (i.getHandshakePrivateKey() == null) ps.setNull(7, BINARY);
else ps.setBytes(7, i.getHandshakePrivateKey());
else ps.setBytes(7, i.getHandshakePrivateKey().getEncoded());
ps.setLong(8, i.getTimeCreated());
int affected = ps.executeUpdate();
if (affected != 1) throw new DbStateException();
@@ -1068,7 +1074,7 @@ abstract class JdbcDatabase implements Database<Connection> {
+ " VALUES (?, ?, ?, ?, ?)";
ps = txn.prepareStatement(sql);
ps.setBytes(1, p.getId().getBytes());
ps.setBytes(2, p.getPublicKey());
ps.setBytes(2, p.getPublicKey().getEncoded());
ps.setString(3, p.getAlias());
ps.setInt(4, p.getState().getValue());
ps.setLong(5, p.getTimestamp());
@@ -1444,14 +1450,16 @@ abstract class JdbcDatabase implements Database<Connection> {
int formatVersion = rs.getInt(2);
String name = rs.getString(3);
String alias = rs.getString(4);
byte[] publicKey = rs.getBytes(5);
byte[] handshakePublicKey = rs.getBytes(6);
PublicKey publicKey = new SignaturePublicKey(rs.getBytes(5));
byte[] handshakePub = rs.getBytes(6);
AuthorId localAuthorId = new AuthorId(rs.getBytes(7));
boolean verified = rs.getBoolean(8);
rs.close();
ps.close();
Author author =
new Author(authorId, formatVersion, name, publicKey);
PublicKey handshakePublicKey = handshakePub == null ?
null : new AgreementPublicKey(handshakePub);
return new Contact(c, author, localAuthorId, alias,
handshakePublicKey, verified);
} catch (SQLException e) {
@@ -1479,12 +1487,14 @@ abstract class JdbcDatabase implements Database<Connection> {
int formatVersion = rs.getInt(3);
String name = rs.getString(4);
String alias = rs.getString(5);
byte[] publicKey = rs.getBytes(6);
byte[] handshakePublicKey = rs.getBytes(7);
PublicKey publicKey = new SignaturePublicKey(rs.getBytes(6));
byte[] handshakePub = rs.getBytes(7);
AuthorId localAuthorId = new AuthorId(rs.getBytes(8));
boolean verified = rs.getBoolean(9);
Author author =
new Author(authorId, formatVersion, name, publicKey);
PublicKey handshakePublicKey = handshakePub == null ?
null : new AgreementPublicKey(handshakePub);
contacts.add(new Contact(contactId, author, localAuthorId,
alias, handshakePublicKey, verified));
}
@@ -1540,12 +1550,14 @@ abstract class JdbcDatabase implements Database<Connection> {
int formatVersion = rs.getInt(2);
String name = rs.getString(3);
String alias = rs.getString(4);
byte[] publicKey = rs.getBytes(5);
byte[] handshakePublicKey = rs.getBytes(6);
PublicKey publicKey = new SignaturePublicKey(rs.getBytes(5));
byte[] handshakePub = rs.getBytes(6);
AuthorId localAuthorId = new AuthorId(rs.getBytes(7));
boolean verified = rs.getBoolean(8);
Author author =
new Author(remote, formatVersion, name, publicKey);
PublicKey handshakePublicKey = handshakePub == null ?
null : new AgreementPublicKey(handshakePub);
contacts.add(new Contact(contactId, author, localAuthorId,
alias, handshakePublicKey, verified));
}
@@ -1756,16 +1768,20 @@ abstract class JdbcDatabase implements Database<Connection> {
if (!rs.next()) throw new DbStateException();
int formatVersion = rs.getInt(1);
String name = rs.getString(2);
byte[] publicKey = rs.getBytes(3);
byte[] privateKey = rs.getBytes(4);
byte[] handshakePublicKey = rs.getBytes(5);
byte[] handshakePrivateKey = rs.getBytes(6);
PublicKey publicKey = new SignaturePublicKey(rs.getBytes(3));
PrivateKey privateKey = new SignaturePrivateKey(rs.getBytes(4));
byte[] handshakePub = rs.getBytes(5);
byte[] handshakePriv = rs.getBytes(6);
long created = rs.getLong(7);
if (rs.next()) throw new DbStateException();
rs.close();
ps.close();
LocalAuthor local = new LocalAuthor(a, formatVersion, name,
publicKey, privateKey);
PublicKey handshakePublicKey = handshakePub == null ?
null : new AgreementPublicKey(handshakePub);
PrivateKey handshakePrivateKey = handshakePriv == null ?
null : new AgreementPrivateKey(handshakePriv);
return new Identity(local, handshakePublicKey, handshakePrivateKey,
created);
} catch (SQLException e) {
@@ -1792,13 +1808,17 @@ abstract class JdbcDatabase implements Database<Connection> {
AuthorId authorId = new AuthorId(rs.getBytes(1));
int formatVersion = rs.getInt(2);
String name = rs.getString(3);
byte[] publicKey = rs.getBytes(4);
byte[] privateKey = rs.getBytes(5);
byte[] handshakePublicKey = rs.getBytes(6);
byte[] handshakePrivateKey = rs.getBytes(7);
PublicKey publicKey = new SignaturePublicKey(rs.getBytes(4));
PrivateKey privateKey = new SignaturePrivateKey(rs.getBytes(5));
byte[] handshakePub = rs.getBytes(6);
byte[] handshakePriv = rs.getBytes(7);
long created = rs.getLong(8);
LocalAuthor local = new LocalAuthor(authorId, formatVersion,
name, publicKey, privateKey);
PublicKey handshakePublicKey = handshakePub == null ?
null : new AgreementPublicKey(handshakePub);
PrivateKey handshakePrivateKey = handshakePriv == null ?
null : new AgreementPrivateKey(handshakePriv);
identities.add(new Identity(local, handshakePublicKey,
handshakePrivateKey, created));
}
@@ -2395,7 +2415,7 @@ abstract class JdbcDatabase implements Database<Connection> {
List<PendingContact> pendingContacts = new ArrayList<>();
while (rs.next()) {
PendingContactId id = new PendingContactId(rs.getBytes(1));
byte[] publicKey = rs.getBytes(2);
PublicKey publicKey = new AgreementPublicKey(rs.getBytes(2));
String alias = rs.getString(3);
PendingContactState state =
PendingContactState.fromValue(rs.getInt(4));
@@ -3182,15 +3202,15 @@ abstract class JdbcDatabase implements Database<Connection> {
@Override
public void setHandshakeKeyPair(Connection txn, AuthorId local,
byte[] publicKey, byte[] privateKey) throws DbException {
PublicKey publicKey, PrivateKey privateKey) throws DbException {
PreparedStatement ps = null;
try {
String sql = "UPDATE localAuthors"
+ " SET handshakePublicKey = ?, handshakePrivateKey = ?"
+ " WHERE authorId = ?";
ps = txn.prepareStatement(sql);
ps.setBytes(1, publicKey);
ps.setBytes(2, privateKey);
ps.setBytes(1, publicKey.getEncoded());
ps.setBytes(2, privateKey.getEncoded());
ps.setBytes(3, local.getBytes());
int affected = ps.executeUpdate();
if (affected < 0 || affected > 1) throw new DbStateException();

View File

@@ -2,13 +2,13 @@ package org.briarproject.bramble.identity;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.AuthorFactory;
import org.briarproject.bramble.api.identity.AuthorId;
import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.ByteUtils;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
@@ -16,6 +16,8 @@ import javax.inject.Inject;
import static org.briarproject.bramble.api.identity.Author.FORMAT_VERSION;
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.writeUint32;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@Immutable
@NotNullByDefault
@@ -29,13 +31,13 @@ class AuthorFactoryImpl implements AuthorFactory {
}
@Override
public Author createAuthor(String name, byte[] publicKey) {
public Author createAuthor(String name, PublicKey publicKey) {
return createAuthor(FORMAT_VERSION, name, publicKey);
}
@Override
public Author createAuthor(int formatVersion, String name,
byte[] publicKey) {
PublicKey publicKey) {
AuthorId id = getId(formatVersion, name, publicKey);
return new Author(id, formatVersion, name, publicKey);
}
@@ -43,16 +45,17 @@ class AuthorFactoryImpl implements AuthorFactory {
@Override
public LocalAuthor createLocalAuthor(String name) {
KeyPair signatureKeyPair = crypto.generateSignatureKeyPair();
byte[] publicKey = signatureKeyPair.getPublic().getEncoded();
byte[] privateKey = signatureKeyPair.getPrivate().getEncoded();
PublicKey publicKey = signatureKeyPair.getPublic();
PrivateKey privateKey = signatureKeyPair.getPrivate();
AuthorId id = getId(FORMAT_VERSION, name, publicKey);
return new LocalAuthor(id, FORMAT_VERSION, name, publicKey, privateKey);
}
private AuthorId getId(int formatVersion, String name, byte[] publicKey) {
private AuthorId getId(int formatVersion, String name,
PublicKey publicKey) {
byte[] formatVersionBytes = new byte[INT_32_BYTES];
ByteUtils.writeUint32(formatVersion, formatVersionBytes, 0);
writeUint32(formatVersion, formatVersionBytes, 0);
return new AuthorId(crypto.hash(LABEL, formatVersionBytes,
StringUtils.toUtf8(name), publicKey));
toUtf8(name), publicKey.getEncoded()));
}
}

View File

@@ -2,6 +2,8 @@ package org.briarproject.bramble.identity;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
@@ -73,8 +75,8 @@ class IdentityManagerImpl implements IdentityManager, OpenDatabaseHook {
long start = now();
LocalAuthor localAuthor = authorFactory.createLocalAuthor(name);
KeyPair handshakeKeyPair = crypto.generateAgreementKeyPair();
byte[] handshakePub = handshakeKeyPair.getPublic().getEncoded();
byte[] handshakePriv = handshakeKeyPair.getPrivate().getEncoded();
PublicKey handshakePub = handshakeKeyPair.getPublic();
PrivateKey handshakePriv = handshakeKeyPair.getPrivate();
logDuration(LOG, "Creating identity", start);
return new Identity(localAuthor, handshakePub, handshakePriv,
clock.currentTimeMillis());
@@ -98,9 +100,9 @@ class IdentityManagerImpl implements IdentityManager, OpenDatabaseHook {
} else if (shouldStoreKeys) {
// Handshake keys were generated when loading the identity -
// store them
byte[] handshakePub =
PublicKey handshakePub =
requireNonNull(cached.getHandshakePublicKey());
byte[] handshakePriv =
PrivateKey handshakePriv =
requireNonNull(cached.getHandshakePrivateKey());
db.setHandshakeKeyPair(txn, cached.getId(), handshakePub,
handshakePriv);
@@ -122,12 +124,12 @@ class IdentityManagerImpl implements IdentityManager, OpenDatabaseHook {
}
@Override
public byte[][] getHandshakeKeys(Transaction txn) throws DbException {
public KeyPair getHandshakeKeys(Transaction txn) throws DbException {
Identity cached = getCachedIdentity(txn);
return new byte[][] {
cached.getHandshakePublicKey(),
cached.getHandshakePrivateKey()
};
PublicKey handshakePub = requireNonNull(cached.getHandshakePublicKey());
PrivateKey handshakePriv =
requireNonNull(cached.getHandshakePrivateKey());
return new KeyPair(handshakePub, handshakePriv);
}
/**
@@ -159,8 +161,8 @@ class IdentityManagerImpl implements IdentityManager, OpenDatabaseHook {
LOG.info("Identity loaded");
if (i.hasHandshakeKeyPair()) return i;
KeyPair handshakeKeyPair = crypto.generateAgreementKeyPair();
byte[] handshakePub = handshakeKeyPair.getPublic().getEncoded();
byte[] handshakePriv = handshakeKeyPair.getPrivate().getEncoded();
PublicKey handshakePub = handshakeKeyPair.getPublic();
PrivateKey handshakePriv = handshakeKeyPair.getPrivate();
LOG.info("Handshake key pair generated");
shouldStoreKeys = true;
return new Identity(i.getLocalAuthor(), handshakePub, handshakePriv,

View File

@@ -3,6 +3,9 @@ package org.briarproject.bramble.client;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyParser;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.data.BdfEntry;
import org.briarproject.bramble.api.data.BdfList;
@@ -43,6 +46,8 @@ import static org.briarproject.bramble.test.TestUtils.getAuthor;
import static org.briarproject.bramble.test.TestUtils.getMessage;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getSignaturePrivateKey;
import static org.briarproject.bramble.test.TestUtils.getSignaturePublicKey;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@@ -66,6 +71,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
context.mock(CryptoComponent.class);
private final AuthorFactory authorFactory =
context.mock(AuthorFactory.class);
private final KeyParser keyParser = context.mock(KeyParser.class);
private final GroupId groupId = new GroupId(getRandomId());
private final BdfDictionary dictionary = new BdfDictionary();
@@ -262,24 +268,25 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test
public void testSign() throws Exception {
byte[] privateKey = getRandomBytes(42);
byte[] signed = getRandomBytes(42);
PrivateKey privateKey = getSignaturePrivateKey();
byte[] signature = getRandomBytes(42);
byte[] bytes = expectToByteArray(list);
context.checking(new Expectations() {{
oneOf(cryptoComponent).sign(label, bytes, privateKey);
will(returnValue(signed));
will(returnValue(signature));
}});
assertArrayEquals(signed, clientHelper.sign(label, list, privateKey));
assertArrayEquals(signature,
clientHelper.sign(label, list, privateKey));
context.assertIsSatisfied();
}
@Test
public void testVerifySignature() throws Exception {
byte[] signature = getRandomBytes(MAX_SIGNATURE_LENGTH);
byte[] publicKey = getRandomBytes(42);
byte[] signed = expectToByteArray(list);
PublicKey publicKey = getSignaturePublicKey();
context.checking(new Expectations() {{
oneOf(cryptoComponent).verifySignature(signature, label, signed,
@@ -294,8 +301,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test
public void testVerifyWrongSignature() throws Exception {
byte[] signature = getRandomBytes(MAX_SIGNATURE_LENGTH);
byte[] publicKey = getRandomBytes(42);
byte[] signed = expectToByteArray(list);
PublicKey publicKey = getSignaturePublicKey();
context.checking(new Expectations() {{
oneOf(cryptoComponent).verifySignature(signature, label, signed,
@@ -315,6 +322,10 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test
public void testParsesAndEncodesAuthor() throws Exception {
context.checking(new Expectations() {{
oneOf(cryptoComponent).getSignatureKeyParser();
will(returnValue(keyParser));
oneOf(keyParser).parsePublicKey(author.getPublicKey().getEncoded());
will(returnValue(author.getPublicKey()));
oneOf(authorFactory).createAuthor(author.getFormatVersion(),
author.getName(), author.getPublicKey());
will(returnValue(author));
@@ -329,10 +340,14 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList authorList = BdfList.of(
author.getFormatVersion(),
author.getName(),
author.getPublicKey()
author.getPublicKey().getEncoded()
);
context.checking(new Expectations() {{
oneOf(cryptoComponent).getSignatureKeyParser();
will(returnValue(keyParser));
oneOf(keyParser).parsePublicKey(author.getPublicKey().getEncoded());
will(returnValue(author.getPublicKey()));
oneOf(authorFactory).createAuthor(author.getFormatVersion(),
author.getName(), author.getPublicKey());
will(returnValue(author));
@@ -355,7 +370,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion(),
author.getName(),
author.getPublicKey(),
author.getPublicKey().getEncoded(),
"foo"
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
@@ -366,7 +381,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
null,
author.getName(),
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -377,7 +392,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
"foo",
author.getName(),
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -387,7 +402,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion() + 1,
author.getName(),
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -397,7 +412,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion(),
"",
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -407,7 +422,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion(),
getRandomString(MAX_AUTHOR_NAME_LENGTH + 1),
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -417,7 +432,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion(),
null,
author.getPublicKey()
author.getPublicKey().getEncoded()
);
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@@ -472,6 +487,24 @@ public class ClientHelperImplTest extends BrambleTestCase {
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
@Test(expected = FormatException.class)
public void testRejectsAuthorWithInvalidPublicKey() throws Exception {
BdfList invalidAuthor = BdfList.of(
author.getFormatVersion(),
author.getName(),
author.getPublicKey().getEncoded()
);
context.checking(new Expectations() {{
oneOf(cryptoComponent).getSignatureKeyParser();
will(returnValue(keyParser));
oneOf(keyParser).parsePublicKey(author.getPublicKey().getEncoded());
will(throwException(new GeneralSecurityException()));
}});
clientHelper.parseAndValidateAuthor(invalidAuthor);
}
private byte[] expectToByteArray(BdfList list) throws Exception {
BdfWriter bdfWriter = context.mock(BdfWriter.class);

View File

@@ -21,7 +21,7 @@ import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.ID_LAB
import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.RAW_LINK_BYTES;
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertArrayEquals;
@@ -34,12 +34,11 @@ public class PendingContactFactoryImplTest extends BrambleMockTestCase {
private final CryptoComponent crypto = context.mock(CryptoComponent.class);
private final Clock clock = context.mock(Clock.class);
private final KeyParser keyParser = context.mock(KeyParser.class);
private final PublicKey publicKey = context.mock(PublicKey.class);
private final PendingContactFactory pendingContactFactory =
new PendingContactFactoryImpl(crypto, clock);
private final String alias = getRandomString(MAX_AUTHOR_NAME_LENGTH);
private final byte[] publicKeyBytes = getRandomBytes(RAW_LINK_BYTES - 1);
private final PublicKey publicKey = getAgreementPublicKey();
private final byte[] idBytes = getRandomId();
private final long timestamp = System.currentTimeMillis();
@@ -64,7 +63,7 @@ public class PendingContactFactoryImplTest extends BrambleMockTestCase {
context.checking(new Expectations() {{
oneOf(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
oneOf(keyParser).parsePublicKey(with(equal(publicKeyBytes)));
oneOf(keyParser).parsePublicKey(publicKey.getEncoded());
will(throwException(new GeneralSecurityException()));
}});
@@ -95,11 +94,9 @@ public class PendingContactFactoryImplTest extends BrambleMockTestCase {
context.checking(new Expectations() {{
oneOf(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
oneOf(keyParser).parsePublicKey(with(equal(publicKeyBytes)));
oneOf(keyParser).parsePublicKey(publicKey.getEncoded());
will(returnValue(publicKey));
allowing(publicKey).getEncoded();
will(returnValue(publicKeyBytes));
oneOf(crypto).hash(ID_LABEL, publicKeyBytes);
oneOf(crypto).hash(ID_LABEL, publicKey.getEncoded());
will(returnValue(idBytes));
oneOf(clock).currentTimeMillis();
will(returnValue(timestamp));
@@ -108,7 +105,8 @@ public class PendingContactFactoryImplTest extends BrambleMockTestCase {
PendingContact p =
pendingContactFactory.createPendingContact(link, alias);
assertArrayEquals(idBytes, p.getId().getBytes());
assertArrayEquals(publicKeyBytes, p.getPublicKey());
assertArrayEquals(publicKey.getEncoded(),
p.getPublicKey().getEncoded());
assertEquals(alias, p.getAlias());
assertEquals(WAITING_FOR_CONNECTION, p.getState());
assertEquals(timestamp, p.getTimestamp());
@@ -121,6 +119,7 @@ public class PendingContactFactoryImplTest extends BrambleMockTestCase {
private String encodeLink(int formatVersion) {
byte[] rawLink = new byte[RAW_LINK_BYTES];
rawLink[0] = (byte) formatVersion;
byte[] publicKeyBytes = publicKey.getEncoded();
arraycopy(publicKeyBytes, 0, rawLink, 1, publicKeyBytes.length);
String base32 = Base32.encode(rawLink).toLowerCase();
assertEquals(BASE32_LINK_BYTES, base32.length());

View File

@@ -1,6 +1,8 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SignaturePrivateKey;
import org.briarproject.bramble.api.crypto.SignaturePublicKey;
import org.junit.Test;
@@ -139,14 +141,14 @@ public class EdSignatureTest extends SignatureTest {
}
@Override
protected byte[] sign(String label, byte[] toSign, byte[] privateKey)
protected byte[] sign(String label, byte[] toSign, PrivateKey privateKey)
throws GeneralSecurityException {
return crypto.sign(label, toSign, privateKey);
}
@Override
protected boolean verify(byte[] signature, String label, byte[] signed,
byte[] publicKey) throws GeneralSecurityException {
PublicKey publicKey) throws GeneralSecurityException {
return crypto.verifySignature(signature, label, signed, publicKey);
}

View File

@@ -65,7 +65,7 @@ public class KeyAgreementTest extends BrambleTestCase {
}
@Test
public void testRfc7748TestVector() throws Exception {
public void testRfc7748TestVector() {
// Private keys need to be clamped because curve25519-java does the
// clamping at key generation time, not multiplication time
byte[] aPriv = Curve25519KeyParser.clamp(fromHexString(ALICE_PRIVATE));

View File

@@ -23,7 +23,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
new CryptoComponentImpl(new TestSecureRandomProvider(), null);
@Test
public void testAgreementPublicKeyLength() throws Exception {
public void testAgreementPublicKeyLength() {
// Generate 10 agreement key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateAgreementKeyPair();
@@ -70,7 +70,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
}
@Test
public void testAgreementKeyParserByFuzzing() throws Exception {
public void testAgreementKeyParserByFuzzing() {
KeyParser parser = crypto.getAgreementKeyParser();
// Generate a key pair to get the proper public key length
KeyPair p = crypto.generateAgreementKeyPair();
@@ -92,7 +92,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
}
@Test
public void testSignaturePublicKeyLength() throws Exception {
public void testSignaturePublicKeyLength() {
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
@@ -107,10 +107,10 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
byte[] key = keyPair.getPrivate().getEncoded();
PrivateKey privateKey = keyPair.getPrivate();
// Sign some random data and check the length of the signature
byte[] toBeSigned = getRandomBytes(1234);
byte[] signature = crypto.sign("label", toBeSigned, key);
byte[] signature = crypto.sign("label", toBeSigned, privateKey);
assertTrue(signature.length <= MAX_SIGNATURE_BYTES);
}
}
@@ -123,16 +123,15 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] message = getRandomBytes(123);
byte[] signature = crypto.sign("test", message,
privateKey.getEncoded());
byte[] signature = crypto.sign("test", message, privateKey);
// Verify the signature
assertTrue(crypto.verifySignature(signature, "test", message,
publicKey.getEncoded()));
publicKey));
// Encode and parse the public key - no exceptions should be thrown
publicKey = parser.parsePublicKey(publicKey.getEncoded());
// Verify the signature again
assertTrue(crypto.verifySignature(signature, "test", message,
publicKey.getEncoded()));
publicKey));
}
@Test
@@ -143,23 +142,21 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] message = getRandomBytes(123);
byte[] signature = crypto.sign("test", message,
privateKey.getEncoded());
byte[] signature = crypto.sign("test", message, privateKey);
// Verify the signature
assertTrue(crypto.verifySignature(signature, "test", message,
publicKey.getEncoded()));
publicKey));
// Encode and parse the private key - no exceptions should be thrown
privateKey = parser.parsePrivateKey(privateKey.getEncoded());
// Sign the data again - the signatures should be the same
byte[] signature1 = crypto.sign("test", message,
privateKey.getEncoded());
byte[] signature1 = crypto.sign("test", message, privateKey);
assertTrue(crypto.verifySignature(signature1, "test", message,
publicKey.getEncoded()));
publicKey));
assertArrayEquals(signature, signature1);
}
@Test
public void testSignatureKeyParserByFuzzing() throws Exception {
public void testSignatureKeyParserByFuzzing() {
KeyParser parser = crypto.getSignatureKeyParser();
// Generate a key pair to get the proper public key length
KeyPair p = crypto.generateSignatureKeyPair();

View File

@@ -2,6 +2,8 @@ package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSecureRandomProvider;
import org.briarproject.bramble.test.TestUtils;
@@ -19,23 +21,24 @@ public abstract class SignatureTest extends BrambleTestCase {
protected final CryptoComponent crypto;
private final byte[] publicKey, privateKey;
private final PublicKey publicKey;
private final PrivateKey privateKey;
private final String label = StringUtils.getRandomString(42);
private final byte[] inputBytes = TestUtils.getRandomBytes(123);
protected abstract KeyPair generateKeyPair();
protected abstract byte[] sign(String label, byte[] toSign,
byte[] privateKey) throws GeneralSecurityException;
PrivateKey privateKey) throws GeneralSecurityException;
protected abstract boolean verify(byte[] signature, String label,
byte[] signed, byte[] publicKey) throws GeneralSecurityException;
byte[] signed, PublicKey publicKey) throws GeneralSecurityException;
SignatureTest() {
crypto = new CryptoComponentImpl(new TestSecureRandomProvider(), null);
KeyPair k = generateKeyPair();
publicKey = k.getPublic().getEncoded();
privateKey = k.getPrivate().getEncoded();
publicKey = k.getPublic();
privateKey = k.getPrivate();
}
@Test
@@ -51,7 +54,7 @@ public abstract class SignatureTest extends BrambleTestCase {
public void testDifferentKeysProduceDifferentSignatures() throws Exception {
// Generate second private key
KeyPair k2 = generateKeyPair();
byte[] privateKey2 = k2.getPrivate().getEncoded();
PrivateKey privateKey2 = k2.getPrivate();
// Calculate the signature with each key
byte[] sig1 = sign(label, inputBytes, privateKey);
byte[] sig2 = sign(label, inputBytes, privateKey2);
@@ -92,7 +95,7 @@ public abstract class SignatureTest extends BrambleTestCase {
public void testDifferentKeyFailsVerification() throws Exception {
// Generate second private key
KeyPair k2 = generateKeyPair();
byte[] privateKey2 = k2.getPrivate().getEncoded();
PrivateKey privateKey2 = k2.getPrivate();
// calculate the signature with different key, should fail to verify
byte[] sig = sign(label, inputBytes, privateKey2);
assertFalse(verify(sig, label, inputBytes, publicKey));

View File

@@ -5,6 +5,8 @@ import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.PendingContactId;
import org.briarproject.bramble.api.contact.event.ContactAddedEvent;
import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.ContactExistsException;
import org.briarproject.bramble.api.db.DatabaseComponent;
@@ -66,7 +68,6 @@ import java.util.concurrent.atomic.AtomicReference;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static org.briarproject.bramble.api.crypto.CryptoConstants.MAX_AGREEMENT_PUBLIC_KEY_BYTES;
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.VISIBLE;
@@ -75,13 +76,14 @@ import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERE
import static org.briarproject.bramble.api.sync.validation.MessageState.UNKNOWN;
import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
import static org.briarproject.bramble.db.DatabaseConstants.MAX_OFFERED_MESSAGES;
import static org.briarproject.bramble.test.TestUtils.getAgreementPrivateKey;
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
import static org.briarproject.bramble.test.TestUtils.getAuthor;
import static org.briarproject.bramble.test.TestUtils.getClientId;
import static org.briarproject.bramble.test.TestUtils.getContact;
import static org.briarproject.bramble.test.TestUtils.getGroup;
import static org.briarproject.bramble.test.TestUtils.getIdentity;
import static org.briarproject.bramble.test.TestUtils.getMessage;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTransportId;
@@ -476,8 +478,8 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
}
try {
byte[] publicKey = getRandomBytes(MAX_AGREEMENT_PUBLIC_KEY_BYTES);
byte[] privateKey = getRandomBytes(123);
PublicKey publicKey = getAgreementPublicKey();
PrivateKey privateKey = getAgreementPrivateKey();
db.transaction(false, transaction ->
db.setHandshakeKeyPair(transaction, localAuthor.getId(),
publicKey, privateKey));

View File

@@ -3,6 +3,8 @@ package org.briarproject.bramble.db;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.PendingContact;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DatabaseConfig;
import org.briarproject.bramble.api.db.DbException;
@@ -58,7 +60,6 @@ import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.briarproject.bramble.api.contact.PendingContactState.FAILED;
import static org.briarproject.bramble.api.crypto.CryptoConstants.MAX_AGREEMENT_PUBLIC_KEY_BYTES;
import static org.briarproject.bramble.api.db.Metadata.REMOVE;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
@@ -72,13 +73,14 @@ import static org.briarproject.bramble.db.DatabaseConstants.DB_SETTINGS_NAMESPAC
import static org.briarproject.bramble.db.DatabaseConstants.LAST_COMPACTED_KEY;
import static org.briarproject.bramble.db.DatabaseConstants.MAX_COMPACTION_INTERVAL_MS;
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
import static org.briarproject.bramble.test.TestUtils.getAgreementPrivateKey;
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
import static org.briarproject.bramble.test.TestUtils.getAuthor;
import static org.briarproject.bramble.test.TestUtils.getClientId;
import static org.briarproject.bramble.test.TestUtils.getGroup;
import static org.briarproject.bramble.test.TestUtils.getIdentity;
import static org.briarproject.bramble.test.TestUtils.getMessage;
import static org.briarproject.bramble.test.TestUtils.getPendingContact;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
@@ -2250,8 +2252,8 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
Identity withoutKeys =
new Identity(localAuthor, null, null, identity.getTimeCreated());
assertFalse(withoutKeys.hasHandshakeKeyPair());
byte[] publicKey = getRandomBytes(MAX_AGREEMENT_PUBLIC_KEY_BYTES);
byte[] privateKey = getRandomBytes(123);
PublicKey publicKey = getAgreementPublicKey();
PrivateKey privateKey = getAgreementPrivateKey();
Database<Connection> db = open(false);
Connection txn = db.startTransaction();
@@ -2262,8 +2264,12 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
db.setHandshakeKeyPair(txn, localAuthor.getId(), publicKey, privateKey);
retrieved = db.getIdentity(txn, localAuthor.getId());
assertTrue(retrieved.hasHandshakeKeyPair());
assertArrayEquals(publicKey, retrieved.getHandshakePublicKey());
assertArrayEquals(privateKey, retrieved.getHandshakePrivateKey());
PublicKey handshakePub = retrieved.getHandshakePublicKey();
assertNotNull(handshakePub);
assertArrayEquals(publicKey.getEncoded(), handshakePub.getEncoded());
PrivateKey handshakePriv = retrieved.getHandshakePrivateKey();
assertNotNull(handshakePriv);
assertArrayEquals(privateKey.getEncoded(), handshakePriv.getEncoded());
db.commitTransaction(txn);
db.close();

View File

@@ -18,6 +18,8 @@ import org.junit.Before;
import org.junit.Test;
import static java.util.Collections.singletonList;
import static org.briarproject.bramble.test.TestUtils.getAgreementPrivateKey;
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
import static org.briarproject.bramble.test.TestUtils.getIdentity;
import static org.junit.Assert.assertEquals;
@@ -28,21 +30,16 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
private final AuthorFactory authorFactory =
context.mock(AuthorFactory.class);
private final Clock clock = context.mock(Clock.class);
private final PublicKey handshakePublicKey = context.mock(PublicKey.class);
private final PrivateKey handshakePrivateKey =
context.mock(PrivateKey.class);
private final Transaction txn = new Transaction(null, false);
private final Identity identityWithKeys = getIdentity();
private final LocalAuthor localAuthor = identityWithKeys.getLocalAuthor();
private final Identity identityWithoutKeys = new Identity(localAuthor,
null, null, identityWithKeys.getTimeCreated());
private final PublicKey handshakePublicKey = getAgreementPublicKey();
private final PrivateKey handshakePrivateKey = getAgreementPrivateKey();
private final KeyPair handshakeKeyPair =
new KeyPair(handshakePublicKey, handshakePrivateKey);
private final byte[] handshakePublicKeyBytes =
identityWithKeys.getHandshakePublicKey();
private final byte[] handshakePrivateKeyBytes =
identityWithKeys.getHandshakePrivateKey();
private IdentityManagerImpl identityManager;
@@ -69,12 +66,8 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
will(returnValue(singletonList(identityWithoutKeys)));
oneOf(crypto).generateAgreementKeyPair();
will(returnValue(handshakeKeyPair));
oneOf(handshakePublicKey).getEncoded();
will(returnValue(handshakePublicKeyBytes));
oneOf(handshakePrivateKey).getEncoded();
will(returnValue(handshakePrivateKeyBytes));
oneOf(db).setHandshakeKeyPair(txn, localAuthor.getId(),
handshakePublicKeyBytes, handshakePrivateKeyBytes);
handshakePublicKey, handshakePrivateKey);
}});
identityManager.onDatabaseOpened(txn);
@@ -104,10 +97,6 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
will(returnValue(singletonList(identityWithoutKeys)));
oneOf(crypto).generateAgreementKeyPair();
will(returnValue(handshakeKeyPair));
oneOf(handshakePublicKey).getEncoded();
will(returnValue(handshakePublicKeyBytes));
oneOf(handshakePrivateKey).getEncoded();
will(returnValue(handshakePrivateKeyBytes));
}});
assertEquals(localAuthor, identityManager.getLocalAuthor());

View File

@@ -16,10 +16,13 @@ import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Rule;
import org.junit.Test;
import static java.util.Collections.emptyList;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.COMMIT_LENGTH;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.MASTER_KEY_LABEL;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.SHARED_SECRET_LABEL;
import static org.briarproject.bramble.test.TestUtils.getAgreementPrivateKey;
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.hamcrest.Matchers.equalTo;
@@ -34,21 +37,17 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
setImposteriser(ClassImposteriser.INSTANCE);
}};
private final PublicKey alicePubKey =
context.mock(PublicKey.class, "alice");
private final byte[] alicePubKeyBytes = getRandomBytes(32);
private final PublicKey alicePubKey = getAgreementPublicKey();
private final byte[] aliceCommit = getRandomBytes(COMMIT_LENGTH);
private final byte[] alicePayload = getRandomBytes(COMMIT_LENGTH + 8);
private final byte[] aliceConfirm = getRandomBytes(SecretKey.LENGTH);
private final PublicKey bobPubKey = context.mock(PublicKey.class, "bob");
private final byte[] bobPubKeyBytes = getRandomBytes(32);
private final PublicKey bobPubKey = getAgreementPublicKey();
private final byte[] bobCommit = getRandomBytes(COMMIT_LENGTH);
private final byte[] bobPayload = getRandomBytes(COMMIT_LENGTH + 19);
private final byte[] bobConfirm = getRandomBytes(SecretKey.LENGTH);
private final PublicKey badPubKey = context.mock(PublicKey.class, "bad");
private final byte[] badPubKeyBytes = getRandomBytes(32);
private final PublicKey badPubKey = getAgreementPublicKey();
private final byte[] badCommit = getRandomBytes(COMMIT_LENGTH);
private final byte[] badConfirm = getRandomBytes(SecretKey.LENGTH);
@@ -64,15 +63,13 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
PayloadEncoder payloadEncoder;
@Mock
KeyAgreementTransport transport;
@Mock
PublicKey ourPubKey;
@Test
public void testAliceProtocol() throws Exception {
// set up
Payload theirPayload = new Payload(bobCommit, null);
Payload ourPayload = new Payload(aliceCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(bobCommit, emptyList());
Payload ourPayload = new Payload(aliceCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(alicePubKey, getAgreementPrivateKey());
SecretKey sharedSecret = getSecretKey();
SecretKey masterKey = getSecretKey();
@@ -87,24 +84,18 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(alicePayload));
allowing(payloadEncoder).encode(theirPayload);
will(returnValue(bobPayload));
allowing(ourPubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
allowing(alicePubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
allowing(bobPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
// Alice sends her public key
oneOf(transport).sendKey(alicePubKeyBytes);
oneOf(transport).sendKey(alicePubKey.getEncoded());
// Alice receives Bob's public key
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(bobPubKeyBytes));
will(returnValue(bobPubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(bobPubKeyBytes);
oneOf(keyParser).parsePublicKey(bobPubKey.getEncoded());
will(returnValue(bobPubKey));
// Alice verifies Bob's public key
@@ -114,7 +105,7 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
// Alice computes shared secret
oneOf(crypto).deriveSharedSecret(SHARED_SECRET_LABEL, bobPubKey,
ourKeyPair, new byte[] {PROTOCOL_VERSION},
alicePubKeyBytes, bobPubKeyBytes);
alicePubKey.getEncoded(), bobPubKey.getEncoded());
will(returnValue(sharedSecret));
// Alice sends her confirmation record
@@ -146,9 +137,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test
public void testBobProtocol() throws Exception {
// set up
Payload theirPayload = new Payload(aliceCommit, null);
Payload ourPayload = new Payload(bobCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(aliceCommit, emptyList());
Payload ourPayload = new Payload(bobCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(bobPubKey, getAgreementPrivateKey());
SecretKey sharedSecret = getSecretKey();
SecretKey masterKey = getSecretKey();
@@ -163,20 +154,14 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(bobPayload));
allowing(payloadEncoder).encode(theirPayload);
will(returnValue(alicePayload));
allowing(ourPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
allowing(alicePubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
allowing(bobPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
// Bob receives Alice's public key
oneOf(transport).receiveKey();
will(returnValue(alicePubKeyBytes));
will(returnValue(alicePubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(alicePubKeyBytes);
oneOf(keyParser).parsePublicKey(alicePubKey.getEncoded());
will(returnValue(alicePubKey));
// Bob verifies Alice's public key
@@ -184,12 +169,12 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(aliceCommit));
// Bob sends his public key
oneOf(transport).sendKey(bobPubKeyBytes);
oneOf(transport).sendKey(bobPubKey.getEncoded());
// Bob computes shared secret
oneOf(crypto).deriveSharedSecret(SHARED_SECRET_LABEL, alicePubKey,
ourKeyPair, new byte[] {PROTOCOL_VERSION},
alicePubKeyBytes, bobPubKeyBytes);
alicePubKey.getEncoded(), bobPubKey.getEncoded());
will(returnValue(sharedSecret));
// Bob receives Alices's confirmation record
@@ -221,9 +206,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class)
public void testAliceProtocolAbortOnBadKey() throws Exception {
// set up
Payload theirPayload = new Payload(bobCommit, null);
Payload ourPayload = new Payload(aliceCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(bobCommit, emptyList());
Payload ourPayload = new Payload(aliceCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(alicePubKey, getAgreementPrivateKey());
KeyAgreementProtocol protocol = new KeyAgreementProtocol(callbacks,
crypto, keyAgreementCrypto, payloadEncoder, transport,
@@ -232,20 +217,18 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
// expectations
context.checking(new Expectations() {{
// Helpers
allowing(ourPubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
// Alice sends her public key
oneOf(transport).sendKey(alicePubKeyBytes);
oneOf(transport).sendKey(alicePubKey.getEncoded());
// Alice receives a bad public key
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(badPubKeyBytes));
will(returnValue(badPubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(badPubKeyBytes);
oneOf(keyParser).parsePublicKey(badPubKey.getEncoded());
will(returnValue(badPubKey));
// Alice verifies Bob's public key
@@ -258,7 +241,7 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
// Alice never computes shared secret
never(crypto).deriveSharedSecret(SHARED_SECRET_LABEL, badPubKey,
ourKeyPair, new byte[] {PROTOCOL_VERSION},
alicePubKeyBytes, bobPubKeyBytes);
alicePubKey.getEncoded(), bobPubKey.getEncoded());
}});
// execute
@@ -268,9 +251,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class)
public void testBobProtocolAbortOnBadKey() throws Exception {
// set up
Payload theirPayload = new Payload(aliceCommit, null);
Payload ourPayload = new Payload(bobCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(aliceCommit, emptyList());
Payload ourPayload = new Payload(bobCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(bobPubKey, getAgreementPrivateKey());
KeyAgreementProtocol protocol = new KeyAgreementProtocol(callbacks,
crypto, keyAgreementCrypto, payloadEncoder, transport,
@@ -279,16 +262,14 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
// expectations
context.checking(new Expectations() {{
// Helpers
allowing(ourPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
// Bob receives a bad public key
oneOf(transport).receiveKey();
will(returnValue(badPubKeyBytes));
will(returnValue(badPubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(badPubKeyBytes);
oneOf(keyParser).parsePublicKey(badPubKey.getEncoded());
will(returnValue(badPubKey));
// Bob verifies Alice's public key
@@ -299,7 +280,7 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
oneOf(transport).sendAbort(false);
// Bob never sends his public key
never(transport).sendKey(bobPubKeyBytes);
never(transport).sendKey(bobPubKey.getEncoded());
}});
// execute
@@ -309,9 +290,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class)
public void testAliceProtocolAbortOnBadConfirm() throws Exception {
// set up
Payload theirPayload = new Payload(bobCommit, null);
Payload ourPayload = new Payload(aliceCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(bobCommit, emptyList());
Payload ourPayload = new Payload(aliceCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(alicePubKey, getAgreementPrivateKey());
SecretKey sharedSecret = getSecretKey();
KeyAgreementProtocol protocol = new KeyAgreementProtocol(callbacks,
@@ -325,22 +306,18 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(alicePayload));
allowing(payloadEncoder).encode(theirPayload);
will(returnValue(bobPayload));
allowing(ourPubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
allowing(bobPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
// Alice sends her public key
oneOf(transport).sendKey(alicePubKeyBytes);
oneOf(transport).sendKey(alicePubKey.getEncoded());
// Alice receives Bob's public key
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(bobPubKeyBytes));
will(returnValue(bobPubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(bobPubKeyBytes);
oneOf(keyParser).parsePublicKey(bobPubKey.getEncoded());
will(returnValue(bobPubKey));
// Alice verifies Bob's public key
@@ -350,7 +327,7 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
// Alice computes shared secret
oneOf(crypto).deriveSharedSecret(SHARED_SECRET_LABEL, bobPubKey,
ourKeyPair, new byte[] {PROTOCOL_VERSION},
alicePubKeyBytes, bobPubKeyBytes);
alicePubKey.getEncoded(), bobPubKey.getEncoded());
will(returnValue(sharedSecret));
// Alice sends her confirmation record
@@ -384,9 +361,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class)
public void testBobProtocolAbortOnBadConfirm() throws Exception {
// set up
Payload theirPayload = new Payload(aliceCommit, null);
Payload ourPayload = new Payload(bobCommit, null);
KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
Payload theirPayload = new Payload(aliceCommit, emptyList());
Payload ourPayload = new Payload(bobCommit, emptyList());
KeyPair ourKeyPair = new KeyPair(bobPubKey, getAgreementPrivateKey());
SecretKey sharedSecret = getSecretKey();
KeyAgreementProtocol protocol = new KeyAgreementProtocol(callbacks,
@@ -400,18 +377,14 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(bobPayload));
allowing(payloadEncoder).encode(theirPayload);
will(returnValue(alicePayload));
allowing(ourPubKey).getEncoded();
will(returnValue(bobPubKeyBytes));
allowing(crypto).getAgreementKeyParser();
will(returnValue(keyParser));
allowing(alicePubKey).getEncoded();
will(returnValue(alicePubKeyBytes));
// Bob receives Alice's public key
oneOf(transport).receiveKey();
will(returnValue(alicePubKeyBytes));
will(returnValue(alicePubKey.getEncoded()));
oneOf(callbacks).initialRecordReceived();
oneOf(keyParser).parsePublicKey(alicePubKeyBytes);
oneOf(keyParser).parsePublicKey(alicePubKey.getEncoded());
will(returnValue(alicePubKey));
// Bob verifies Alice's public key
@@ -419,12 +392,12 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
will(returnValue(aliceCommit));
// Bob sends his public key
oneOf(transport).sendKey(bobPubKeyBytes);
oneOf(transport).sendKey(bobPubKey.getEncoded());
// Bob computes shared secret
oneOf(crypto).deriveSharedSecret(SHARED_SECRET_LABEL, alicePubKey,
ourKeyPair, new byte[] {PROTOCOL_VERSION},
alicePubKeyBytes, bobPubKeyBytes);
alicePubKey.getEncoded(), bobPubKey.getEncoded());
will(returnValue(sharedSecret));
// Bob receives a bad confirmation record