restructure and unite service android/java to libsignal

This commit is contained in:
Ryan ZHAO
2020-11-26 09:46:52 +11:00
parent 673d35625b
commit 7a66a47520
3790 changed files with 101955 additions and 74 deletions

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.session.libsignal">
</manifest>

View File

@@ -0,0 +1,10 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public interface DecryptionCallback {
public void handlePlaintext(byte[] plaintext);
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class DuplicateMessageException extends Exception {
public DuplicateMessageException(String s) {
super(s);
}
}

View File

@@ -0,0 +1,56 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.util.Hex;
/**
* A class for representing an identity key.
*
* @author Moxie Marlinspike
*/
public class IdentityKey {
private final ECPublicKey publicKey;
public IdentityKey(ECPublicKey publicKey) {
this.publicKey = publicKey;
}
public IdentityKey(byte[] bytes, int offset) throws InvalidKeyException {
this.publicKey = Curve.decodePoint(bytes, offset);
}
public ECPublicKey getPublicKey() {
return publicKey;
}
public byte[] serialize() {
return publicKey.serialize();
}
public String getFingerprint() {
return Hex.toString(publicKey.serialize());
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof IdentityKey)) return false;
return publicKey.equals(((IdentityKey) other).getPublicKey());
}
@Override
public int hashCode() {
return publicKey.hashCode();
}
}

View File

@@ -0,0 +1,55 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import static org.session.libsignal.libsignal.state.StorageProtos.IdentityKeyPairStructure;
/**
* Holder for public and private identity key pair.
*
* @author Moxie Marlinspike
*/
public class IdentityKeyPair {
private final IdentityKey publicKey;
private final ECPrivateKey privateKey;
public IdentityKeyPair(IdentityKey publicKey, ECPrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public IdentityKeyPair(byte[] serialized) throws InvalidKeyException {
try {
IdentityKeyPairStructure structure = IdentityKeyPairStructure.parseFrom(serialized);
this.publicKey = new IdentityKey(structure.getPublicKey().toByteArray(), 0);
this.privateKey = Curve.decodePrivatePoint(structure.getPrivateKey().toByteArray());
} catch (InvalidProtocolBufferException e) {
throw new InvalidKeyException(e);
}
}
public IdentityKey getPublicKey() {
return publicKey;
}
public ECPrivateKey getPrivateKey() {
return privateKey;
}
public byte[] serialize() {
return IdentityKeyPairStructure.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
.setPrivateKey(ByteString.copyFrom(privateKey.serialize()))
.build().toByteArray();
}
}

View File

@@ -0,0 +1,23 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class InvalidKeyException extends Exception {
public InvalidKeyException() {}
public InvalidKeyException(String detailMessage) {
super(detailMessage);
}
public InvalidKeyException(Throwable throwable) {
super(throwable);
}
public InvalidKeyException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}

View File

@@ -0,0 +1,16 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class InvalidKeyIdException extends Exception {
public InvalidKeyIdException(String detailMessage) {
super(detailMessage);
}
public InvalidKeyIdException(Throwable throwable) {
super(throwable);
}
}

View File

@@ -0,0 +1,17 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class InvalidMacException extends Exception {
public InvalidMacException(String detailMessage) {
super(detailMessage);
}
public InvalidMacException(Throwable throwable) {
super(throwable);
}
}

View File

@@ -0,0 +1,29 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
import java.util.List;
public class InvalidMessageException extends Exception {
public InvalidMessageException() {}
public InvalidMessageException(String detailMessage) {
super(detailMessage);
}
public InvalidMessageException(Throwable throwable) {
super(throwable);
}
public InvalidMessageException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public InvalidMessageException(String detailMessage, List<Exception> exceptions) {
super(detailMessage, exceptions.get(0));
}
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class InvalidVersionException extends Exception {
public InvalidVersionException(String detailMessage) {
super(detailMessage);
}
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class LegacyMessageException extends Exception {
public LegacyMessageException(String s) {
super(s);
}
}

View File

@@ -0,0 +1,16 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class NoSessionException extends Exception {
public NoSessionException(String s) {
super(s);
}
public NoSessionException(Exception nested) {
super(nested);
}
}

View File

@@ -0,0 +1,212 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.logging.Log;
import org.session.libsignal.libsignal.protocol.PreKeySignalMessage;
import org.session.libsignal.libsignal.protocol.SignalMessage;
import org.session.libsignal.libsignal.ratchet.AliceSignalProtocolParameters;
import org.session.libsignal.libsignal.ratchet.BobSignalProtocolParameters;
import org.session.libsignal.libsignal.ratchet.RatchetingSession;
import org.session.libsignal.libsignal.state.IdentityKeyStore;
import org.session.libsignal.libsignal.state.PreKeyBundle;
import org.session.libsignal.libsignal.state.PreKeyStore;
import org.session.libsignal.libsignal.state.SessionRecord;
import org.session.libsignal.libsignal.state.SessionStore;
import org.session.libsignal.libsignal.state.SignalProtocolStore;
import org.session.libsignal.libsignal.state.SignedPreKeyStore;
import org.session.libsignal.libsignal.util.guava.Optional;
/**
* SessionBuilder is responsible for setting up encrypted sessions.
* Once a session has been established, {@link org.session.libsignal.libsignal.SessionCipher}
* can be used to encrypt/decrypt messages in that session.
* <p>
* Sessions are built from one of three different possible vectors:
* <ol>
* <li>A {@link org.session.libsignal.libsignal.state.PreKeyBundle} retrieved from a server.</li>
* <li>A {@link PreKeySignalMessage} received from a client.</li>
* </ol>
*
* Sessions are constructed per recipientId + deviceId tuple. Remote logical users are identified
* by their recipientId, and each logical recipientId can have multiple physical devices.
*
* @author Moxie Marlinspike
*/
public class SessionBuilder {
private static final String TAG = SessionBuilder.class.getSimpleName();
private final SessionStore sessionStore;
private final PreKeyStore preKeyStore;
private final SignedPreKeyStore signedPreKeyStore;
private final IdentityKeyStore identityKeyStore;
private final SignalProtocolAddress remoteAddress;
/**
* Constructs a SessionBuilder.
*
* @param sessionStore The {@link org.session.libsignal.libsignal.state.SessionStore} to store the constructed session in.
* @param preKeyStore The {@link org.session.libsignal.libsignal.state.PreKeyStore} where the client's local {@link org.session.libsignal.libsignal.state.PreKeyRecord}s are stored.
* @param identityKeyStore The {@link org.session.libsignal.libsignal.state.IdentityKeyStore} containing the client's identity key information.
* @param remoteAddress The address of the remote user to build a session with.
*/
public SessionBuilder(SessionStore sessionStore,
PreKeyStore preKeyStore,
SignedPreKeyStore signedPreKeyStore,
IdentityKeyStore identityKeyStore,
SignalProtocolAddress remoteAddress)
{
this.sessionStore = sessionStore;
this.preKeyStore = preKeyStore;
this.signedPreKeyStore = signedPreKeyStore;
this.identityKeyStore = identityKeyStore;
this.remoteAddress = remoteAddress;
}
/**
* Constructs a SessionBuilder
* @param store The {@link SignalProtocolStore} to store all state information in.
* @param remoteAddress The address of the remote user to build a session with.
*/
public SessionBuilder(SignalProtocolStore store, SignalProtocolAddress remoteAddress) {
this(store, store, store, store, remoteAddress);
}
/**
* Build a new session from a received {@link PreKeySignalMessage}.
*
* After a session is constructed in this way, the embedded {@link SignalMessage}
* can be decrypted.
*
* @param message The received {@link PreKeySignalMessage}.
* @throws org.session.libsignal.libsignal.InvalidKeyIdException when there is no local
* {@link org.session.libsignal.libsignal.state.PreKeyRecord}
* that corresponds to the PreKey ID in
* the message.
* @throws org.session.libsignal.libsignal.InvalidKeyException when the message is formatted incorrectly.
* @throws org.session.libsignal.libsignal.UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
*/
/*package*/ Optional<Integer> process(SessionRecord sessionRecord, PreKeySignalMessage message)
throws InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
IdentityKey theirIdentityKey = message.getIdentityKey();
if (!identityKeyStore.isTrustedIdentity(remoteAddress, theirIdentityKey, IdentityKeyStore.Direction.RECEIVING)) {
throw new UntrustedIdentityException(remoteAddress.getName(), theirIdentityKey);
}
Optional<Integer> unsignedPreKeyId = processV3(sessionRecord, message);
identityKeyStore.saveIdentity(remoteAddress, theirIdentityKey);
return unsignedPreKeyId;
}
private Optional<Integer> processV3(SessionRecord sessionRecord, PreKeySignalMessage message)
throws UntrustedIdentityException, InvalidKeyIdException, InvalidKeyException
{
if (sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize())) {
Log.w(TAG, "We've already setup a session for this V3 message, letting bundled message fall through...");
return Optional.absent();
}
ECKeyPair ourSignedPreKey = signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair();
BobSignalProtocolParameters.Builder parameters = BobSignalProtocolParameters.newBuilder();
parameters.setTheirBaseKey(message.getBaseKey())
.setTheirIdentityKey(message.getIdentityKey())
.setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
.setOurSignedPreKey(ourSignedPreKey)
.setOurRatchetKey(ourSignedPreKey);
if (message.getPreKeyId().isPresent()) {
parameters.setOurOneTimePreKey(Optional.of(preKeyStore.loadPreKey(message.getPreKeyId().get()).getKeyPair()));
} else {
parameters.setOurOneTimePreKey(Optional.<ECKeyPair>absent());
}
if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();
RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());
sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId());
sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize());
if (message.getPreKeyId().isPresent()) {
return message.getPreKeyId();
} else {
return Optional.absent();
}
}
/**
* Build a new session from a {@link org.session.libsignal.libsignal.state.PreKeyBundle} retrieved from
* a server.
*
* @param preKey A PreKey for the destination recipient, retrieved from a server.
* @throws InvalidKeyException when the {@link org.session.libsignal.libsignal.state.PreKeyBundle} is
* badly formatted.
* @throws org.session.libsignal.libsignal.UntrustedIdentityException when the sender's
* {@link IdentityKey} is not
* trusted.
*/
public void process(PreKeyBundle preKey) throws InvalidKeyException, UntrustedIdentityException {
synchronized (SessionCipher.SESSION_LOCK) {
if (!identityKeyStore.isTrustedIdentity(remoteAddress, preKey.getIdentityKey(), IdentityKeyStore.Direction.SENDING)) {
throw new UntrustedIdentityException(remoteAddress.getName(), preKey.getIdentityKey());
}
if (preKey.getSignedPreKey() != null &&
!Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),
preKey.getSignedPreKey().serialize(),
preKey.getSignedPreKeySignature()))
{
throw new InvalidKeyException("Invalid signature on device key!");
}
if (preKey.getSignedPreKey() == null) {
throw new InvalidKeyException("No signed prekey!");
}
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
ECKeyPair ourBaseKey = Curve.generateKeyPair();
ECPublicKey theirSignedPreKey = preKey.getSignedPreKey();
Optional<ECPublicKey> theirOneTimePreKey = Optional.fromNullable(preKey.getPreKey());
Optional<Integer> theirOneTimePreKeyId = theirOneTimePreKey.isPresent() ? Optional.of(preKey.getPreKeyId()) :
Optional.<Integer>absent();
AliceSignalProtocolParameters.Builder parameters = AliceSignalProtocolParameters.newBuilder();
parameters.setOurBaseKey(ourBaseKey)
.setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
.setTheirIdentityKey(preKey.getIdentityKey())
.setTheirSignedPreKey(theirSignedPreKey)
.setTheirRatchetKey(theirSignedPreKey)
.setTheirOneTimePreKey(theirOneTimePreKey);
if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();
RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());
sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId, preKey.getSignedPreKeyId(), ourBaseKey.getPublicKey());
sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId());
sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize());
identityKeyStore.saveIdentity(remoteAddress, preKey.getIdentityKey());
sessionStore.storeSession(remoteAddress, sessionRecord);
}
}
}

View File

@@ -0,0 +1,440 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.loki.FallbackSessionCipher;
import org.session.libsignal.libsignal.protocol.CiphertextMessage;
import org.session.libsignal.libsignal.protocol.PreKeySignalMessage;
import org.session.libsignal.libsignal.protocol.SignalMessage;
import org.session.libsignal.libsignal.ratchet.ChainKey;
import org.session.libsignal.libsignal.ratchet.MessageKeys;
import org.session.libsignal.libsignal.ratchet.RootKey;
import org.session.libsignal.libsignal.state.IdentityKeyStore;
import org.session.libsignal.libsignal.state.PreKeyStore;
import org.session.libsignal.libsignal.state.SessionRecord;
import org.session.libsignal.libsignal.state.SessionState;
import org.session.libsignal.libsignal.state.SessionStore;
import org.session.libsignal.libsignal.state.SignalProtocolStore;
import org.session.libsignal.libsignal.state.SignedPreKeyStore;
import org.session.libsignal.libsignal.util.Pair;
import org.session.libsignal.libsignal.util.guava.Optional;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import static org.session.libsignal.libsignal.state.SessionState.UnacknowledgedPreKeyMessageItems;
/**
* The main entry point for Signal Protocol encrypt/decrypt operations.
*
* Once a session has been established with {@link SessionBuilder},
* this class can be used for all encrypt/decrypt operations within
* that session.
*
* @author Moxie Marlinspike
*/
public class SessionCipher {
public static final Object SESSION_LOCK = new Object();
private final SessionStore sessionStore;
private final IdentityKeyStore identityKeyStore;
private final SessionBuilder sessionBuilder;
private final PreKeyStore preKeyStore;
private final SignalProtocolAddress remoteAddress;
/**
* Construct a SessionCipher for encrypt/decrypt operations on a session.
* In order to use SessionCipher, a session must have already been created
* and stored using {@link SessionBuilder}.
*
* @param sessionStore The {@link SessionStore} that contains a session for this recipient.
* @param remoteAddress The remote address that messages will be encrypted to or decrypted from.
*/
public SessionCipher(SessionStore sessionStore, PreKeyStore preKeyStore,
SignedPreKeyStore signedPreKeyStore, IdentityKeyStore identityKeyStore,
SignalProtocolAddress remoteAddress)
{
this.sessionStore = sessionStore;
this.preKeyStore = preKeyStore;
this.identityKeyStore = identityKeyStore;
this.remoteAddress = remoteAddress;
this.sessionBuilder = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
identityKeyStore, remoteAddress);
}
public SessionCipher(SignalProtocolStore store, SignalProtocolAddress remoteAddress) {
this(store, store, store, store, remoteAddress);
}
/**
* Encrypt a message.
*
* @param paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
* @return A ciphertext message encrypted to the recipient+device tuple.
*/
public CiphertextMessage encrypt(byte[] paddedMessage) throws UntrustedIdentityException {
synchronized (SESSION_LOCK) {
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
SessionState sessionState = sessionRecord.getSessionState();
ChainKey chainKey = sessionState.getSenderChainKey();
MessageKeys messageKeys = chainKey.getMessageKeys();
ECPublicKey senderEphemeral = sessionState.getSenderRatchetKey();
int previousCounter = sessionState.getPreviousCounter();
int sessionVersion = sessionState.getSessionVersion();
byte[] ciphertextBody = getCiphertext(messageKeys, paddedMessage);
CiphertextMessage ciphertextMessage = new SignalMessage(sessionVersion, messageKeys.getMacKey(),
senderEphemeral, chainKey.getIndex(),
previousCounter, ciphertextBody,
sessionState.getLocalIdentityKey(),
sessionState.getRemoteIdentityKey());
if (sessionState.hasUnacknowledgedPreKeyMessage()) {
UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems();
int localRegistrationId = sessionState.getLocalRegistrationId();
ciphertextMessage = new PreKeySignalMessage(sessionVersion, localRegistrationId, items.getPreKeyId(),
items.getSignedPreKeyId(), items.getBaseKey(),
sessionState.getLocalIdentityKey(),
(SignalMessage) ciphertextMessage);
}
sessionState.setSenderChainKey(chainKey.getNextChainKey());
if (!identityKeyStore.isTrustedIdentity(remoteAddress, sessionState.getRemoteIdentityKey(), IdentityKeyStore.Direction.SENDING)) {
throw new UntrustedIdentityException(remoteAddress.getName(), sessionState.getRemoteIdentityKey());
}
identityKeyStore.saveIdentity(remoteAddress, sessionState.getRemoteIdentityKey());
sessionStore.storeSession(remoteAddress, sessionRecord);
return ciphertextMessage;
}
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link PreKeySignalMessage} to decrypt.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws InvalidKeyIdException when there is no local {@link org.session.libsignal.libsignal.state.PreKeyRecord}
* that corresponds to the PreKey ID in the message.
* @throws InvalidKeyException when the message is formatted incorrectly.
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
*/
public byte[] decrypt(PreKeySignalMessage ciphertext)
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
return decrypt(ciphertext, new NullDecryptionCallback());
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link PreKeySignalMessage} to decrypt.
* @param callback A callback that is triggered after decryption is complete,
* but before the updated session state has been committed to the session
* DB. This allows some implementations to store the committed plaintext
* to a DB first, in case they are concerned with a crash happening between
* the time the session state is updated but before they're able to store
* the plaintext to disk.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws InvalidKeyIdException when there is no local {@link org.session.libsignal.libsignal.state.PreKeyRecord}
* that corresponds to the PreKey ID in the message.
* @throws InvalidKeyException when the message is formatted incorrectly.
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
*/
public byte[] decrypt(PreKeySignalMessage ciphertext, DecryptionCallback callback)
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
synchronized (SESSION_LOCK) {
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
Optional<Integer> unsignedPreKeyId = sessionBuilder.process(sessionRecord, ciphertext);
byte[] plaintext = decrypt(sessionRecord, ciphertext.getWhisperMessage());
callback.handlePlaintext(plaintext);
sessionStore.storeSession(remoteAddress, sessionRecord);
if (unsignedPreKeyId.isPresent()) {
preKeyStore.removePreKey(unsignedPreKeyId.get());
}
return plaintext;
}
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link SignalMessage} to decrypt.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws NoSessionException if there is no established session for this contact.
*/
public byte[] decrypt(SignalMessage ciphertext)
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException,
NoSessionException, UntrustedIdentityException
{
return decrypt(ciphertext, new NullDecryptionCallback());
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link SignalMessage} to decrypt.
* @param callback A callback that is triggered after decryption is complete,
* but before the updated session state has been committed to the session
* DB. This allows some implementations to store the committed plaintext
* to a DB first, in case they are concerned with a crash happening between
* the time the session state is updated but before they're able to store
* the plaintext to disk.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws NoSessionException if there is no established session for this contact.
*/
public byte[] decrypt(SignalMessage ciphertext, DecryptionCallback callback)
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException,
NoSessionException, UntrustedIdentityException
{
synchronized (SESSION_LOCK) {
if (!sessionStore.containsSession(remoteAddress)) {
throw new NoSessionException("No session for: " + remoteAddress);
}
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
byte[] plaintext = decrypt(sessionRecord, ciphertext);
if (!identityKeyStore.isTrustedIdentity(remoteAddress, sessionRecord.getSessionState().getRemoteIdentityKey(), IdentityKeyStore.Direction.RECEIVING)) {
throw new UntrustedIdentityException(remoteAddress.getName(), sessionRecord.getSessionState().getRemoteIdentityKey());
}
identityKeyStore.saveIdentity(remoteAddress, sessionRecord.getSessionState().getRemoteIdentityKey());
callback.handlePlaintext(plaintext);
sessionStore.storeSession(remoteAddress, sessionRecord);
return plaintext;
}
}
private byte[] decrypt(SessionRecord sessionRecord, SignalMessage ciphertext)
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException
{
synchronized (SESSION_LOCK) {
Iterator<SessionState> previousStates = sessionRecord.getPreviousSessionStates().iterator();
List<Exception> exceptions = new LinkedList<Exception>();
try {
SessionState sessionState = new SessionState(sessionRecord.getSessionState());
byte[] plaintext = decrypt(sessionState, ciphertext);
sessionRecord.setState(sessionState);
return plaintext;
} catch (InvalidMessageException e) {
exceptions.add(e);
}
while (previousStates.hasNext()) {
try {
SessionState promotedState = new SessionState(previousStates.next());
byte[] plaintext = decrypt(promotedState, ciphertext);
previousStates.remove();
sessionRecord.promoteState(promotedState);
return plaintext;
} catch (InvalidMessageException e) {
exceptions.add(e);
}
}
throw new InvalidMessageException("No valid sessions.", exceptions);
}
}
private byte[] decrypt(SessionState sessionState, SignalMessage ciphertextMessage)
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException
{
if (!sessionState.hasSenderChain()) {
throw new InvalidMessageException("Uninitialized session!");
}
if (ciphertextMessage.getMessageVersion() != sessionState.getSessionVersion()) {
throw new InvalidMessageException(String.format("Message version %d, but session version %d",
ciphertextMessage.getMessageVersion(),
sessionState.getSessionVersion()));
}
ECPublicKey theirEphemeral = ciphertextMessage.getSenderRatchetKey();
int counter = ciphertextMessage.getCounter();
ChainKey chainKey = getOrCreateChainKey(sessionState, theirEphemeral);
MessageKeys messageKeys = getOrCreateMessageKeys(sessionState, theirEphemeral,
chainKey, counter);
ciphertextMessage.verifyMac(sessionState.getRemoteIdentityKey(),
sessionState.getLocalIdentityKey(),
messageKeys.getMacKey());
byte[] plaintext = getPlaintext(messageKeys, ciphertextMessage.getBody());
sessionState.clearUnacknowledgedPreKeyMessage();
return plaintext;
}
public int getRemoteRegistrationId() {
synchronized (SESSION_LOCK) {
SessionRecord record = sessionStore.loadSession(remoteAddress);
return record.getSessionState().getRemoteRegistrationId();
}
}
public int getSessionVersion() {
synchronized (SESSION_LOCK) {
if (!sessionStore.containsSession(remoteAddress)) {
// Loki - If we have no session then we must be using the FallbackSessionCipher
return FallbackSessionCipher.getSessionVersion();
}
SessionRecord record = sessionStore.loadSession(remoteAddress);
return record.getSessionState().getSessionVersion();
}
}
private ChainKey getOrCreateChainKey(SessionState sessionState, ECPublicKey theirEphemeral)
throws InvalidMessageException
{
try {
if (sessionState.hasReceiverChain(theirEphemeral)) {
return sessionState.getReceiverChainKey(theirEphemeral);
} else {
RootKey rootKey = sessionState.getRootKey();
ECKeyPair ourEphemeral = sessionState.getSenderRatchetKeyPair();
Pair<RootKey, ChainKey> receiverChain = rootKey.createChain(theirEphemeral, ourEphemeral);
ECKeyPair ourNewEphemeral = Curve.generateKeyPair();
Pair<RootKey, ChainKey> senderChain = receiverChain.first().createChain(theirEphemeral, ourNewEphemeral);
sessionState.setRootKey(senderChain.first());
sessionState.addReceiverChain(theirEphemeral, receiverChain.second());
sessionState.setPreviousCounter(Math.max(sessionState.getSenderChainKey().getIndex()-1, 0));
sessionState.setSenderChain(ourNewEphemeral, senderChain.second());
return receiverChain.second();
}
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
}
}
private MessageKeys getOrCreateMessageKeys(SessionState sessionState,
ECPublicKey theirEphemeral,
ChainKey chainKey, int counter)
throws InvalidMessageException, DuplicateMessageException
{
if (chainKey.getIndex() > counter) {
if (sessionState.hasMessageKeys(theirEphemeral, counter)) {
return sessionState.removeMessageKeys(theirEphemeral, counter);
} else {
throw new DuplicateMessageException("Received message with old counter: " +
chainKey.getIndex() + " , " + counter);
}
}
if (counter - chainKey.getIndex() > 2000) {
throw new InvalidMessageException("Over 2000 messages into the future!");
}
while (chainKey.getIndex() < counter) {
MessageKeys messageKeys = chainKey.getMessageKeys();
sessionState.setMessageKeys(theirEphemeral, messageKeys);
chainKey = chainKey.getNextChainKey();
}
sessionState.setReceiverChainKey(theirEphemeral, chainKey.getNextChainKey());
return chainKey.getMessageKeys();
}
private byte[] getCiphertext(MessageKeys messageKeys, byte[] plaintext) {
try {
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
return cipher.doFinal(plaintext);
} catch (IllegalBlockSizeException e) {
throw new AssertionError(e);
} catch (BadPaddingException e) {
throw new AssertionError(e);
}
}
private byte[] getPlaintext(MessageKeys messageKeys, byte[] cipherText)
throws InvalidMessageException
{
try {
Cipher cipher = getCipher(Cipher.DECRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
return cipher.doFinal(cipherText);
} catch (IllegalBlockSizeException e) {
throw new InvalidMessageException(e);
} catch (BadPaddingException e) {
throw new InvalidMessageException(e);
}
}
private Cipher getCipher(int mode, SecretKeySpec key, IvParameterSpec iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, key, iv);
return cipher;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (NoSuchPaddingException e) {
throw new AssertionError(e);
} catch (java.security.InvalidKeyException e) {
throw new AssertionError(e);
} catch (InvalidAlgorithmParameterException e) {
throw new AssertionError(e);
}
}
private static class NullDecryptionCallback implements DecryptionCallback {
@Override
public void handlePlaintext(byte[] plaintext) {}
}
}

View File

@@ -0,0 +1,44 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class SignalProtocolAddress {
private final String name;
private final int deviceId;
public SignalProtocolAddress(String name, int deviceId) {
this.name = name;
this.deviceId = deviceId;
}
public String getName() {
return name;
}
public int getDeviceId() {
return deviceId;
}
@Override
public String toString() {
return name + ":" + deviceId;
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof SignalProtocolAddress)) return false;
SignalProtocolAddress that = (SignalProtocolAddress)other;
return this.name.equals(that.name) && this.deviceId == that.deviceId;
}
@Override
public int hashCode() {
return this.name.hashCode() ^ this.deviceId;
}
}

View File

@@ -0,0 +1,9 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class StaleKeyExchangeException extends Throwable {
}

View File

@@ -0,0 +1,25 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal;
public class UntrustedIdentityException extends Exception {
private final String name;
private final IdentityKey key;
public UntrustedIdentityException(String name, IdentityKey key) {
this.name = name;
this.key = key;
}
public IdentityKey getUntrustedIdentity() {
return key;
}
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,54 @@
package org.session.libsignal.libsignal.devices;
import org.session.libsignal.libsignal.util.ByteArrayComparator;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DeviceConsistencyCodeGenerator {
private static final int CODE_VERSION = 0;
public static String generateFor(DeviceConsistencyCommitment commitment,
List<DeviceConsistencySignature> signatures)
{
try {
ArrayList<DeviceConsistencySignature> sortedSignatures = new ArrayList<DeviceConsistencySignature>(signatures);
Collections.sort(sortedSignatures, new SignatureComparator());
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(ByteUtil.shortToByteArray(CODE_VERSION));
messageDigest.update(commitment.toByteArray());
for (DeviceConsistencySignature signature : sortedSignatures) {
messageDigest.update(signature.getVrfOutput());
}
byte[] hash = messageDigest.digest();
String digits = getEncodedChunk(hash, 0) + getEncodedChunk(hash, 5);
return digits.substring(0, 6);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String getEncodedChunk(byte[] hash, int offset) {
long chunk = ByteUtil.byteArray5ToLong(hash, offset) % 100000;
return String.format("%05d", chunk);
}
private static class SignatureComparator extends ByteArrayComparator implements Comparator<DeviceConsistencySignature> {
@Override
public int compare(DeviceConsistencySignature first, DeviceConsistencySignature second) {
return compare(first.getVrfOutput(), second.getVrfOutput());
}
}
}

View File

@@ -0,0 +1,49 @@
package org.session.libsignal.libsignal.devices;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.util.ByteUtil;
import org.session.libsignal.libsignal.util.IdentityKeyComparator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DeviceConsistencyCommitment {
private static final String VERSION = "DeviceConsistencyCommitment_V0";
private final int generation;
private final byte[] serialized;
public DeviceConsistencyCommitment(int generation, List<IdentityKey> identityKeys) {
try {
ArrayList<IdentityKey> sortedIdentityKeys = new ArrayList<IdentityKey>(identityKeys);
Collections.sort(sortedIdentityKeys, new IdentityKeyComparator());
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(VERSION.getBytes());
messageDigest.update(ByteUtil.intToByteArray(generation));
for (IdentityKey commitment : sortedIdentityKeys) {
messageDigest.update(commitment.getPublicKey().serialize());
}
this.generation = generation;
this.serialized = messageDigest.digest();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public byte[] toByteArray() {
return serialized;
}
public int getGeneration() {
return generation;
}
}

View File

@@ -0,0 +1,21 @@
package org.session.libsignal.libsignal.devices;
public class DeviceConsistencySignature {
private final byte[] signature;
private final byte[] vrfOutput;
public DeviceConsistencySignature(byte[] signature, byte[] vrfOutput) {
this.signature = signature;
this.vrfOutput = vrfOutput;
}
public byte[] getVrfOutput() {
return vrfOutput;
}
public byte[] getSignature() {
return signature;
}
}

View File

@@ -0,0 +1,144 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
import org.whispersystems.curve25519.Curve25519;
import org.whispersystems.curve25519.Curve25519KeyPair;
import org.whispersystems.curve25519.VrfSignatureVerificationFailedException;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.DjbECPrivateKey;
import org.session.libsignal.libsignal.ecc.DjbECPublicKey;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import static org.whispersystems.curve25519.Curve25519.BEST;
public class Curve {
public static final int DJB_TYPE = 0x05;
public static boolean isNative() {
return Curve25519.getInstance(BEST).isNative();
}
public static ECKeyPair generateKeyPair() {
Curve25519KeyPair keyPair = Curve25519.getInstance(BEST).generateKeyPair();
return new ECKeyPair(new DjbECPublicKey(keyPair.getPublicKey()), new DjbECPrivateKey(keyPair.getPrivateKey()));
}
public static ECPublicKey decodePoint(byte[] bytes, int offset)
throws InvalidKeyException
{
if (bytes == null || bytes.length - offset < 1) {
throw new InvalidKeyException("No key type identifier");
}
int type = bytes[offset] & 0xFF;
switch (type) {
case Curve.DJB_TYPE:
if (bytes.length - offset < 33) {
throw new InvalidKeyException("Bad key length: " + bytes.length);
}
byte[] keyBytes = new byte[32];
System.arraycopy(bytes, offset+1, keyBytes, 0, keyBytes.length);
return new DjbECPublicKey(keyBytes);
default:
throw new InvalidKeyException("Bad key type: " + type);
}
}
public static ECPrivateKey decodePrivatePoint(byte[] bytes) {
return new DjbECPrivateKey(bytes);
}
public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
throws InvalidKeyException
{
if (publicKey == null) {
throw new InvalidKeyException("public value is null");
}
if (privateKey == null) {
throw new InvalidKeyException("private value is null");
}
if (publicKey.getType() != privateKey.getType()) {
throw new InvalidKeyException("Public and private keys must be of the same type!");
}
if (publicKey.getType() == DJB_TYPE) {
return Curve25519.getInstance(BEST)
.calculateAgreement(((DjbECPublicKey) publicKey).getPublicKey(),
((DjbECPrivateKey) privateKey).getPrivateKey());
} else {
throw new InvalidKeyException("Unknown type: " + publicKey.getType());
}
}
public static boolean verifySignature(ECPublicKey signingKey, byte[] message, byte[] signature)
throws InvalidKeyException
{
if (signingKey == null || message == null || signature == null) {
throw new InvalidKeyException("Values must not be null");
}
if (signingKey.getType() == DJB_TYPE) {
return Curve25519.getInstance(BEST)
.verifySignature(((DjbECPublicKey) signingKey).getPublicKey(), message, signature);
} else {
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
}
}
public static byte[] calculateSignature(ECPrivateKey signingKey, byte[] message)
throws InvalidKeyException
{
if (signingKey == null || message == null) {
throw new InvalidKeyException("Values must not be null");
}
if (signingKey.getType() == DJB_TYPE) {
return Curve25519.getInstance(BEST)
.calculateSignature(((DjbECPrivateKey) signingKey).getPrivateKey(), message);
} else {
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
}
}
public static byte[] calculateVrfSignature(ECPrivateKey signingKey, byte[] message)
throws InvalidKeyException
{
if (signingKey == null || message == null) {
throw new InvalidKeyException("Values must not be null");
}
if (signingKey.getType() == DJB_TYPE) {
return Curve25519.getInstance(BEST)
.calculateVrfSignature(((DjbECPrivateKey)signingKey).getPrivateKey(), message);
} else {
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
}
}
public static byte[] verifyVrfSignature(ECPublicKey signingKey, byte[] message, byte[] signature)
throws InvalidKeyException, VrfSignatureVerificationFailedException
{
if (signingKey == null || message == null || signature == null) {
throw new InvalidKeyException("Values must not be null");
}
if (signingKey.getType() == DJB_TYPE) {
return Curve25519.getInstance(BEST)
.verifyVrfSignature(((DjbECPublicKey) signingKey).getPublicKey(), message, signature);
} else {
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
}
}
}

View File

@@ -0,0 +1,30 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
public class DjbECPrivateKey implements ECPrivateKey {
private final byte[] privateKey;
public DjbECPrivateKey(byte[] privateKey) {
this.privateKey = privateKey;
}
@Override
public byte[] serialize() {
return privateKey;
}
@Override
public int getType() {
return Curve.DJB_TYPE;
}
public byte[] getPrivateKey() {
return privateKey;
}
}

View File

@@ -0,0 +1,55 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.math.BigInteger;
import java.util.Arrays;
public class DjbECPublicKey implements ECPublicKey {
private final byte[] publicKey;
public DjbECPublicKey(byte[] publicKey) {
this.publicKey = publicKey;
}
@Override
public byte[] serialize() {
byte[] type = {Curve.DJB_TYPE};
return ByteUtil.combine(type, publicKey);
}
@Override
public int getType() {
return Curve.DJB_TYPE;
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof DjbECPublicKey)) return false;
DjbECPublicKey that = (DjbECPublicKey)other;
return Arrays.equals(this.publicKey, that.publicKey);
}
@Override
public int hashCode() {
return Arrays.hashCode(publicKey);
}
@Override
public int compareTo(ECPublicKey another) {
return new BigInteger(publicKey).compareTo(new BigInteger(((DjbECPublicKey)another).publicKey));
}
public byte[] getPublicKey() {
return publicKey;
}
}

View File

@@ -0,0 +1,28 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
public class ECKeyPair {
private final ECPublicKey publicKey;
private final ECPrivateKey privateKey;
public ECKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public ECPublicKey getPublicKey() {
return publicKey;
}
public ECPrivateKey getPrivateKey() {
return privateKey;
}
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
public interface ECPrivateKey {
public byte[] serialize();
public int getType();
}

View File

@@ -0,0 +1,16 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ecc;
public interface ECPublicKey extends Comparable<ECPublicKey> {
public static final int KEY_SIZE = 33;
public byte[] serialize();
public int getType();
}

View File

@@ -0,0 +1,43 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
import org.session.libsignal.libsignal.util.ByteUtil;
public class DisplayableFingerprint {
private final String localFingerprintNumbers;
private final String remoteFingerprintNumbers;
DisplayableFingerprint(byte[] localFingerprint, byte[] remoteFingerprint)
{
this.localFingerprintNumbers = getDisplayStringFor(localFingerprint);
this.remoteFingerprintNumbers = getDisplayStringFor(remoteFingerprint);
}
public String getDisplayText() {
if (localFingerprintNumbers.compareTo(remoteFingerprintNumbers) <= 0) {
return localFingerprintNumbers + remoteFingerprintNumbers;
} else {
return remoteFingerprintNumbers + localFingerprintNumbers;
}
}
private String getDisplayStringFor(byte[] fingerprint) {
return getEncodedChunk(fingerprint, 0) +
getEncodedChunk(fingerprint, 5) +
getEncodedChunk(fingerprint, 10) +
getEncodedChunk(fingerprint, 15) +
getEncodedChunk(fingerprint, 20) +
getEncodedChunk(fingerprint, 25);
}
private String getEncodedChunk(byte[] hash, int offset) {
long chunk = ByteUtil.byteArray5ToLong(hash, offset) % 100000;
return String.format("%05d", chunk);
}
}

View File

@@ -0,0 +1,36 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
import org.session.libsignal.libsignal.fingerprint.DisplayableFingerprint;
import org.session.libsignal.libsignal.fingerprint.ScannableFingerprint;
public class Fingerprint {
private final DisplayableFingerprint displayableFingerprint;
private final ScannableFingerprint scannableFingerprint;
public Fingerprint(DisplayableFingerprint displayableFingerprint,
ScannableFingerprint scannableFingerprint)
{
this.displayableFingerprint = displayableFingerprint;
this.scannableFingerprint = scannableFingerprint;
}
/**
* @return A text fingerprint that can be displayed and compared remotely.
*/
public DisplayableFingerprint getDisplayableFingerprint() {
return displayableFingerprint;
}
/**
* @return A scannable fingerprint that can be scanned anc compared locally.
*/
public ScannableFingerprint getScannableFingerprint() {
return scannableFingerprint;
}
}

View File

@@ -0,0 +1,18 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
import org.session.libsignal.libsignal.IdentityKey;
import java.util.List;
public interface FingerprintGenerator {
public Fingerprint createFor(String localStableIdentifier, IdentityKey localIdentityKey,
String remoteStableIdentifier, IdentityKey remoteIdentityKey);
public Fingerprint createFor(String localStableIdentifier, List<IdentityKey> localIdentityKey,
String remoteStableIdentifier, List<IdentityKey> remoteIdentityKey);
}

View File

@@ -0,0 +1,39 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
public class FingerprintIdentifierMismatchException extends Exception {
private final String localIdentifier;
private final String remoteIdentifier;
private final String scannedLocalIdentifier;
private final String scannedRemoteIdentifier;
public FingerprintIdentifierMismatchException(String localIdentifier, String remoteIdentifier,
String scannedLocalIdentifier, String scannedRemoteIdentifier)
{
this.localIdentifier = localIdentifier;
this.remoteIdentifier = remoteIdentifier;
this.scannedLocalIdentifier = scannedLocalIdentifier;
this.scannedRemoteIdentifier = scannedRemoteIdentifier;
}
public String getScannedRemoteIdentifier() {
return scannedRemoteIdentifier;
}
public String getScannedLocalIdentifier() {
return scannedLocalIdentifier;
}
public String getRemoteIdentifier() {
return remoteIdentifier;
}
public String getLocalIdentifier() {
return localIdentifier;
}
}

View File

@@ -0,0 +1,14 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
public class FingerprintParsingException extends Exception {
public FingerprintParsingException(Exception nested) {
super(nested);
}
}

View File

@@ -0,0 +1,26 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
public class FingerprintVersionMismatchException extends Exception {
private final int theirVersion;
private final int ourVersion;
public FingerprintVersionMismatchException(int theirVersion, int ourVersion) {
super();
this.theirVersion = theirVersion;
this.ourVersion = ourVersion;
}
public int getTheirVersion() {
return theirVersion;
}
public int getOurVersion() {
return ourVersion;
}
}

View File

@@ -0,0 +1,127 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.util.ByteUtil;
import org.session.libsignal.libsignal.util.IdentityKeyComparator;
import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class NumericFingerprintGenerator implements FingerprintGenerator {
private static final int FINGERPRINT_VERSION = 0;
private final int iterations;
/**
* Construct a fingerprint generator for 60 digit numerics.
*
* @param iterations The number of internal iterations to perform in the process of
* generating a fingerprint. This needs to be constant, and synchronized
* across all clients.
*
* The higher the iteration count, the higher the security level:
*
* - 1024 ~ 109.7 bits
* - 1400 > 110 bits
* - 5200 > 112 bits
*/
public NumericFingerprintGenerator(int iterations) {
this.iterations = iterations;
}
/**
* Generate a scannable and displayble fingerprint.
*
* @param localStableIdentifier The client's "stable" identifier.
* @param localIdentityKey The client's identity key.
* @param remoteStableIdentifier The remote party's "stable" identifier.
* @param remoteIdentityKey The remote party's identity key.
* @return A unique fingerprint for this conversation.
*/
@Override
public Fingerprint createFor(String localStableIdentifier, final IdentityKey localIdentityKey,
String remoteStableIdentifier, final IdentityKey remoteIdentityKey)
{
return createFor(localStableIdentifier,
new LinkedList<IdentityKey>() {{
add(localIdentityKey);
}},
remoteStableIdentifier,
new LinkedList<IdentityKey>() {{
add(remoteIdentityKey);
}});
}
/**
* Generate a scannable and displayble fingerprint for logical identities that have multiple
* physical keys.
*
* Do not trust the output of this unless you've been through the device consistency process
* for the provided localIdentityKeys.
*
* @param localStableIdentifier The client's "stable" identifier.
* @param localIdentityKeys The client's collection of physical identity keys.
* @param remoteStableIdentifier The remote party's "stable" identifier.
* @param remoteIdentityKeys The remote party's collection of physical identity key.
* @return A unique fingerprint for this conversation.
*/
public Fingerprint createFor(String localStableIdentifier, List<IdentityKey> localIdentityKeys,
String remoteStableIdentifier, List<IdentityKey> remoteIdentityKeys)
{
byte[] localFingerprint = getFingerprint(iterations, localStableIdentifier, localIdentityKeys);
byte[] remoteFingerprint = getFingerprint(iterations, remoteStableIdentifier, remoteIdentityKeys);
DisplayableFingerprint displayableFingerprint = new DisplayableFingerprint(localFingerprint,
remoteFingerprint);
ScannableFingerprint scannableFingerprint = new ScannableFingerprint(localFingerprint,
remoteFingerprint);
return new Fingerprint(displayableFingerprint, scannableFingerprint);
}
private byte[] getFingerprint(int iterations, String stableIdentifier, List<IdentityKey> unsortedIdentityKeys) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-512");
byte[] publicKey = getLogicalKeyBytes(unsortedIdentityKeys);
byte[] hash = ByteUtil.combine(ByteUtil.shortToByteArray(FINGERPRINT_VERSION),
publicKey, stableIdentifier.getBytes());
for (int i=0;i<iterations;i++) {
digest.update(hash);
hash = digest.digest(publicKey);
}
return hash;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private byte[] getLogicalKeyBytes(List<IdentityKey> identityKeys) {
ArrayList<IdentityKey> sortedIdentityKeys = new ArrayList<IdentityKey>(identityKeys);
Collections.sort(sortedIdentityKeys, new IdentityKeyComparator());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (IdentityKey identityKey : sortedIdentityKeys) {
byte[] publicKeyBytes = identityKey.getPublicKey().serialize();
baos.write(publicKeyBytes, 0, publicKeyBytes.length);
}
return baos.toByteArray();
}
}

View File

@@ -0,0 +1,75 @@
/**
* Copyright (C) 2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.fingerprint;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.fingerprint.FingerprintParsingException;
import org.session.libsignal.libsignal.fingerprint.FingerprintProtos.CombinedFingerprints;
import org.session.libsignal.libsignal.fingerprint.FingerprintProtos.LogicalFingerprint;
import org.session.libsignal.libsignal.fingerprint.FingerprintVersionMismatchException;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.security.MessageDigest;
public class ScannableFingerprint {
private static final int VERSION = 1;
private final CombinedFingerprints fingerprints;
ScannableFingerprint(byte[] localFingerprintData, byte[] remoteFingerprintData)
{
LogicalFingerprint localFingerprint = LogicalFingerprint.newBuilder()
.setContent(ByteString.copyFrom(ByteUtil.trim(localFingerprintData, 32)))
.build();
LogicalFingerprint remoteFingerprint = LogicalFingerprint.newBuilder()
.setContent(ByteString.copyFrom(ByteUtil.trim(remoteFingerprintData, 32)))
.build();
this.fingerprints = CombinedFingerprints.newBuilder()
.setVersion(VERSION)
.setLocalFingerprint(localFingerprint)
.setRemoteFingerprint(remoteFingerprint)
.build();
}
/**
* @return A byte string to be displayed in a QR code.
*/
public byte[] getSerialized() {
return fingerprints.toByteArray();
}
/**
* Compare a scanned QR code with what we expect.
*
* @param scannedFingerprintData The scanned data
* @return True if matching, otehrwise false.
* @throws FingerprintVersionMismatchException if the scanned fingerprint is the wrong version.
*/
public boolean compareTo(byte[] scannedFingerprintData)
throws FingerprintVersionMismatchException,
FingerprintParsingException
{
try {
CombinedFingerprints scanned = CombinedFingerprints.parseFrom(scannedFingerprintData);
if (!scanned.hasRemoteFingerprint() || !scanned.hasLocalFingerprint() ||
!scanned.hasVersion() || scanned.getVersion() != VERSION)
{
throw new FingerprintVersionMismatchException(scanned.getVersion(), VERSION);
}
return MessageDigest.isEqual(fingerprints.getLocalFingerprint().getContent().toByteArray(), scanned.getRemoteFingerprint().getContent().toByteArray()) &&
MessageDigest.isEqual(fingerprints.getRemoteFingerprint().getContent().toByteArray(), scanned.getLocalFingerprint().getContent().toByteArray());
} catch (InvalidProtocolBufferException e) {
throw new FingerprintParsingException(e);
}
}
}

View File

@@ -0,0 +1,229 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups;
import org.session.libsignal.libsignal.DecryptionCallback;
import org.session.libsignal.libsignal.DuplicateMessageException;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.LegacyMessageException;
import org.session.libsignal.libsignal.NoSessionException;
import org.session.libsignal.libsignal.groups.SenderKeyName;
import org.session.libsignal.libsignal.groups.ratchet.SenderChainKey;
import org.session.libsignal.libsignal.groups.ratchet.SenderMessageKey;
import org.session.libsignal.libsignal.groups.state.SenderKeyRecord;
import org.session.libsignal.libsignal.groups.state.SenderKeyState;
import org.session.libsignal.libsignal.groups.state.SenderKeyStore;
import org.session.libsignal.libsignal.protocol.SenderKeyMessage;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* The main entry point for Signal Protocol group encrypt/decrypt operations.
*
* Once a session has been established with {@link org.session.libsignal.libsignal.groups.GroupSessionBuilder}
* and a {@link org.session.libsignal.libsignal.protocol.SenderKeyDistributionMessage} has been
* distributed to each member of the group, this class can be used for all subsequent encrypt/decrypt
* operations within that session (ie: until group membership changes).
*
* @author Moxie Marlinspike
*/
public class GroupCipher {
static final Object LOCK = new Object();
private final SenderKeyStore senderKeyStore;
private final SenderKeyName senderKeyId;
public GroupCipher(SenderKeyStore senderKeyStore, SenderKeyName senderKeyId) {
this.senderKeyStore = senderKeyStore;
this.senderKeyId = senderKeyId;
}
/**
* Encrypt a message.
*
* @param paddedPlaintext The plaintext message bytes, optionally padded.
* @return Ciphertext.
* @throws NoSessionException
*/
public byte[] encrypt(byte[] paddedPlaintext) throws NoSessionException {
synchronized (LOCK) {
try {
SenderKeyRecord record = senderKeyStore.loadSenderKey(senderKeyId);
SenderKeyState senderKeyState = record.getSenderKeyState();
SenderMessageKey senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey();
byte[] ciphertext = getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext);
SenderKeyMessage senderKeyMessage = new SenderKeyMessage(senderKeyState.getKeyId(),
senderKey.getIteration(),
ciphertext,
senderKeyState.getSigningKeyPrivate());
senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext());
senderKeyStore.storeSenderKey(senderKeyId, record);
return senderKeyMessage.serialize();
} catch (InvalidKeyIdException e) {
throw new NoSessionException(e);
}
}
}
/**
* Decrypt a SenderKey group message.
*
* @param senderKeyMessageBytes The received ciphertext.
* @return Plaintext
* @throws LegacyMessageException
* @throws InvalidMessageException
* @throws DuplicateMessageException
*/
public byte[] decrypt(byte[] senderKeyMessageBytes)
throws LegacyMessageException, DuplicateMessageException, InvalidMessageException, NoSessionException
{
return decrypt(senderKeyMessageBytes, new NullDecryptionCallback());
}
/**
* Decrypt a SenderKey group message.
*
* @param senderKeyMessageBytes The received ciphertext.
* @param callback A callback that is triggered after decryption is complete,
* but before the updated session state has been committed to the session
* DB. This allows some implementations to store the committed plaintext
* to a DB first, in case they are concerned with a crash happening between
* the time the session state is updated but before they're able to store
* the plaintext to disk.
* @return Plaintext
* @throws LegacyMessageException
* @throws InvalidMessageException
* @throws DuplicateMessageException
*/
public byte[] decrypt(byte[] senderKeyMessageBytes, DecryptionCallback callback)
throws LegacyMessageException, InvalidMessageException, DuplicateMessageException,
NoSessionException
{
synchronized (LOCK) {
try {
SenderKeyRecord record = senderKeyStore.loadSenderKey(senderKeyId);
if (record.isEmpty()) {
throw new NoSessionException("No sender key for: " + senderKeyId);
}
SenderKeyMessage senderKeyMessage = new SenderKeyMessage(senderKeyMessageBytes);
SenderKeyState senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId());
senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic());
SenderMessageKey senderKey = getSenderKey(senderKeyState, senderKeyMessage.getIteration());
byte[] plaintext = getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText());
callback.handlePlaintext(plaintext);
senderKeyStore.storeSenderKey(senderKeyId, record);
return plaintext;
} catch (org.session.libsignal.libsignal.InvalidKeyException e) {
throw new InvalidMessageException(e);
} catch (InvalidKeyIdException e) {
throw new InvalidMessageException(e);
}
}
}
private SenderMessageKey getSenderKey(SenderKeyState senderKeyState, int iteration)
throws DuplicateMessageException, InvalidMessageException
{
SenderChainKey senderChainKey = senderKeyState.getSenderChainKey();
if (senderChainKey.getIteration() > iteration) {
if (senderKeyState.hasSenderMessageKey(iteration)) {
return senderKeyState.removeSenderMessageKey(iteration);
} else {
throw new DuplicateMessageException("Received message with old counter: " +
senderChainKey.getIteration() + " , " + iteration);
}
}
if (iteration - senderChainKey.getIteration() > 2000) {
throw new InvalidMessageException("Over 2000 messages into the future!");
}
while (senderChainKey.getIteration() < iteration) {
senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey());
senderChainKey = senderChainKey.getNext();
}
senderKeyState.setSenderChainKey(senderChainKey.getNext());
return senderChainKey.getSenderMessageKey();
}
private byte[] getPlainText(byte[] iv, byte[] key, byte[] ciphertext)
throws InvalidMessageException
{
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), ivParameterSpec);
return cipher.doFinal(ciphertext);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (NoSuchPaddingException e) {
throw new AssertionError(e);
} catch(java.security.InvalidKeyException e) {
throw new AssertionError(e);
} catch (InvalidAlgorithmParameterException e) {
throw new AssertionError(e);
} catch (IllegalBlockSizeException e) {
throw new InvalidMessageException(e);
} catch (BadPaddingException e) {
throw new InvalidMessageException(e);
}
}
private byte[] getCipherText(byte[] iv, byte[] key, byte[] plaintext) {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), ivParameterSpec);
return cipher.doFinal(plaintext);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (NoSuchPaddingException e) {
throw new AssertionError(e);
} catch (InvalidAlgorithmParameterException e) {
throw new AssertionError(e);
} catch (IllegalBlockSizeException e) {
throw new AssertionError(e);
} catch (BadPaddingException e) {
throw new AssertionError(e);
} catch (java.security.InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static class NullDecryptionCallback implements DecryptionCallback {
@Override
public void handlePlaintext(byte[] plaintext) {}
}
}

View File

@@ -0,0 +1,90 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.groups.state.SenderKeyRecord;
import org.session.libsignal.libsignal.groups.state.SenderKeyState;
import org.session.libsignal.libsignal.groups.state.SenderKeyStore;
import org.session.libsignal.libsignal.protocol.SenderKeyDistributionMessage;
import org.session.libsignal.libsignal.util.KeyHelper;
/**
* GroupSessionBuilder is responsible for setting up group SenderKey encrypted sessions.
*
* Once a session has been established, {@link org.session.libsignal.libsignal.groups.GroupCipher}
* can be used to encrypt/decrypt messages in that session.
* <p>
* The built sessions are unidirectional: they can be used either for sending or for receiving,
* but not both.
*
* Sessions are constructed per (groupId + senderId + deviceId) tuple. Remote logical users
* are identified by their senderId, and each logical recipientId can have multiple physical
* devices.
*
* @author Moxie Marlinspike
*/
public class GroupSessionBuilder {
private final SenderKeyStore senderKeyStore;
public GroupSessionBuilder(SenderKeyStore senderKeyStore) {
this.senderKeyStore = senderKeyStore;
}
/**
* Construct a group session for receiving messages from senderKeyName.
*
* @param senderKeyName The (groupId, senderId, deviceId) tuple associated with the SenderKeyDistributionMessage.
* @param senderKeyDistributionMessage A received SenderKeyDistributionMessage.
*/
public void process(SenderKeyName senderKeyName, SenderKeyDistributionMessage senderKeyDistributionMessage) {
synchronized (GroupCipher.LOCK) {
SenderKeyRecord senderKeyRecord = senderKeyStore.loadSenderKey(senderKeyName);
senderKeyRecord.addSenderKeyState(senderKeyDistributionMessage.getId(),
senderKeyDistributionMessage.getIteration(),
senderKeyDistributionMessage.getChainKey(),
senderKeyDistributionMessage.getSignatureKey());
senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
}
}
/**
* Construct a group session for sending messages.
*
* @param senderKeyName The (groupId, senderId, deviceId) tuple. In this case, 'senderId' should be the caller.
* @return A SenderKeyDistributionMessage that is individually distributed to each member of the group.
*/
public SenderKeyDistributionMessage create(SenderKeyName senderKeyName) {
synchronized (GroupCipher.LOCK) {
try {
SenderKeyRecord senderKeyRecord = senderKeyStore.loadSenderKey(senderKeyName);
if (senderKeyRecord.isEmpty()) {
senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(),
0,
KeyHelper.generateSenderKey(),
KeyHelper.generateSenderSigningKey());
senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
}
SenderKeyState state = senderKeyRecord.getSenderKeyState();
return new SenderKeyDistributionMessage(state.getKeyId(),
state.getSenderChainKey().getIteration(),
state.getSenderChainKey().getSeed(),
state.getSigningKeyPublic());
} catch (InvalidKeyIdException e) {
throw new AssertionError(e);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
}
}

View File

@@ -0,0 +1,52 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups;
import org.session.libsignal.libsignal.SignalProtocolAddress;
/**
* A representation of a (groupId + senderId + deviceId) tuple.
*/
public class SenderKeyName {
private final String groupId;
private final SignalProtocolAddress sender;
public SenderKeyName(String groupId, SignalProtocolAddress sender) {
this.groupId = groupId;
this.sender = sender;
}
public String getGroupId() {
return groupId;
}
public SignalProtocolAddress getSender() {
return sender;
}
public String serialize() {
return groupId + "::" + sender.getName() + "::" + String.valueOf(sender.getDeviceId());
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof SenderKeyName)) return false;
SenderKeyName that = (SenderKeyName)other;
return
this.groupId.equals(that.groupId) &&
this.sender.equals(that.sender);
}
@Override
public int hashCode() {
return this.groupId.hashCode() ^ this.sender.hashCode();
}
}

View File

@@ -0,0 +1,68 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups.ratchet;
import org.session.libsignal.libsignal.groups.ratchet.SenderMessageKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Each SenderKey is a "chain" of keys, each derived from the previous.
*
* At any given point in time, the state of a SenderKey can be represented
* as the current chain key value, along with its iteration count. From there,
* subsequent iterations can be derived, as well as individual message keys from
* each chain key.
*
* @author Moxie Marlinspike
*/
public class SenderChainKey {
private static final byte[] MESSAGE_KEY_SEED = {0x01};
private static final byte[] CHAIN_KEY_SEED = {0x02};
private final int iteration;
private final byte[] chainKey;
public SenderChainKey(int iteration, byte[] chainKey) {
this.iteration = iteration;
this.chainKey = chainKey;
}
public int getIteration() {
return iteration;
}
public SenderMessageKey getSenderMessageKey() {
return new SenderMessageKey(iteration, getDerivative(MESSAGE_KEY_SEED, chainKey));
}
public SenderChainKey getNext() {
return new SenderChainKey(iteration + 1, getDerivative(CHAIN_KEY_SEED, chainKey));
}
public byte[] getSeed() {
return chainKey;
}
private byte[] getDerivative(byte[] seed, byte[] key) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(seed);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
}

View File

@@ -0,0 +1,50 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups.ratchet;
import org.session.libsignal.libsignal.kdf.HKDFv3;
import org.session.libsignal.libsignal.util.ByteUtil;
/**
* The final symmetric material (IV and Cipher Key) used for encrypting
* individual SenderKey messages.
*
* @author Moxie Marlinspike
*/
public class SenderMessageKey {
private final int iteration;
private final byte[] iv;
private final byte[] cipherKey;
private final byte[] seed;
public SenderMessageKey(int iteration, byte[] seed) {
byte[] derivative = new HKDFv3().deriveSecrets(seed, "WhisperGroup".getBytes(), 48);
byte[][] parts = ByteUtil.split(derivative, 16, 32);
this.iteration = iteration;
this.seed = seed;
this.iv = parts[0];
this.cipherKey = parts[1];
}
public int getIteration() {
return iteration;
}
public byte[] getIv() {
return iv;
}
public byte[] getCipherKey() {
return cipherKey;
}
public byte[] getSeed() {
return seed;
}
}

View File

@@ -0,0 +1,85 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups.state;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.state.StorageProtos;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import static org.session.libsignal.libsignal.state.StorageProtos.SenderKeyRecordStructure;
/**
* A durable representation of a set of SenderKeyStates for a specific
* SenderKeyName.
*
* @author Moxie Marlisnpike
*/
public class SenderKeyRecord {
private static final int MAX_STATES = 5;
private LinkedList<SenderKeyState> senderKeyStates = new LinkedList<SenderKeyState>();
public SenderKeyRecord() {}
public SenderKeyRecord(byte[] serialized) throws IOException {
SenderKeyRecordStructure senderKeyRecordStructure = SenderKeyRecordStructure.parseFrom(serialized);
for (StorageProtos.SenderKeyStateStructure structure : senderKeyRecordStructure.getSenderKeyStatesList()) {
this.senderKeyStates.add(new SenderKeyState(structure));
}
}
public boolean isEmpty() {
return senderKeyStates.isEmpty();
}
public SenderKeyState getSenderKeyState() throws InvalidKeyIdException {
if (!senderKeyStates.isEmpty()) {
return senderKeyStates.get(0);
} else {
throw new InvalidKeyIdException("No key state in record!");
}
}
public SenderKeyState getSenderKeyState(int keyId) throws InvalidKeyIdException {
for (SenderKeyState state : senderKeyStates) {
if (state.getKeyId() == keyId) {
return state;
}
}
throw new InvalidKeyIdException("No keys for: " + keyId);
}
public void addSenderKeyState(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
senderKeyStates.addFirst(new SenderKeyState(id, iteration, chainKey, signatureKey));
if (senderKeyStates.size() > MAX_STATES) {
senderKeyStates.removeLast();
}
}
public void setSenderKeyState(int id, int iteration, byte[] chainKey, ECKeyPair signatureKey) {
senderKeyStates.clear();
senderKeyStates.add(new SenderKeyState(id, iteration, chainKey, signatureKey));
}
public byte[] serialize() {
SenderKeyRecordStructure.Builder recordStructure = SenderKeyRecordStructure.newBuilder();
for (SenderKeyState senderKeyState : senderKeyStates) {
recordStructure.addSenderKeyStates(senderKeyState.getStructure());
}
return recordStructure.build().toByteArray();
}
}

View File

@@ -0,0 +1,162 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups.state;
import com.google.protobuf.ByteString;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.groups.ratchet.SenderChainKey;
import org.session.libsignal.libsignal.groups.ratchet.SenderMessageKey;
import org.session.libsignal.libsignal.util.guava.Optional;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static org.session.libsignal.libsignal.state.StorageProtos.SenderKeyStateStructure;
/**
* Represents the state of an individual SenderKey ratchet.
*
* @author Moxie Marlinspike
*/
public class SenderKeyState {
private static final int MAX_MESSAGE_KEYS = 2000;
private SenderKeyStateStructure senderKeyStateStructure;
public SenderKeyState(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
this(id, iteration, chainKey, signatureKey, Optional.<ECPrivateKey>absent());
}
public SenderKeyState(int id, int iteration, byte[] chainKey, ECKeyPair signatureKey) {
this(id, iteration, chainKey, signatureKey.getPublicKey(), Optional.of(signatureKey.getPrivateKey()));
}
private SenderKeyState(int id, int iteration, byte[] chainKey,
ECPublicKey signatureKeyPublic,
Optional<ECPrivateKey> signatureKeyPrivate)
{
SenderKeyStateStructure.SenderChainKey senderChainKeyStructure =
SenderKeyStateStructure.SenderChainKey.newBuilder()
.setIteration(iteration)
.setSeed(ByteString.copyFrom(chainKey))
.build();
SenderKeyStateStructure.SenderSigningKey.Builder signingKeyStructure =
SenderKeyStateStructure.SenderSigningKey.newBuilder()
.setPublic(ByteString.copyFrom(signatureKeyPublic.serialize()));
if (signatureKeyPrivate.isPresent()) {
signingKeyStructure.setPrivate(ByteString.copyFrom(signatureKeyPrivate.get().serialize()));
}
this.senderKeyStateStructure = SenderKeyStateStructure.newBuilder()
.setSenderKeyId(id)
.setSenderChainKey(senderChainKeyStructure)
.setSenderSigningKey(signingKeyStructure)
.build();
}
public SenderKeyState(SenderKeyStateStructure senderKeyStateStructure) {
this.senderKeyStateStructure = senderKeyStateStructure;
}
public int getKeyId() {
return senderKeyStateStructure.getSenderKeyId();
}
public SenderChainKey getSenderChainKey() {
return new SenderChainKey(senderKeyStateStructure.getSenderChainKey().getIteration(),
senderKeyStateStructure.getSenderChainKey().getSeed().toByteArray());
}
public void setSenderChainKey(SenderChainKey chainKey) {
SenderKeyStateStructure.SenderChainKey senderChainKeyStructure =
SenderKeyStateStructure.SenderChainKey.newBuilder()
.setIteration(chainKey.getIteration())
.setSeed(ByteString.copyFrom(chainKey.getSeed()))
.build();
this.senderKeyStateStructure = senderKeyStateStructure.toBuilder()
.setSenderChainKey(senderChainKeyStructure)
.build();
}
public ECPublicKey getSigningKeyPublic() throws InvalidKeyException {
return Curve.decodePoint(senderKeyStateStructure.getSenderSigningKey()
.getPublic()
.toByteArray(), 0);
}
public ECPrivateKey getSigningKeyPrivate() {
return Curve.decodePrivatePoint(senderKeyStateStructure.getSenderSigningKey()
.getPrivate().toByteArray());
}
public boolean hasSenderMessageKey(int iteration) {
for (SenderKeyStateStructure.SenderMessageKey senderMessageKey : senderKeyStateStructure.getSenderMessageKeysList()) {
if (senderMessageKey.getIteration() == iteration) return true;
}
return false;
}
public void addSenderMessageKey(SenderMessageKey senderMessageKey) {
SenderKeyStateStructure.SenderMessageKey senderMessageKeyStructure =
SenderKeyStateStructure.SenderMessageKey.newBuilder()
.setIteration(senderMessageKey.getIteration())
.setSeed(ByteString.copyFrom(senderMessageKey.getSeed()))
.build();
SenderKeyStateStructure.Builder builder = this.senderKeyStateStructure.toBuilder();
builder.addSenderMessageKeys(senderMessageKeyStructure);
if (builder.getSenderMessageKeysCount() > MAX_MESSAGE_KEYS) {
builder.removeSenderMessageKeys(0);
}
this.senderKeyStateStructure = builder.build();
}
public SenderMessageKey removeSenderMessageKey(int iteration) {
List<SenderKeyStateStructure.SenderMessageKey> keys = new LinkedList<SenderKeyStateStructure.SenderMessageKey>(senderKeyStateStructure.getSenderMessageKeysList());
Iterator<SenderKeyStateStructure.SenderMessageKey> iterator = keys.iterator();
SenderKeyStateStructure.SenderMessageKey result = null;
while (iterator.hasNext()) {
SenderKeyStateStructure.SenderMessageKey senderMessageKey = iterator.next();
if (senderMessageKey.getIteration() == iteration) {
result = senderMessageKey;
iterator.remove();
break;
}
}
this.senderKeyStateStructure = this.senderKeyStateStructure.toBuilder()
.clearSenderMessageKeys()
.addAllSenderMessageKeys(keys)
.build();
if (result != null) {
return new SenderMessageKey(result.getIteration(), result.getSeed().toByteArray());
} else {
return null;
}
}
public SenderKeyStateStructure getStructure() {
return senderKeyStateStructure;
}
}

View File

@@ -0,0 +1,38 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.groups.state;
import org.session.libsignal.libsignal.groups.SenderKeyName;
import org.session.libsignal.libsignal.groups.state.SenderKeyRecord;
public interface SenderKeyStore {
/**
* Commit to storage the {@link org.session.libsignal.libsignal.groups.state.SenderKeyRecord} for a
* given (groupId + senderId + deviceId) tuple.
*
* @param senderKeyName the (groupId + senderId + deviceId) tuple.
* @param record the current SenderKeyRecord for the specified senderKeyName.
*/
public void storeSenderKey(SenderKeyName senderKeyName, SenderKeyRecord record);
/**
* Returns a copy of the {@link SenderKeyRecord}
* corresponding to the (groupId + senderId + deviceId) tuple, or a new SenderKeyRecord if
* one does not currently exist.
* <p>
* It is important that implementations return a copy of the current durable information. The
* returned SenderKeyRecord may be modified, but those changes should not have an effect on the
* durable session state (what is returned by subsequent calls to this method) without the
* store method being called here first.
*
* @param senderKeyName The (groupId + senderId + deviceId) tuple.
* @return a copy of the SenderKeyRecord corresponding to the (groupId + senderId + deviceId tuple, or
* a new SenderKeyRecord if one does not currently exist.
*/
public SenderKeyRecord loadSenderKey(SenderKeyName senderKeyName);
}

View File

@@ -0,0 +1,50 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.kdf;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.text.ParseException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DerivedMessageSecrets {
public static final int SIZE = 80;
private static final int CIPHER_KEY_LENGTH = 32;
private static final int MAC_KEY_LENGTH = 32;
private static final int IV_LENGTH = 16;
private final SecretKeySpec cipherKey;
private final SecretKeySpec macKey;
private final IvParameterSpec iv;
public DerivedMessageSecrets(byte[] okm) {
try {
byte[][] keys = ByteUtil.split(okm, CIPHER_KEY_LENGTH, MAC_KEY_LENGTH, IV_LENGTH);
this.cipherKey = new SecretKeySpec(keys[0], "AES");
this.macKey = new SecretKeySpec(keys[1], "HmacSHA256");
this.iv = new IvParameterSpec(keys[2]);
} catch (ParseException e) {
throw new AssertionError(e);
}
}
public SecretKeySpec getCipherKey() {
return cipherKey;
}
public SecretKeySpec getMacKey() {
return macKey;
}
public IvParameterSpec getIv() {
return iv;
}
}

View File

@@ -0,0 +1,31 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.kdf;
import org.session.libsignal.libsignal.util.ByteUtil;
public class DerivedRootSecrets {
public static final int SIZE = 64;
private final byte[] rootKey;
private final byte[] chainKey;
public DerivedRootSecrets(byte[] okm) {
byte[][] keys = ByteUtil.split(okm, 32, 32);
this.rootKey = keys[0];
this.chainKey = keys[1];
}
public byte[] getRootKey() {
return rootKey;
}
public byte[] getChainKey() {
return chainKey;
}
}

View File

@@ -0,0 +1,89 @@
/**
* Copyright (C) 2013-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.kdf;
import org.session.libsignal.libsignal.kdf.HKDFv2;
import org.session.libsignal.libsignal.kdf.HKDFv3;
import java.io.ByteArrayOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public abstract class HKDF {
private static final int HASH_OUTPUT_SIZE = 32;
public static HKDF createFor(int messageVersion) {
switch (messageVersion) {
case 2: return new HKDFv2();
case 3: return new HKDFv3();
default: throw new AssertionError("Unknown version: " + messageVersion);
}
}
public byte[] deriveSecrets(byte[] inputKeyMaterial, byte[] info, int outputLength) {
byte[] salt = new byte[HASH_OUTPUT_SIZE];
return deriveSecrets(inputKeyMaterial, salt, info, outputLength);
}
public byte[] deriveSecrets(byte[] inputKeyMaterial, byte[] salt, byte[] info, int outputLength) {
byte[] prk = extract(salt, inputKeyMaterial);
return expand(prk, info, outputLength);
}
private byte[] extract(byte[] salt, byte[] inputKeyMaterial) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(salt, "HmacSHA256"));
return mac.doFinal(inputKeyMaterial);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
private byte[] expand(byte[] prk, byte[] info, int outputSize) {
try {
int iterations = (int) Math.ceil((double) outputSize / (double) HASH_OUTPUT_SIZE);
byte[] mixin = new byte[0];
ByteArrayOutputStream results = new ByteArrayOutputStream();
int remainingBytes = outputSize;
for (int i= getIterationStartOffset();i<iterations + getIterationStartOffset();i++) {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(prk, "HmacSHA256"));
mac.update(mixin);
if (info != null) {
mac.update(info);
}
mac.update((byte)i);
byte[] stepResult = mac.doFinal();
int stepSize = Math.min(remainingBytes, stepResult.length);
results.write(stepResult, 0, stepSize);
mixin = stepResult;
remainingBytes -= stepSize;
}
return results.toByteArray();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
protected abstract int getIterationStartOffset();
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.kdf;
public class HKDFv2 extends HKDF {
@Override
protected int getIterationStartOffset() {
return 0;
}
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.kdf;
public class HKDFv3 extends HKDF {
@Override
protected int getIterationStartOffset() {
return 1;
}
}

View File

@@ -0,0 +1,94 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.logging;
import org.session.libsignal.libsignal.logging.SignalProtocolLogger;
import org.session.libsignal.libsignal.logging.SignalProtocolLoggerProvider;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
public class Log {
private Log() {}
public static void v(String tag, String msg) {
log(SignalProtocolLogger.VERBOSE, tag, msg);
}
public static void v(String tag, String msg, Throwable tr) {
log(SignalProtocolLogger.VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
}
public static void d(String tag, String msg) {
log(SignalProtocolLogger.DEBUG, tag, msg);
}
public static void d(String tag, String msg, Throwable tr) {
log(SignalProtocolLogger.DEBUG, tag, msg + '\n' + getStackTraceString(tr));
}
public static void i(String tag, String msg) {
log(SignalProtocolLogger.INFO, tag, msg);
}
public static void i(String tag, String msg, Throwable tr) {
log(SignalProtocolLogger.INFO, tag, msg + '\n' + getStackTraceString(tr));
}
public static void w(String tag, String msg) {
log(SignalProtocolLogger.WARN, tag, msg);
}
public static void w(String tag, String msg, Throwable tr) {
log(SignalProtocolLogger.WARN, tag, msg + '\n' + getStackTraceString(tr));
}
public static void w(String tag, Throwable tr) {
log(SignalProtocolLogger.WARN, tag, getStackTraceString(tr));
}
public static void e(String tag, String msg) {
log(SignalProtocolLogger.ERROR, tag, msg);
}
public static void e(String tag, String msg, Throwable tr) {
log(SignalProtocolLogger.ERROR, tag, msg + '\n' + getStackTraceString(tr));
}
private static String getStackTraceString(Throwable tr) {
if (tr == null) {
return "";
}
// This is to reduce the amount of log spew that apps do in the non-error
// condition of the network being unavailable.
Throwable t = tr;
while (t != null) {
if (t instanceof UnknownHostException) {
return "";
}
t = t.getCause();
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
tr.printStackTrace(pw);
pw.flush();
return sw.toString();
}
private static void log(int priority, String tag, String msg) {
SignalProtocolLogger logger = SignalProtocolLoggerProvider.getProvider();
if (logger != null) {
logger.log(priority, tag, msg);
}
}
}

View File

@@ -0,0 +1,18 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.logging;
public interface SignalProtocolLogger {
public static final int VERBOSE = 2;
public static final int DEBUG = 3;
public static final int INFO = 4;
public static final int WARN = 5;
public static final int ERROR = 6;
public static final int ASSERT = 7;
public void log(int priority, String tag, String message);
}

View File

@@ -0,0 +1,19 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.logging;
public class SignalProtocolLoggerProvider {
private static SignalProtocolLogger provider;
public static SignalProtocolLogger getProvider() {
return provider;
}
public static void setProvider(SignalProtocolLogger provider) {
SignalProtocolLoggerProvider.provider = provider;
}
}

View File

@@ -0,0 +1,39 @@
package org.session.libsignal.libsignal.loki
import com.google.protobuf.ByteString
import org.session.libsignal.libsignal.logging.Log
import org.session.libsignal.libsignal.protocol.CiphertextMessage
import org.session.libsignal.libsignal.protocol.SignalProtos
class ClosedGroupCiphertextMessage(val ivAndCiphertext: ByteArray, val senderPublicKey: ByteArray, val keyIndex: Int) : CiphertextMessage {
private val serialized: ByteArray
companion object {
fun from(serialized: ByteArray): ClosedGroupCiphertextMessage? {
try {
val proto = SignalProtos.ClosedGroupCiphertextMessage.parseFrom(serialized)
return ClosedGroupCiphertextMessage(proto.ciphertext.toByteArray(), proto.senderPublicKey.toByteArray(), proto.keyIndex)
} catch (exception: Exception) {
Log.d("Loki", "Couldn't parse proto due to error: $exception.")
return null
}
}
}
init {
val builder = SignalProtos.ClosedGroupCiphertextMessage.newBuilder()
builder.ciphertext = ByteString.copyFrom(ivAndCiphertext)
builder.senderPublicKey = ByteString.copyFrom(senderPublicKey)
builder.keyIndex = keyIndex
serialized = builder.build().toByteArray()
}
override fun getType(): Int {
return CiphertextMessage.CLOSED_GROUP_CIPHERTEXT
}
override fun serialize(): ByteArray {
return serialized
}
}

View File

@@ -0,0 +1,45 @@
package org.session.libsignal.libsignal.loki
import org.whispersystems.curve25519.Curve25519
import org.session.libsignal.service.internal.util.Util
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object DiffieHellman {
private val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
private val curve = Curve25519.getInstance(Curve25519.BEST)
private val ivSize = 16
@JvmStatic @Throws
fun encrypt(plaintext: ByteArray, symmetricKey: ByteArray): ByteArray {
val iv = Util.getSecretBytes(ivSize)
val ivSpec = IvParameterSpec(iv)
val secretKeySpec = SecretKeySpec(symmetricKey, "AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec)
val ciphertext = cipher.doFinal(plaintext)
return iv + ciphertext
}
@JvmStatic @Throws
fun encrypt(plaintext: ByteArray, publicKey: ByteArray, privateKey: ByteArray): ByteArray {
val symmetricKey = curve.calculateAgreement(publicKey, privateKey)
return encrypt(plaintext, symmetricKey)
}
@JvmStatic @Throws
fun decrypt(ivAndCiphertext: ByteArray, symmetricKey: ByteArray): ByteArray {
val iv = ivAndCiphertext.sliceArray(0 until ivSize)
val ciphertext = ivAndCiphertext.sliceArray(ivSize until ivAndCiphertext.size)
val ivSpec = IvParameterSpec(iv)
val secretKeySpec = SecretKeySpec(symmetricKey, "AES")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec)
return cipher.doFinal(ciphertext)
}
@JvmStatic @Throws
fun decrypt(ivAndCiphertext: ByteArray, publicKey: ByteArray, privateKey: ByteArray): ByteArray {
val symmetricKey = curve.calculateAgreement(publicKey, privateKey)
return decrypt(ivAndCiphertext, symmetricKey)
}
}

View File

@@ -0,0 +1,14 @@
package org.session.libsignal.libsignal.loki
import org.session.libsignal.libsignal.protocol.CiphertextMessage
class FallbackMessage(private val paddedMessageBody: ByteArray) : CiphertextMessage {
override fun serialize(): ByteArray {
return paddedMessageBody
}
override fun getType(): Int {
return CiphertextMessage.FALLBACK_MESSAGE_TYPE
}
}

View File

@@ -0,0 +1,51 @@
package org.session.libsignal.libsignal.loki
import org.whispersystems.curve25519.Curve25519
import org.session.libsignal.libsignal.util.Hex
import org.session.libsignal.service.loki.utilities.removing05PrefixIfNeeded
/**
* A session cipher that uses the current user's private key along with a contact's public key to encrypt data.
*/
class FallbackSessionCipher(private val userPrivateKey: ByteArray, private val hexEncodedContactPublicKey: String) {
private val contactPublicKey by lazy {
val hexEncodedContactPublicKey = hexEncodedContactPublicKey.removing05PrefixIfNeeded()
Hex.fromStringCondensed(hexEncodedContactPublicKey)
}
private val symmetricKey: ByteArray?
get() {
try {
val curve = Curve25519.getInstance(Curve25519.BEST)
return curve.calculateAgreement(contactPublicKey, userPrivateKey)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
companion object {
@JvmStatic val sessionVersion = 3
}
fun encrypt(paddedMessageBody: ByteArray): ByteArray? {
val symmetricKey = symmetricKey ?: return null
try {
return DiffieHellman.encrypt(paddedMessageBody, symmetricKey)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
fun decrypt(bytes: ByteArray): ByteArray? {
val symmetricKey = symmetricKey ?: return null
try {
return DiffieHellman.decrypt(bytes, symmetricKey)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
}

View File

@@ -0,0 +1,78 @@
package org.session.libsignal.libsignal.loki
import org.session.libsignal.libsignal.DecryptionCallback
import org.session.libsignal.libsignal.SessionCipher
import org.session.libsignal.libsignal.SignalProtocolAddress
import org.session.libsignal.libsignal.protocol.PreKeySignalMessage
import org.session.libsignal.libsignal.protocol.SignalMessage
import org.session.libsignal.libsignal.state.SessionState
import org.session.libsignal.libsignal.state.SignalProtocolStore
/**
* A wrapper class for `SessionCipher`.
* This applies session reset logic on decryption.
*/
class LokiSessionCipher(private val protocolStore: SignalProtocolStore, private var sessionResetProtocol: SessionResetProtocol, val address: SignalProtocolAddress) : SessionCipher(protocolStore, address) {
override fun decrypt(ciphertext: PreKeySignalMessage?, callback: DecryptionCallback?): ByteArray {
// Record the current session state as it may change during decryption
val activeSession = getCurrentSessionState()
if (activeSession == null && ciphertext != null) {
sessionResetProtocol.validatePreKeySignalMessage(address.name, ciphertext)
}
val plainText = super.decrypt(ciphertext, callback)
handleSessionResetRequestIfNeeded(activeSession)
return plainText
}
override fun decrypt(ciphertext: SignalMessage?, callback: DecryptionCallback?): ByteArray {
// Record the current session state as it may change during decryption
val activeSession = getCurrentSessionState()
val plainText = super.decrypt(ciphertext, callback)
handleSessionResetRequestIfNeeded(activeSession)
return plainText
}
private fun getCurrentSessionState(): SessionState? {
val sessionRecord = protocolStore.loadSession(address)
return sessionRecord.sessionState
}
private fun handleSessionResetRequestIfNeeded(oldSession: SessionState?) {
if (oldSession == null) { return }
val publicKey = address.name
val currentSessionResetStatus = sessionResetProtocol.getSessionResetStatus(publicKey)
if (currentSessionResetStatus == SessionResetStatus.NONE) return
val currentSession = getCurrentSessionState()
if (currentSession == null || currentSession.aliceBaseKey?.contentEquals(oldSession.aliceBaseKey) != true) {
if (currentSessionResetStatus == SessionResetStatus.REQUEST_RECEIVED) {
// The other user used an old session to contact us; wait for them to switch to a new one.
restoreSession(oldSession)
} else {
// Our session reset was successful; we initiated one and got a new session back from the other user.
deleteAllSessionsExcept(currentSession)
sessionResetProtocol.setSessionResetStatus(publicKey, SessionResetStatus.NONE)
sessionResetProtocol.onNewSessionAdopted(publicKey, currentSessionResetStatus)
}
} else if (currentSessionResetStatus == SessionResetStatus.REQUEST_RECEIVED) {
// Our session reset was successful; we received a message with the same session from the other user.
deleteAllSessionsExcept(oldSession)
sessionResetProtocol.setSessionResetStatus(publicKey, SessionResetStatus.NONE)
sessionResetProtocol.onNewSessionAdopted(publicKey, currentSessionResetStatus)
}
}
private fun restoreSession(state: SessionState) {
val session = protocolStore.loadSession(address)
session.previousSessionStates.removeAll { it.aliceBaseKey?.contentEquals(state.aliceBaseKey) ?: false }
session.promoteState(state)
protocolStore.storeSession(address, session)
}
private fun deleteAllSessionsExcept(state: SessionState?) {
val sessionRecord = protocolStore.loadSession(address)
sessionRecord.removePreviousSessionStates()
sessionRecord.setState(state ?: SessionState())
protocolStore.storeSession(address, sessionRecord)
}
}

View File

@@ -0,0 +1,11 @@
package org.session.libsignal.libsignal.loki
import org.session.libsignal.libsignal.protocol.PreKeySignalMessage
interface SessionResetProtocol {
fun getSessionResetStatus(publicKey: String): SessionResetStatus
fun setSessionResetStatus(publicKey: String, sessionResetStatus: SessionResetStatus)
fun validatePreKeySignalMessage(publicKey: String, message: PreKeySignalMessage)
fun onNewSessionAdopted(publicKey: String, oldSessionResetStatus: SessionResetStatus)
}

View File

@@ -0,0 +1,7 @@
package org.session.libsignal.libsignal.loki
enum class SessionResetStatus(val rawValue: Int) {
NONE(0),
IN_PROGRESS(1),
REQUEST_RECEIVED(2)
}

View File

@@ -0,0 +1,26 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
* <p>
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.protocol;
public interface CiphertextMessage {
public static final int CURRENT_VERSION = 3;
public static final int WHISPER_TYPE = 2;
public static final int PREKEY_TYPE = 3;
public static final int SENDERKEY_TYPE = 4;
public static final int SENDERKEY_DISTRIBUTION_TYPE = 5;
public static final int CLOSED_GROUP_CIPHERTEXT = 6;
public static final int FALLBACK_MESSAGE_TYPE = 999; // Loki
// This should be the worst case (worse than V2). So not always accurate, but good enough for padding.
public static final int ENCRYPTED_MESSAGE_OVERHEAD = 53;
public byte[] serialize();
public int getType();
}

View File

@@ -0,0 +1,68 @@
package org.session.libsignal.libsignal.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.whispersystems.curve25519.VrfSignatureVerificationFailedException;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.devices.DeviceConsistencyCommitment;
import org.session.libsignal.libsignal.devices.DeviceConsistencySignature;
import org.session.libsignal.libsignal.ecc.Curve;
public class DeviceConsistencyMessage {
private final DeviceConsistencySignature signature;
private final int generation;
private final byte[] serialized;
public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, IdentityKeyPair identityKeyPair) {
try {
byte[] signatureBytes = Curve.calculateVrfSignature(identityKeyPair.getPrivateKey(), commitment.toByteArray());
byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKeyPair.getPublicKey().getPublicKey(), commitment.toByteArray(), signatureBytes);
this.generation = commitment.getGeneration();
this.signature = new DeviceConsistencySignature(signatureBytes, vrfOutputBytes);
this.serialized = SignalProtos.DeviceConsistencyCodeMessage.newBuilder()
.setGeneration(commitment.getGeneration())
.setSignature(ByteString.copyFrom(signature.getSignature()))
.build()
.toByteArray();
} catch (InvalidKeyException e) {
throw new AssertionError(e);
} catch (VrfSignatureVerificationFailedException e) {
throw new AssertionError(e);
}
}
public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, byte[] serialized, IdentityKey identityKey) throws InvalidMessageException {
try {
SignalProtos.DeviceConsistencyCodeMessage message = SignalProtos.DeviceConsistencyCodeMessage.parseFrom(serialized);
byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKey.getPublicKey(), commitment.toByteArray(), message.getSignature().toByteArray());
this.generation = message.getGeneration();
this.signature = new DeviceConsistencySignature(message.getSignature().toByteArray(), vrfOutputBytes);
this.serialized = serialized;
} catch (InvalidProtocolBufferException e) {
throw new InvalidMessageException(e);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
} catch (VrfSignatureVerificationFailedException e) {
throw new InvalidMessageException(e);
}
}
public byte[] getSerialized() {
return serialized;
}
public DeviceConsistencySignature getSignature() {
return signature;
}
public int getGeneration() {
return generation;
}
}

View File

@@ -0,0 +1,143 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.InvalidVersionException;
import org.session.libsignal.libsignal.LegacyMessageException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.util.ByteUtil;
import org.session.libsignal.libsignal.util.guava.Optional;
public class PreKeySignalMessage implements CiphertextMessage {
private final int version;
private final int registrationId;
private final Optional<Integer> preKeyId;
private final int signedPreKeyId;
private final ECPublicKey baseKey;
private final IdentityKey identityKey;
private final SignalMessage message;
private final byte[] serialized;
public PreKeySignalMessage(byte[] serialized)
throws InvalidMessageException, InvalidVersionException
{
try {
this.version = ByteUtil.highBitsToInt(serialized[0]);
if (this.version > CiphertextMessage.CURRENT_VERSION) {
throw new InvalidVersionException("Unknown version: " + this.version);
}
if (this.version < CiphertextMessage.CURRENT_VERSION) {
throw new LegacyMessageException("Legacy version: " + this.version);
}
SignalProtos.PreKeySignalMessage preKeyWhisperMessage
= SignalProtos.PreKeySignalMessage.parseFrom(ByteString.copyFrom(serialized, 1,
serialized.length-1));
if (!preKeyWhisperMessage.hasSignedPreKeyId() ||
!preKeyWhisperMessage.hasBaseKey() ||
!preKeyWhisperMessage.hasIdentityKey() ||
!preKeyWhisperMessage.hasMessage())
{
throw new InvalidMessageException("Incomplete message.");
}
this.serialized = serialized;
this.registrationId = preKeyWhisperMessage.getRegistrationId();
this.preKeyId = preKeyWhisperMessage.hasPreKeyId() ? Optional.of(preKeyWhisperMessage.getPreKeyId()) : Optional.<Integer>absent();
this.signedPreKeyId = preKeyWhisperMessage.hasSignedPreKeyId() ? preKeyWhisperMessage.getSignedPreKeyId() : -1;
this.baseKey = Curve.decodePoint(preKeyWhisperMessage.getBaseKey().toByteArray(), 0);
this.identityKey = new IdentityKey(Curve.decodePoint(preKeyWhisperMessage.getIdentityKey().toByteArray(), 0));
this.message = new SignalMessage(preKeyWhisperMessage.getMessage().toByteArray());
} catch (InvalidProtocolBufferException e) {
throw new InvalidMessageException(e);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
} catch (LegacyMessageException e) {
throw new InvalidMessageException(e);
}
}
public PreKeySignalMessage(int messageVersion, int registrationId, Optional<Integer> preKeyId,
int signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey,
SignalMessage message)
{
this.version = messageVersion;
this.registrationId = registrationId;
this.preKeyId = preKeyId;
this.signedPreKeyId = signedPreKeyId;
this.baseKey = baseKey;
this.identityKey = identityKey;
this.message = message;
SignalProtos.PreKeySignalMessage.Builder builder =
SignalProtos.PreKeySignalMessage.newBuilder()
.setSignedPreKeyId(signedPreKeyId)
.setBaseKey(ByteString.copyFrom(baseKey.serialize()))
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setMessage(ByteString.copyFrom(message.serialize()))
.setRegistrationId(registrationId);
if (preKeyId.isPresent()) {
builder.setPreKeyId(preKeyId.get());
}
byte[] versionBytes = {ByteUtil.intsToByteHighAndLow(this.version, CURRENT_VERSION)};
byte[] messageBytes = builder.build().toByteArray();
this.serialized = ByteUtil.combine(versionBytes, messageBytes);
}
public int getMessageVersion() {
return version;
}
public IdentityKey getIdentityKey() {
return identityKey;
}
public int getRegistrationId() {
return registrationId;
}
public Optional<Integer> getPreKeyId() {
return preKeyId;
}
public int getSignedPreKeyId() {
return signedPreKeyId;
}
public ECPublicKey getBaseKey() {
return baseKey;
}
public SignalMessage getWhisperMessage() {
return message;
}
@Override
public byte[] serialize() {
return serialized;
}
@Override
public int getType() {
return CiphertextMessage.PREKEY_TYPE;
}
}

View File

@@ -0,0 +1,103 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.LegacyMessageException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.util.ByteUtil;
public class SenderKeyDistributionMessage implements CiphertextMessage {
private final int id;
private final int iteration;
private final byte[] chainKey;
private final ECPublicKey signatureKey;
private final byte[] serialized;
public SenderKeyDistributionMessage(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
byte[] version = {ByteUtil.intsToByteHighAndLow(CURRENT_VERSION, CURRENT_VERSION)};
byte[] protobuf = SignalProtos.SenderKeyDistributionMessage.newBuilder()
.setId(id)
.setIteration(iteration)
.setChainKey(ByteString.copyFrom(chainKey))
.setSigningKey(ByteString.copyFrom(signatureKey.serialize()))
.build().toByteArray();
this.id = id;
this.iteration = iteration;
this.chainKey = chainKey;
this.signatureKey = signatureKey;
this.serialized = ByteUtil.combine(version, protobuf);
}
public SenderKeyDistributionMessage(byte[] serialized) throws LegacyMessageException, InvalidMessageException {
try {
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1);
byte version = messageParts[0][0];
byte[] message = messageParts[1];
if (ByteUtil.highBitsToInt(version) < CiphertextMessage.CURRENT_VERSION) {
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
}
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
}
SignalProtos.SenderKeyDistributionMessage distributionMessage = SignalProtos.SenderKeyDistributionMessage.parseFrom(message);
if (!distributionMessage.hasId() ||
!distributionMessage.hasIteration() ||
!distributionMessage.hasChainKey() ||
!distributionMessage.hasSigningKey())
{
throw new InvalidMessageException("Incomplete message.");
}
this.serialized = serialized;
this.id = distributionMessage.getId();
this.iteration = distributionMessage.getIteration();
this.chainKey = distributionMessage.getChainKey().toByteArray();
this.signatureKey = Curve.decodePoint(distributionMessage.getSigningKey().toByteArray(), 0);
} catch (InvalidProtocolBufferException e) {
throw new InvalidMessageException(e);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
}
}
@Override
public byte[] serialize() {
return serialized;
}
@Override
public int getType() {
return SENDERKEY_DISTRIBUTION_TYPE;
}
public int getIteration() {
return iteration;
}
public byte[] getChainKey() {
return chainKey;
}
public ECPublicKey getSignatureKey() {
return signatureKey;
}
public int getId() {
return id;
}
}

View File

@@ -0,0 +1,129 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.LegacyMessageException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.protocol.CiphertextMessage;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.text.ParseException;
public class SenderKeyMessage implements CiphertextMessage {
private static final int SIGNATURE_LENGTH = 64;
private final int messageVersion;
private final int keyId;
private final int iteration;
private final byte[] ciphertext;
private final byte[] serialized;
public SenderKeyMessage(byte[] serialized) throws InvalidMessageException, LegacyMessageException {
try {
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1 - SIGNATURE_LENGTH, SIGNATURE_LENGTH);
byte version = messageParts[0][0];
byte[] message = messageParts[1];
byte[] signature = messageParts[2];
if (ByteUtil.highBitsToInt(version) < 3) {
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
}
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
}
SignalProtos.SenderKeyMessage senderKeyMessage = SignalProtos.SenderKeyMessage.parseFrom(message);
if (!senderKeyMessage.hasId() ||
!senderKeyMessage.hasIteration() ||
!senderKeyMessage.hasCiphertext())
{
throw new InvalidMessageException("Incomplete message.");
}
this.serialized = serialized;
this.messageVersion = ByteUtil.highBitsToInt(version);
this.keyId = senderKeyMessage.getId();
this.iteration = senderKeyMessage.getIteration();
this.ciphertext = senderKeyMessage.getCiphertext().toByteArray();
} catch (InvalidProtocolBufferException e) {
throw new InvalidMessageException(e);
} catch (ParseException e) {
throw new InvalidMessageException(e);
}
}
public SenderKeyMessage(int keyId, int iteration, byte[] ciphertext, ECPrivateKey signatureKey) {
byte[] version = {ByteUtil.intsToByteHighAndLow(CURRENT_VERSION, CURRENT_VERSION)};
byte[] message = SignalProtos.SenderKeyMessage.newBuilder()
.setId(keyId)
.setIteration(iteration)
.setCiphertext(ByteString.copyFrom(ciphertext))
.build().toByteArray();
byte[] signature = getSignature(signatureKey, ByteUtil.combine(version, message));
this.serialized = ByteUtil.combine(version, message, signature);
this.messageVersion = CURRENT_VERSION;
this.keyId = keyId;
this.iteration = iteration;
this.ciphertext = ciphertext;
}
public int getKeyId() {
return keyId;
}
public int getIteration() {
return iteration;
}
public byte[] getCipherText() {
return ciphertext;
}
public void verifySignature(ECPublicKey signatureKey)
throws InvalidMessageException
{
try {
byte[][] parts = ByteUtil.split(serialized, serialized.length - SIGNATURE_LENGTH, SIGNATURE_LENGTH);
if (!Curve.verifySignature(signatureKey, parts[0], parts[1])) {
throw new InvalidMessageException("Invalid signature!");
}
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
}
}
private byte[] getSignature(ECPrivateKey signatureKey, byte[] serialized) {
try {
return Curve.calculateSignature(signatureKey, serialized);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
@Override
public byte[] serialize() {
return serialized;
}
@Override
public int getType() {
return CiphertextMessage.SENDERKEY_TYPE;
}
}

View File

@@ -0,0 +1,163 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.InvalidMessageException;
import org.session.libsignal.libsignal.LegacyMessageException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.protocol.CiphertextMessage;
import org.session.libsignal.libsignal.util.ByteUtil;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SignalMessage implements CiphertextMessage {
private static final int MAC_LENGTH = 8;
private final int messageVersion;
private final ECPublicKey senderRatchetKey;
private final int counter;
private final int previousCounter;
private final byte[] ciphertext;
private final byte[] serialized;
public SignalMessage(byte[] serialized) throws InvalidMessageException, LegacyMessageException {
try {
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1 - MAC_LENGTH, MAC_LENGTH);
byte version = messageParts[0][0];
byte[] message = messageParts[1];
byte[] mac = messageParts[2];
if (ByteUtil.highBitsToInt(version) < CURRENT_VERSION) {
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
}
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
}
SignalProtos.SignalMessage whisperMessage = SignalProtos.SignalMessage.parseFrom(message);
if (!whisperMessage.hasCiphertext() ||
!whisperMessage.hasCounter() ||
!whisperMessage.hasRatchetKey())
{
throw new InvalidMessageException("Incomplete message.");
}
this.serialized = serialized;
this.senderRatchetKey = Curve.decodePoint(whisperMessage.getRatchetKey().toByteArray(), 0);
this.messageVersion = ByteUtil.highBitsToInt(version);
this.counter = whisperMessage.getCounter();
this.previousCounter = whisperMessage.getPreviousCounter();
this.ciphertext = whisperMessage.getCiphertext().toByteArray();
} catch (InvalidProtocolBufferException e) {
throw new InvalidMessageException(e);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
} catch (ParseException e) {
throw new InvalidMessageException(e);
}
}
public SignalMessage(int messageVersion, SecretKeySpec macKey, ECPublicKey senderRatchetKey,
int counter, int previousCounter, byte[] ciphertext,
IdentityKey senderIdentityKey,
IdentityKey receiverIdentityKey)
{
byte[] version = {ByteUtil.intsToByteHighAndLow(messageVersion, CURRENT_VERSION)};
byte[] message = SignalProtos.SignalMessage.newBuilder()
.setRatchetKey(ByteString.copyFrom(senderRatchetKey.serialize()))
.setCounter(counter)
.setPreviousCounter(previousCounter)
.setCiphertext(ByteString.copyFrom(ciphertext))
.build().toByteArray();
byte[] mac = getMac(senderIdentityKey, receiverIdentityKey, macKey, ByteUtil.combine(version, message));
this.serialized = ByteUtil.combine(version, message, mac);
this.senderRatchetKey = senderRatchetKey;
this.counter = counter;
this.previousCounter = previousCounter;
this.ciphertext = ciphertext;
this.messageVersion = messageVersion;
}
public ECPublicKey getSenderRatchetKey() {
return senderRatchetKey;
}
public int getMessageVersion() {
return messageVersion;
}
public int getCounter() {
return counter;
}
public byte[] getBody() {
return ciphertext;
}
public void verifyMac(IdentityKey senderIdentityKey, IdentityKey receiverIdentityKey, SecretKeySpec macKey)
throws InvalidMessageException
{
byte[][] parts = ByteUtil.split(serialized, serialized.length - MAC_LENGTH, MAC_LENGTH);
byte[] ourMac = getMac(senderIdentityKey, receiverIdentityKey, macKey, parts[0]);
byte[] theirMac = parts[1];
if (!MessageDigest.isEqual(ourMac, theirMac)) {
throw new InvalidMessageException("Bad Mac!");
}
}
private byte[] getMac(IdentityKey senderIdentityKey,
IdentityKey receiverIdentityKey,
SecretKeySpec macKey, byte[] serialized)
{
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(macKey);
mac.update(senderIdentityKey.getPublicKey().serialize());
mac.update(receiverIdentityKey.getPublicKey().serialize());
byte[] fullMac = mac.doFinal(serialized);
return ByteUtil.trim(fullMac, MAC_LENGTH);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (java.security.InvalidKeyException e) {
throw new AssertionError(e);
}
}
@Override
public byte[] serialize() {
return serialized;
}
@Override
public int getType() {
return CiphertextMessage.WHISPER_TYPE;
}
public static boolean isLegacy(byte[] message) {
return message != null && message.length >= 1 &&
ByteUtil.highBitsToInt(message[0]) != CiphertextMessage.CURRENT_VERSION;
}
}

View File

@@ -0,0 +1,114 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.util.guava.Optional;
public class AliceSignalProtocolParameters {
private final IdentityKeyPair ourIdentityKey;
private final ECKeyPair ourBaseKey;
private final IdentityKey theirIdentityKey;
private final ECPublicKey theirSignedPreKey;
private final Optional<ECPublicKey> theirOneTimePreKey;
private final ECPublicKey theirRatchetKey;
private AliceSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourBaseKey,
IdentityKey theirIdentityKey, ECPublicKey theirSignedPreKey,
ECPublicKey theirRatchetKey, Optional<ECPublicKey> theirOneTimePreKey)
{
this.ourIdentityKey = ourIdentityKey;
this.ourBaseKey = ourBaseKey;
this.theirIdentityKey = theirIdentityKey;
this.theirSignedPreKey = theirSignedPreKey;
this.theirRatchetKey = theirRatchetKey;
this.theirOneTimePreKey = theirOneTimePreKey;
if (ourIdentityKey == null || ourBaseKey == null || theirIdentityKey == null ||
theirSignedPreKey == null || theirRatchetKey == null || theirOneTimePreKey == null)
{
throw new IllegalArgumentException("Null values!");
}
}
public IdentityKeyPair getOurIdentityKey() {
return ourIdentityKey;
}
public ECKeyPair getOurBaseKey() {
return ourBaseKey;
}
public IdentityKey getTheirIdentityKey() {
return theirIdentityKey;
}
public ECPublicKey getTheirSignedPreKey() {
return theirSignedPreKey;
}
public Optional<ECPublicKey> getTheirOneTimePreKey() {
return theirOneTimePreKey;
}
public static Builder newBuilder() {
return new Builder();
}
public ECPublicKey getTheirRatchetKey() {
return theirRatchetKey;
}
public static class Builder {
private IdentityKeyPair ourIdentityKey;
private ECKeyPair ourBaseKey;
private IdentityKey theirIdentityKey;
private ECPublicKey theirSignedPreKey;
private ECPublicKey theirRatchetKey;
private Optional<ECPublicKey> theirOneTimePreKey;
public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey) {
this.ourIdentityKey = ourIdentityKey;
return this;
}
public Builder setOurBaseKey(ECKeyPair ourBaseKey) {
this.ourBaseKey = ourBaseKey;
return this;
}
public Builder setTheirRatchetKey(ECPublicKey theirRatchetKey) {
this.theirRatchetKey = theirRatchetKey;
return this;
}
public Builder setTheirIdentityKey(IdentityKey theirIdentityKey) {
this.theirIdentityKey = theirIdentityKey;
return this;
}
public Builder setTheirSignedPreKey(ECPublicKey theirSignedPreKey) {
this.theirSignedPreKey = theirSignedPreKey;
return this;
}
public Builder setTheirOneTimePreKey(Optional<ECPublicKey> theirOneTimePreKey) {
this.theirOneTimePreKey = theirOneTimePreKey;
return this;
}
public AliceSignalProtocolParameters create() {
return new AliceSignalProtocolParameters(ourIdentityKey, ourBaseKey, theirIdentityKey,
theirSignedPreKey, theirRatchetKey, theirOneTimePreKey);
}
}
}

View File

@@ -0,0 +1,114 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.util.guava.Optional;
public class BobSignalProtocolParameters {
private final IdentityKeyPair ourIdentityKey;
private final ECKeyPair ourSignedPreKey;
private final Optional<ECKeyPair> ourOneTimePreKey;
private final ECKeyPair ourRatchetKey;
private final IdentityKey theirIdentityKey;
private final ECPublicKey theirBaseKey;
BobSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourSignedPreKey,
ECKeyPair ourRatchetKey, Optional<ECKeyPair> ourOneTimePreKey,
IdentityKey theirIdentityKey, ECPublicKey theirBaseKey)
{
this.ourIdentityKey = ourIdentityKey;
this.ourSignedPreKey = ourSignedPreKey;
this.ourRatchetKey = ourRatchetKey;
this.ourOneTimePreKey = ourOneTimePreKey;
this.theirIdentityKey = theirIdentityKey;
this.theirBaseKey = theirBaseKey;
if (ourIdentityKey == null || ourSignedPreKey == null || ourRatchetKey == null ||
ourOneTimePreKey == null || theirIdentityKey == null || theirBaseKey == null)
{
throw new IllegalArgumentException("Null value!");
}
}
public IdentityKeyPair getOurIdentityKey() {
return ourIdentityKey;
}
public ECKeyPair getOurSignedPreKey() {
return ourSignedPreKey;
}
public Optional<ECKeyPair> getOurOneTimePreKey() {
return ourOneTimePreKey;
}
public IdentityKey getTheirIdentityKey() {
return theirIdentityKey;
}
public ECPublicKey getTheirBaseKey() {
return theirBaseKey;
}
public static Builder newBuilder() {
return new Builder();
}
public ECKeyPair getOurRatchetKey() {
return ourRatchetKey;
}
public static class Builder {
private IdentityKeyPair ourIdentityKey;
private ECKeyPair ourSignedPreKey;
private Optional<ECKeyPair> ourOneTimePreKey;
private ECKeyPair ourRatchetKey;
private IdentityKey theirIdentityKey;
private ECPublicKey theirBaseKey;
public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey) {
this.ourIdentityKey = ourIdentityKey;
return this;
}
public Builder setOurSignedPreKey(ECKeyPair ourSignedPreKey) {
this.ourSignedPreKey = ourSignedPreKey;
return this;
}
public Builder setOurOneTimePreKey(Optional<ECKeyPair> ourOneTimePreKey) {
this.ourOneTimePreKey = ourOneTimePreKey;
return this;
}
public Builder setTheirIdentityKey(IdentityKey theirIdentityKey) {
this.theirIdentityKey = theirIdentityKey;
return this;
}
public Builder setTheirBaseKey(ECPublicKey theirBaseKey) {
this.theirBaseKey = theirBaseKey;
return this;
}
public Builder setOurRatchetKey(ECKeyPair ourRatchetKey) {
this.ourRatchetKey = ourRatchetKey;
return this;
}
public BobSignalProtocolParameters create() {
return new BobSignalProtocolParameters(ourIdentityKey, ourSignedPreKey, ourRatchetKey,
ourOneTimePreKey, theirIdentityKey, theirBaseKey);
}
}
}

View File

@@ -0,0 +1,67 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.kdf.DerivedMessageSecrets;
import org.session.libsignal.libsignal.kdf.HKDF;
import org.session.libsignal.libsignal.ratchet.MessageKeys;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class ChainKey {
private static final byte[] MESSAGE_KEY_SEED = {0x01};
private static final byte[] CHAIN_KEY_SEED = {0x02};
private final HKDF kdf;
private final byte[] key;
private final int index;
public ChainKey(HKDF kdf, byte[] key, int index) {
this.kdf = kdf;
this.key = key;
this.index = index;
}
public byte[] getKey() {
return key;
}
public int getIndex() {
return index;
}
public ChainKey getNextChainKey() {
byte[] nextKey = getBaseMaterial(CHAIN_KEY_SEED);
return new ChainKey(kdf, nextKey, index + 1);
}
public MessageKeys getMessageKeys() {
byte[] inputKeyMaterial = getBaseMaterial(MESSAGE_KEY_SEED);
byte[] keyMaterialBytes = kdf.deriveSecrets(inputKeyMaterial, "WhisperMessageKeys".getBytes(), DerivedMessageSecrets.SIZE);
DerivedMessageSecrets keyMaterial = new DerivedMessageSecrets(keyMaterialBytes);
return new MessageKeys(keyMaterial.getCipherKey(), keyMaterial.getMacKey(), keyMaterial.getIv(), index);
}
private byte[] getBaseMaterial(byte[] seed) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(seed);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
}

View File

@@ -0,0 +1,40 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MessageKeys {
private final SecretKeySpec cipherKey;
private final SecretKeySpec macKey;
private final IvParameterSpec iv;
private final int counter;
public MessageKeys(SecretKeySpec cipherKey, SecretKeySpec macKey, IvParameterSpec iv, int counter) {
this.cipherKey = cipherKey;
this.macKey = macKey;
this.iv = iv;
this.counter = counter;
}
public SecretKeySpec getCipherKey() {
return cipherKey;
}
public SecretKeySpec getMacKey() {
return macKey;
}
public IvParameterSpec getIv() {
return iv;
}
public int getCounter() {
return counter;
}
}

View File

@@ -0,0 +1,163 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.kdf.HKDF;
import org.session.libsignal.libsignal.kdf.HKDFv3;
import org.session.libsignal.libsignal.protocol.CiphertextMessage;
import org.session.libsignal.libsignal.ratchet.AliceSignalProtocolParameters;
import org.session.libsignal.libsignal.ratchet.BobSignalProtocolParameters;
import org.session.libsignal.libsignal.ratchet.SymmetricSignalProtocolParameters;
import org.session.libsignal.libsignal.state.SessionState;
import org.session.libsignal.libsignal.util.ByteUtil;
import org.session.libsignal.libsignal.util.Pair;
import org.session.libsignal.libsignal.util.guava.Optional;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class RatchetingSession {
public static void initializeSession(SessionState sessionState, SymmetricSignalProtocolParameters parameters)
throws InvalidKeyException
{
if (isAlice(parameters.getOurBaseKey().getPublicKey(), parameters.getTheirBaseKey())) {
AliceSignalProtocolParameters.Builder aliceParameters = AliceSignalProtocolParameters.newBuilder();
aliceParameters.setOurBaseKey(parameters.getOurBaseKey())
.setOurIdentityKey(parameters.getOurIdentityKey())
.setTheirRatchetKey(parameters.getTheirRatchetKey())
.setTheirIdentityKey(parameters.getTheirIdentityKey())
.setTheirSignedPreKey(parameters.getTheirBaseKey())
.setTheirOneTimePreKey(Optional.<ECPublicKey>absent());
RatchetingSession.initializeSession(sessionState, aliceParameters.create());
} else {
BobSignalProtocolParameters.Builder bobParameters = BobSignalProtocolParameters.newBuilder();
bobParameters.setOurIdentityKey(parameters.getOurIdentityKey())
.setOurRatchetKey(parameters.getOurRatchetKey())
.setOurSignedPreKey(parameters.getOurBaseKey())
.setOurOneTimePreKey(Optional.<ECKeyPair>absent())
.setTheirBaseKey(parameters.getTheirBaseKey())
.setTheirIdentityKey(parameters.getTheirIdentityKey());
RatchetingSession.initializeSession(sessionState, bobParameters.create());
}
}
public static void initializeSession(SessionState sessionState, AliceSignalProtocolParameters parameters)
throws InvalidKeyException
{
try {
sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION);
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey());
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey());
ECKeyPair sendingRatchetKey = Curve.generateKeyPair();
ByteArrayOutputStream secrets = new ByteArrayOutputStream();
secrets.write(getDiscontinuityBytes());
secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
parameters.getOurIdentityKey().getPrivateKey()));
secrets.write(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),
parameters.getOurBaseKey().getPrivateKey()));
secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
parameters.getOurBaseKey().getPrivateKey()));
if (parameters.getTheirOneTimePreKey().isPresent()) {
secrets.write(Curve.calculateAgreement(parameters.getTheirOneTimePreKey().get(),
parameters.getOurBaseKey().getPrivateKey()));
}
DerivedKeys derivedKeys = calculateDerivedKeys(secrets.toByteArray());
Pair<RootKey, ChainKey> sendingChain = derivedKeys.getRootKey().createChain(parameters.getTheirRatchetKey(), sendingRatchetKey);
sessionState.addReceiverChain(parameters.getTheirRatchetKey(), derivedKeys.getChainKey());
sessionState.setSenderChain(sendingRatchetKey, sendingChain.second());
sessionState.setRootKey(sendingChain.first());
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static void initializeSession(SessionState sessionState, BobSignalProtocolParameters parameters)
throws InvalidKeyException
{
try {
sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION);
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey());
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey());
ByteArrayOutputStream secrets = new ByteArrayOutputStream();
secrets.write(getDiscontinuityBytes());
secrets.write(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),
parameters.getOurSignedPreKey().getPrivateKey()));
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
parameters.getOurIdentityKey().getPrivateKey()));
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
parameters.getOurSignedPreKey().getPrivateKey()));
if (parameters.getOurOneTimePreKey().isPresent()) {
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
parameters.getOurOneTimePreKey().get().getPrivateKey()));
}
DerivedKeys derivedKeys = calculateDerivedKeys(secrets.toByteArray());
sessionState.setSenderChain(parameters.getOurRatchetKey(), derivedKeys.getChainKey());
sessionState.setRootKey(derivedKeys.getRootKey());
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static byte[] getDiscontinuityBytes() {
byte[] discontinuity = new byte[32];
Arrays.fill(discontinuity, (byte) 0xFF);
return discontinuity;
}
private static DerivedKeys calculateDerivedKeys(byte[] masterSecret) {
HKDF kdf = new HKDFv3();
byte[] derivedSecretBytes = kdf.deriveSecrets(masterSecret, "WhisperText".getBytes(), 64);
byte[][] derivedSecrets = ByteUtil.split(derivedSecretBytes, 32, 32);
return new DerivedKeys(new RootKey(kdf, derivedSecrets[0]),
new ChainKey(kdf, derivedSecrets[1], 0));
}
private static boolean isAlice(ECPublicKey ourKey, ECPublicKey theirKey) {
return ourKey.compareTo(theirKey) < 0;
}
private static class DerivedKeys {
private final RootKey rootKey;
private final ChainKey chainKey;
private DerivedKeys(RootKey rootKey, ChainKey chainKey) {
this.rootKey = rootKey;
this.chainKey = chainKey;
}
public RootKey getRootKey() {
return rootKey;
}
public ChainKey getChainKey() {
return chainKey;
}
}
}

View File

@@ -0,0 +1,44 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.kdf.DerivedRootSecrets;
import org.session.libsignal.libsignal.kdf.HKDF;
import org.session.libsignal.libsignal.ratchet.ChainKey;
import org.session.libsignal.libsignal.util.ByteUtil;
import org.session.libsignal.libsignal.util.Pair;
public class RootKey {
private final HKDF kdf;
private final byte[] key;
public RootKey(HKDF kdf, byte[] key) {
this.kdf = kdf;
this.key = key;
}
public byte[] getKeyBytes() {
return key;
}
public Pair<RootKey, ChainKey> createChain(ECPublicKey theirRatchetKey, ECKeyPair ourRatchetKey)
throws InvalidKeyException
{
byte[] sharedSecret = Curve.calculateAgreement(theirRatchetKey, ourRatchetKey.getPrivateKey());
byte[] derivedSecretBytes = kdf.deriveSecrets(sharedSecret, key, "WhisperRatchet".getBytes(), DerivedRootSecrets.SIZE);
DerivedRootSecrets derivedSecrets = new DerivedRootSecrets(derivedSecretBytes);
RootKey newRootKey = new RootKey(kdf, derivedSecrets.getRootKey());
ChainKey newChainKey = new ChainKey(kdf, derivedSecrets.getChainKey(), 0);
return new Pair<RootKey, ChainKey>(newRootKey, newChainKey);
}
}

View File

@@ -0,0 +1,113 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.ratchet;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
public class SymmetricSignalProtocolParameters {
private final ECKeyPair ourBaseKey;
private final ECKeyPair ourRatchetKey;
private final IdentityKeyPair ourIdentityKey;
private final ECPublicKey theirBaseKey;
private final ECPublicKey theirRatchetKey;
private final IdentityKey theirIdentityKey;
SymmetricSignalProtocolParameters(ECKeyPair ourBaseKey, ECKeyPair ourRatchetKey,
IdentityKeyPair ourIdentityKey, ECPublicKey theirBaseKey,
ECPublicKey theirRatchetKey, IdentityKey theirIdentityKey)
{
this.ourBaseKey = ourBaseKey;
this.ourRatchetKey = ourRatchetKey;
this.ourIdentityKey = ourIdentityKey;
this.theirBaseKey = theirBaseKey;
this.theirRatchetKey = theirRatchetKey;
this.theirIdentityKey = theirIdentityKey;
if (ourBaseKey == null || ourRatchetKey == null || ourIdentityKey == null ||
theirBaseKey == null || theirRatchetKey == null || theirIdentityKey == null)
{
throw new IllegalArgumentException("Null values!");
}
}
public ECKeyPair getOurBaseKey() {
return ourBaseKey;
}
public ECKeyPair getOurRatchetKey() {
return ourRatchetKey;
}
public IdentityKeyPair getOurIdentityKey() {
return ourIdentityKey;
}
public ECPublicKey getTheirBaseKey() {
return theirBaseKey;
}
public ECPublicKey getTheirRatchetKey() {
return theirRatchetKey;
}
public IdentityKey getTheirIdentityKey() {
return theirIdentityKey;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private ECKeyPair ourBaseKey;
private ECKeyPair ourRatchetKey;
private IdentityKeyPair ourIdentityKey;
private ECPublicKey theirBaseKey;
private ECPublicKey theirRatchetKey;
private IdentityKey theirIdentityKey;
public Builder setOurBaseKey(ECKeyPair ourBaseKey) {
this.ourBaseKey = ourBaseKey;
return this;
}
public Builder setOurRatchetKey(ECKeyPair ourRatchetKey) {
this.ourRatchetKey = ourRatchetKey;
return this;
}
public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey) {
this.ourIdentityKey = ourIdentityKey;
return this;
}
public Builder setTheirBaseKey(ECPublicKey theirBaseKey) {
this.theirBaseKey = theirBaseKey;
return this;
}
public Builder setTheirRatchetKey(ECPublicKey theirRatchetKey) {
this.theirRatchetKey = theirRatchetKey;
return this;
}
public Builder setTheirIdentityKey(IdentityKey theirIdentityKey) {
this.theirIdentityKey = theirIdentityKey;
return this;
}
public SymmetricSignalProtocolParameters create() {
return new SymmetricSignalProtocolParameters(ourBaseKey, ourRatchetKey, ourIdentityKey,
theirBaseKey, theirRatchetKey, theirIdentityKey);
}
}
}

View File

@@ -0,0 +1,82 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.SignalProtocolAddress;
/**
* Provides an interface to identity information.
*
* @author Moxie Marlinspike
*/
public interface IdentityKeyStore {
public enum Direction {
SENDING, RECEIVING
}
/**
* Get the local client's identity key pair.
*
* @return The local client's persistent identity key pair.
*/
public IdentityKeyPair getIdentityKeyPair();
/**
* Return the local client's registration ID.
* <p>
* Clients should maintain a registration ID, a random number
* between 1 and 16380 that's generated once at install time.
*
* @return the local client's registration ID.
*/
public int getLocalRegistrationId();
/**
* Save a remote client's identity key
* <p>
* Store a remote client's identity key as trusted.
*
* @param address The address of the remote client.
* @param identityKey The remote client's identity key.
* @return True if the identity key replaces a previous identity, false if not
*/
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey);
/**
* Verify a remote client's identity key.
* <p>
* Determine whether a remote client's identity is trusted. Convention is
* that the Signal Protocol is 'trust on first use.' This means that
* an identity key is considered 'trusted' if there is no entry for the recipient
* in the local store, or if it matches the saved key for a recipient in the local
* store. Only if it mismatches an entry in the local store is it considered
* 'untrusted.'
*
* Clients may wish to make a distinction as to how keys are trusted based on the
* direction of travel. For instance, clients may wish to accept all 'incoming' identity
* key changes, while only blocking identity key changes when sending a message.
*
* @param address The address of the remote client.
* @param identityKey The identity key to verify.
* @param direction The direction (sending or receiving) this identity is being used for.
* @return true if trusted, false if untrusted.
*/
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction);
/**
* Return the saved public identity key for a remote client
*
* @param address The address of the remote client
* @return The public identity key, or null if absent
*/
public IdentityKey getIdentity(SignalProtocolAddress address);
}

View File

@@ -0,0 +1,101 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
/**
* A class that contains a remote PreKey and collection
* of associated items.
*
* @author Moxie Marlinspike
*/
public class PreKeyBundle {
private int registrationId;
private int deviceId;
private int preKeyId;
private ECPublicKey preKeyPublic;
private int signedPreKeyId;
private ECPublicKey signedPreKeyPublic;
private byte[] signedPreKeySignature;
private IdentityKey identityKey;
public PreKeyBundle(int registrationId, int deviceId, int preKeyId, ECPublicKey preKeyPublic,
int signedPreKeyId, ECPublicKey signedPreKeyPublic, byte[] signedPreKeySignature,
IdentityKey identityKey)
{
this.registrationId = registrationId;
this.deviceId = deviceId;
this.preKeyId = preKeyId;
this.preKeyPublic = preKeyPublic;
this.signedPreKeyId = signedPreKeyId;
this.signedPreKeyPublic = signedPreKeyPublic;
this.signedPreKeySignature = signedPreKeySignature;
this.identityKey = identityKey;
}
/**
* @return the device ID this PreKey belongs to.
*/
public int getDeviceId() {
return deviceId;
}
/**
* @return the unique key ID for this PreKey.
*/
public int getPreKeyId() {
return preKeyId;
}
/**
* @return the public key for this PreKey.
*/
public ECPublicKey getPreKey() {
return preKeyPublic;
}
/**
* @return the unique key ID for this signed prekey.
*/
public int getSignedPreKeyId() {
return signedPreKeyId;
}
/**
* @return the signed prekey for this PreKeyBundle.
*/
public ECPublicKey getSignedPreKey() {
return signedPreKeyPublic;
}
/**
* @return the signature over the signed prekey.
*/
public byte[] getSignedPreKeySignature() {
return signedPreKeySignature;
}
/**
* @return the {@link IdentityKey} of this PreKeys owner.
*/
public IdentityKey getIdentityKey() {
return identityKey;
}
/**
* @return the registration ID associated with this PreKey.
*/
public int getRegistrationId() {
return registrationId;
}
}

View File

@@ -0,0 +1,56 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import com.google.protobuf.ByteString;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import java.io.IOException;
import static org.session.libsignal.libsignal.state.StorageProtos.PreKeyRecordStructure;
public class PreKeyRecord {
private PreKeyRecordStructure structure;
public PreKeyRecord(int id, ECKeyPair keyPair) {
this.structure = PreKeyRecordStructure.newBuilder()
.setId(id)
.setPublicKey(ByteString.copyFrom(keyPair.getPublicKey()
.serialize()))
.setPrivateKey(ByteString.copyFrom(keyPair.getPrivateKey()
.serialize()))
.build();
}
public PreKeyRecord(byte[] serialized) throws IOException {
this.structure = PreKeyRecordStructure.parseFrom(serialized);
}
public int getId() {
return this.structure.getId();
}
public ECKeyPair getKeyPair() {
try {
ECPublicKey publicKey = Curve.decodePoint(this.structure.getPublicKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(this.structure.getPrivateKey().toByteArray());
return new ECKeyPair(publicKey, privateKey);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public byte[] serialize() {
return this.structure.toByteArray();
}
}

View File

@@ -0,0 +1,48 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.state.PreKeyRecord;
/**
* An interface describing the local storage of {@link PreKeyRecord}s.
*
* @author Moxie Marlinspike
*/
public interface PreKeyStore {
/**
* Load a local PreKeyRecord.
*
* @param preKeyId the ID of the local PreKeyRecord.
* @return the corresponding PreKeyRecord.
* @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
*/
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException;
/**
* Store a local PreKeyRecord.
*
* @param preKeyId the ID of the PreKeyRecord to store.
* @param record the PreKeyRecord.
*/
public void storePreKey(int preKeyId, PreKeyRecord record);
/**
* @param preKeyId A PreKeyRecord ID.
* @return true if the store has a record for the preKeyId, otherwise false.
*/
public boolean containsPreKey(int preKeyId);
/**
* Delete a PreKeyRecord from local storage.
*
* @param preKeyId The ID of the PreKeyRecord to remove.
*/
public void removePreKey(int preKeyId);
}

View File

@@ -0,0 +1,125 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.session.libsignal.libsignal.state.StorageProtos.RecordStructure;
import static org.session.libsignal.libsignal.state.StorageProtos.SessionStructure;
/**
* A SessionRecord encapsulates the state of an ongoing session.
*
* @author Moxie Marlinspike
*/
public class SessionRecord {
private static final int ARCHIVED_STATES_MAX_LENGTH = 40;
private SessionState sessionState = new SessionState();
private LinkedList<SessionState> previousStates = new LinkedList<SessionState>();
private boolean fresh = false;
public SessionRecord() {
this.fresh = true;
}
public SessionRecord(SessionState sessionState) {
this.sessionState = sessionState;
this.fresh = false;
}
public SessionRecord(byte[] serialized) throws IOException {
RecordStructure record = RecordStructure.parseFrom(serialized);
this.sessionState = new SessionState(record.getCurrentSession());
this.fresh = false;
for (SessionStructure previousStructure : record.getPreviousSessionsList()) {
previousStates.add(new SessionState(previousStructure));
}
}
public boolean hasSessionState(int version, byte[] aliceBaseKey) {
if (sessionState.getSessionVersion() == version &&
Arrays.equals(aliceBaseKey, sessionState.getAliceBaseKey()))
{
return true;
}
for (SessionState state : previousStates) {
if (state.getSessionVersion() == version &&
Arrays.equals(aliceBaseKey, state.getAliceBaseKey()))
{
return true;
}
}
return false;
}
public SessionState getSessionState() {
return sessionState;
}
/**
* @return the list of all currently maintained "previous" session states.
*/
public List<SessionState> getPreviousSessionStates() {
return previousStates;
}
public void removePreviousSessionStates() {
previousStates.clear();
}
public boolean isFresh() {
return fresh;
}
/**
* Move the current {@link SessionState} into the list of "previous" session states,
* and replace the current {@link org.session.libsignal.libsignal.state.SessionState}
* with a fresh reset instance.
*/
public void archiveCurrentState() {
promoteState(new SessionState());
}
public void promoteState(SessionState promotedState) {
this.previousStates.addFirst(sessionState);
this.sessionState = promotedState;
if (previousStates.size() > ARCHIVED_STATES_MAX_LENGTH) {
previousStates.removeLast();
}
}
public void setState(SessionState sessionState) {
this.sessionState = sessionState;
}
/**
* @return a serialized version of the current SessionRecord.
*/
public byte[] serialize() {
List<SessionStructure> previousStructures = new LinkedList<SessionStructure>();
for (SessionState previousState : previousStates) {
previousStructures.add(previousState.getStructure());
}
RecordStructure record = RecordStructure.newBuilder()
.setCurrentSession(sessionState.getStructure())
.addAllPreviousSessions(previousStructures)
.build();
return record.toByteArray();
}
}

View File

@@ -0,0 +1,503 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import com.google.protobuf.ByteString;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import org.session.libsignal.libsignal.kdf.HKDF;
import org.session.libsignal.libsignal.logging.Log;
import org.session.libsignal.libsignal.ratchet.ChainKey;
import org.session.libsignal.libsignal.ratchet.MessageKeys;
import org.session.libsignal.libsignal.ratchet.RootKey;
import org.session.libsignal.libsignal.state.StorageProtos.SessionStructure.Chain;
import org.session.libsignal.libsignal.state.StorageProtos.SessionStructure.PendingKeyExchange;
import org.session.libsignal.libsignal.state.StorageProtos.SessionStructure.PendingPreKey;
import org.session.libsignal.libsignal.util.Pair;
import org.session.libsignal.libsignal.util.guava.Optional;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import static org.session.libsignal.libsignal.state.StorageProtos.SessionStructure;
public class SessionState {
private static final int MAX_MESSAGE_KEYS = 2000;
private SessionStructure sessionStructure;
public SessionState() {
this.sessionStructure = SessionStructure.newBuilder().build();
}
public SessionState(SessionStructure sessionStructure) {
this.sessionStructure = sessionStructure;
}
public SessionState(SessionState copy) {
this.sessionStructure = copy.sessionStructure.toBuilder().build();
}
public SessionStructure getStructure() {
return sessionStructure;
}
public byte[] getAliceBaseKey() {
return this.sessionStructure.getAliceBaseKey().toByteArray();
}
public void setAliceBaseKey(byte[] aliceBaseKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setAliceBaseKey(ByteString.copyFrom(aliceBaseKey))
.build();
}
public void setSessionVersion(int version) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setSessionVersion(version)
.build();
}
public int getSessionVersion() {
int sessionVersion = this.sessionStructure.getSessionVersion();
if (sessionVersion == 0) return 2;
else return sessionVersion;
}
public void setRemoteIdentityKey(IdentityKey identityKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRemoteIdentityPublic(ByteString.copyFrom(identityKey.serialize()))
.build();
}
public void setLocalIdentityKey(IdentityKey identityKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setLocalIdentityPublic(ByteString.copyFrom(identityKey.serialize()))
.build();
}
public IdentityKey getRemoteIdentityKey() {
try {
if (!this.sessionStructure.hasRemoteIdentityPublic()) {
return null;
}
return new IdentityKey(this.sessionStructure.getRemoteIdentityPublic().toByteArray(), 0);
} catch (InvalidKeyException e) {
Log.w("SessionRecordV2", e);
return null;
}
}
public IdentityKey getLocalIdentityKey() {
try {
return new IdentityKey(this.sessionStructure.getLocalIdentityPublic().toByteArray(), 0);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public int getPreviousCounter() {
return sessionStructure.getPreviousCounter();
}
public void setPreviousCounter(int previousCounter) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setPreviousCounter(previousCounter)
.build();
}
public RootKey getRootKey() {
return new RootKey(HKDF.createFor(getSessionVersion()),
this.sessionStructure.getRootKey().toByteArray());
}
public void setRootKey(RootKey rootKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRootKey(ByteString.copyFrom(rootKey.getKeyBytes()))
.build();
}
public ECPublicKey getSenderRatchetKey() {
try {
return Curve.decodePoint(sessionStructure.getSenderChain().getSenderRatchetKey().toByteArray(), 0);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public ECKeyPair getSenderRatchetKeyPair() {
ECPublicKey publicKey = getSenderRatchetKey();
ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getSenderChain()
.getSenderRatchetKeyPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public boolean hasReceiverChain(ECPublicKey senderEphemeral) {
return getReceiverChain(senderEphemeral) != null;
}
public boolean hasSenderChain() {
return sessionStructure.hasSenderChain();
}
private Pair<Chain,Integer> getReceiverChain(ECPublicKey senderEphemeral) {
List<Chain> receiverChains = sessionStructure.getReceiverChainsList();
int index = 0;
for (Chain receiverChain : receiverChains) {
try {
ECPublicKey chainSenderRatchetKey = Curve.decodePoint(receiverChain.getSenderRatchetKey().toByteArray(), 0);
if (chainSenderRatchetKey.equals(senderEphemeral)) {
return new Pair<Chain, Integer>(receiverChain,index);
}
} catch (InvalidKeyException e) {
Log.w("SessionRecordV2", e);
}
index++;
}
return null;
}
public ChainKey getReceiverChainKey(ECPublicKey senderEphemeral) {
Pair<Chain,Integer> receiverChainAndIndex = getReceiverChain(senderEphemeral);
Chain receiverChain = receiverChainAndIndex.first();
if (receiverChain == null) {
return null;
} else {
return new ChainKey(HKDF.createFor(getSessionVersion()),
receiverChain.getChainKey().getKey().toByteArray(),
receiverChain.getChainKey().getIndex());
}
}
public void addReceiverChain(ECPublicKey senderRatchetKey, ChainKey chainKey) {
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain chain = Chain.newBuilder()
.setChainKey(chainKeyStructure)
.setSenderRatchetKey(ByteString.copyFrom(senderRatchetKey.serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder().addReceiverChains(chain).build();
if (this.sessionStructure.getReceiverChainsList().size() > 5) {
this.sessionStructure = this.sessionStructure.toBuilder()
.removeReceiverChains(0)
.build();
}
}
public void setSenderChain(ECKeyPair senderRatchetKeyPair, ChainKey chainKey) {
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain senderChain = Chain.newBuilder()
.setSenderRatchetKey(ByteString.copyFrom(senderRatchetKeyPair.getPublicKey().serialize()))
.setSenderRatchetKeyPrivate(ByteString.copyFrom(senderRatchetKeyPair.getPrivateKey().serialize()))
.setChainKey(chainKeyStructure)
.build();
this.sessionStructure = this.sessionStructure.toBuilder().setSenderChain(senderChain).build();
}
public ChainKey getSenderChainKey() {
Chain.ChainKey chainKeyStructure = sessionStructure.getSenderChain().getChainKey();
return new ChainKey(HKDF.createFor(getSessionVersion()),
chainKeyStructure.getKey().toByteArray(), chainKeyStructure.getIndex());
}
public void setSenderChainKey(ChainKey nextChainKey) {
Chain.ChainKey chainKey = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(nextChainKey.getKey()))
.setIndex(nextChainKey.getIndex())
.build();
Chain chain = sessionStructure.getSenderChain().toBuilder()
.setChainKey(chainKey).build();
this.sessionStructure = this.sessionStructure.toBuilder().setSenderChain(chain).build();
}
public boolean hasMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first();
if (chain == null) {
return false;
}
List<Chain.MessageKey> messageKeyList = chain.getMessageKeysList();
for (Chain.MessageKey messageKey : messageKeyList) {
if (messageKey.getIndex() == counter) {
return true;
}
}
return false;
}
public MessageKeys removeMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first();
if (chain == null) {
return null;
}
List<Chain.MessageKey> messageKeyList = new LinkedList<Chain.MessageKey>(chain.getMessageKeysList());
Iterator<Chain.MessageKey> messageKeyIterator = messageKeyList.iterator();
MessageKeys result = null;
while (messageKeyIterator.hasNext()) {
Chain.MessageKey messageKey = messageKeyIterator.next();
if (messageKey.getIndex() == counter) {
result = new MessageKeys(new SecretKeySpec(messageKey.getCipherKey().toByteArray(), "AES"),
new SecretKeySpec(messageKey.getMacKey().toByteArray(), "HmacSHA256"),
new IvParameterSpec(messageKey.getIv().toByteArray()),
messageKey.getIndex());
messageKeyIterator.remove();
break;
}
}
Chain updatedChain = chain.toBuilder().clearMessageKeys()
.addAllMessageKeys(messageKeyList)
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second(), updatedChain)
.build();
return result;
}
public void setMessageKeys(ECPublicKey senderEphemeral, MessageKeys messageKeys) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first();
Chain.MessageKey messageKeyStructure = Chain.MessageKey.newBuilder()
.setCipherKey(ByteString.copyFrom(messageKeys.getCipherKey().getEncoded()))
.setMacKey(ByteString.copyFrom(messageKeys.getMacKey().getEncoded()))
.setIndex(messageKeys.getCounter())
.setIv(ByteString.copyFrom(messageKeys.getIv().getIV()))
.build();
Chain.Builder updatedChain = chain.toBuilder().addMessageKeys(messageKeyStructure);
if (updatedChain.getMessageKeysCount() > MAX_MESSAGE_KEYS) {
updatedChain.removeMessageKeys(0);
}
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second(),
updatedChain.build())
.build();
}
public void setReceiverChainKey(ECPublicKey senderEphemeral, ChainKey chainKey) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first();
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain updatedChain = chain.toBuilder().setChainKey(chainKeyStructure).build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second(), updatedChain)
.build();
}
public void setPendingKeyExchange(int sequence,
ECKeyPair ourBaseKey,
ECKeyPair ourRatchetKey,
IdentityKeyPair ourIdentityKey)
{
PendingKeyExchange structure =
PendingKeyExchange.newBuilder()
.setSequence(sequence)
.setLocalBaseKey(ByteString.copyFrom(ourBaseKey.getPublicKey().serialize()))
.setLocalBaseKeyPrivate(ByteString.copyFrom(ourBaseKey.getPrivateKey().serialize()))
.setLocalRatchetKey(ByteString.copyFrom(ourRatchetKey.getPublicKey().serialize()))
.setLocalRatchetKeyPrivate(ByteString.copyFrom(ourRatchetKey.getPrivateKey().serialize()))
.setLocalIdentityKey(ByteString.copyFrom(ourIdentityKey.getPublicKey().serialize()))
.setLocalIdentityKeyPrivate(ByteString.copyFrom(ourIdentityKey.getPrivateKey().serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setPendingKeyExchange(structure)
.build();
}
public int getPendingKeyExchangeSequence() {
return sessionStructure.getPendingKeyExchange().getSequence();
}
public ECKeyPair getPendingKeyExchangeBaseKey() throws InvalidKeyException {
ECPublicKey publicKey = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
.getLocalBaseKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getPendingKeyExchange()
.getLocalBaseKeyPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public ECKeyPair getPendingKeyExchangeRatchetKey() throws InvalidKeyException {
ECPublicKey publicKey = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
.getLocalRatchetKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getPendingKeyExchange()
.getLocalRatchetKeyPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public IdentityKeyPair getPendingKeyExchangeIdentityKey() throws InvalidKeyException {
IdentityKey publicKey = new IdentityKey(sessionStructure.getPendingKeyExchange()
.getLocalIdentityKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getPendingKeyExchange()
.getLocalIdentityKeyPrivate()
.toByteArray());
return new IdentityKeyPair(publicKey, privateKey);
}
public boolean hasPendingKeyExchange() {
return sessionStructure.hasPendingKeyExchange();
}
public void setUnacknowledgedPreKeyMessage(Optional<Integer> preKeyId, int signedPreKeyId, ECPublicKey baseKey) {
PendingPreKey.Builder pending = PendingPreKey.newBuilder()
.setSignedPreKeyId(signedPreKeyId)
.setBaseKey(ByteString.copyFrom(baseKey.serialize()));
if (preKeyId.isPresent()) {
pending.setPreKeyId(preKeyId.get());
}
this.sessionStructure = this.sessionStructure.toBuilder()
.setPendingPreKey(pending.build())
.build();
}
public boolean hasUnacknowledgedPreKeyMessage() {
return this.sessionStructure.hasPendingPreKey();
}
public UnacknowledgedPreKeyMessageItems getUnacknowledgedPreKeyMessageItems() {
try {
Optional<Integer> preKeyId;
if (sessionStructure.getPendingPreKey().hasPreKeyId()) {
preKeyId = Optional.of(sessionStructure.getPendingPreKey().getPreKeyId());
} else {
preKeyId = Optional.absent();
}
return
new UnacknowledgedPreKeyMessageItems(preKeyId,
sessionStructure.getPendingPreKey().getSignedPreKeyId(),
Curve.decodePoint(sessionStructure.getPendingPreKey()
.getBaseKey()
.toByteArray(), 0));
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public void clearUnacknowledgedPreKeyMessage() {
this.sessionStructure = this.sessionStructure.toBuilder()
.clearPendingPreKey()
.build();
}
public void setRemoteRegistrationId(int registrationId) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRemoteRegistrationId(registrationId)
.build();
}
public int getRemoteRegistrationId() {
return this.sessionStructure.getRemoteRegistrationId();
}
public void setLocalRegistrationId(int registrationId) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setLocalRegistrationId(registrationId)
.build();
}
public int getLocalRegistrationId() {
return this.sessionStructure.getLocalRegistrationId();
}
public byte[] serialize() {
return sessionStructure.toByteArray();
}
public static class UnacknowledgedPreKeyMessageItems {
private final Optional<Integer> preKeyId;
private final int signedPreKeyId;
private final ECPublicKey baseKey;
public UnacknowledgedPreKeyMessageItems(Optional<Integer> preKeyId,
int signedPreKeyId,
ECPublicKey baseKey)
{
this.preKeyId = preKeyId;
this.signedPreKeyId = signedPreKeyId;
this.baseKey = baseKey;
}
public Optional<Integer> getPreKeyId() {
return preKeyId;
}
public int getSignedPreKeyId() {
return signedPreKeyId;
}
public ECPublicKey getBaseKey() {
return baseKey;
}
}
}

View File

@@ -0,0 +1,72 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import org.session.libsignal.libsignal.SignalProtocolAddress;
import org.session.libsignal.libsignal.state.SessionRecord;
import java.util.List;
/**
* The interface to the durable store of session state information
* for remote clients.
*
* @author Moxie Marlinspike
*/
public interface SessionStore {
/**
* Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
* or a new SessionRecord if one does not currently exist.
* <p>
* It is important that implementations return a copy of the current durable information. The
* returned SessionRecord may be modified, but those changes should not have an effect on the
* durable session state (what is returned by subsequent calls to this method) without the
* store method being called here first.
*
* @param address The name and device ID of the remote client.
* @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
* a new SessionRecord if one does not currently exist.
*/
public SessionRecord loadSession(SignalProtocolAddress address);
/**
* Returns all known devices with active sessions for a recipient
*
* @param name the name of the client.
* @return all known sub-devices with active sessions.
*/
public List<Integer> getSubDeviceSessions(String name);
/**
* Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
* @param address the address of the remote client.
* @param record the current SessionRecord for the remote client.
*/
public void storeSession(SignalProtocolAddress address, SessionRecord record);
/**
* Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
* @param address the address of the remote client.
* @return true if a {@link SessionRecord} exists, false otherwise.
*/
public boolean containsSession(SignalProtocolAddress address);
/**
* Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
*
* @param address the address of the remote client.
*/
public void deleteSession(SignalProtocolAddress address);
/**
* Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
*
* @param name the name of the remote client.
*/
public void deleteAllSessions(String name);
}

View File

@@ -0,0 +1,11 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
public interface SignalProtocolStore
extends IdentityKeyStore, PreKeyStore, SessionStore, SignedPreKeyStore
{
}

View File

@@ -0,0 +1,66 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import com.google.protobuf.ByteString;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.ecc.ECPrivateKey;
import org.session.libsignal.libsignal.ecc.ECPublicKey;
import java.io.IOException;
import static org.session.libsignal.libsignal.state.StorageProtos.SignedPreKeyRecordStructure;
public class SignedPreKeyRecord {
private SignedPreKeyRecordStructure structure;
public SignedPreKeyRecord(int id, long timestamp, ECKeyPair keyPair, byte[] signature) {
this.structure = SignedPreKeyRecordStructure.newBuilder()
.setId(id)
.setPublicKey(ByteString.copyFrom(keyPair.getPublicKey()
.serialize()))
.setPrivateKey(ByteString.copyFrom(keyPair.getPrivateKey()
.serialize()))
.setSignature(ByteString.copyFrom(signature))
.setTimestamp(timestamp)
.build();
}
public SignedPreKeyRecord(byte[] serialized) throws IOException {
this.structure = SignedPreKeyRecordStructure.parseFrom(serialized);
}
public int getId() {
return this.structure.getId();
}
public long getTimestamp() {
return this.structure.getTimestamp();
}
public ECKeyPair getKeyPair() {
try {
ECPublicKey publicKey = Curve.decodePoint(this.structure.getPublicKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(this.structure.getPrivateKey().toByteArray());
return new ECKeyPair(publicKey, privateKey);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public byte[] getSignature() {
return this.structure.getSignature().toByteArray();
}
public byte[] serialize() {
return this.structure.toByteArray();
}
}

View File

@@ -0,0 +1,53 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.state.SignedPreKeyRecord;
import java.util.List;
public interface SignedPreKeyStore {
/**
* Load a local SignedPreKeyRecord.
*
* @param signedPreKeyId the ID of the local SignedPreKeyRecord.
* @return the corresponding SignedPreKeyRecord.
* @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
*/
public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException;
/**
* Load all local SignedPreKeyRecords.
*
* @return All stored SignedPreKeyRecords.
*/
public List<SignedPreKeyRecord> loadSignedPreKeys();
/**
* Store a local SignedPreKeyRecord.
*
* @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
* @param record the SignedPreKeyRecord.
*/
public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record);
/**
* @param signedPreKeyId A SignedPreKeyRecord ID.
* @return true if the store has a record for the signedPreKeyId, otherwise false.
*/
public boolean containsSignedPreKey(int signedPreKeyId);
/**
* Delete a SignedPreKeyRecord from local storage.
*
* @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
*/
public void removeSignedPreKey(int signedPreKeyId);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,60 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state.impl;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.SignalProtocolAddress;
import org.session.libsignal.libsignal.state.IdentityKeyStore;
import java.util.HashMap;
import java.util.Map;
public class InMemoryIdentityKeyStore implements IdentityKeyStore {
private final Map<SignalProtocolAddress, IdentityKey> trustedKeys = new HashMap<SignalProtocolAddress, IdentityKey>();
private final IdentityKeyPair identityKeyPair;
private final int localRegistrationId;
public InMemoryIdentityKeyStore(IdentityKeyPair identityKeyPair, int localRegistrationId) {
this.identityKeyPair = identityKeyPair;
this.localRegistrationId = localRegistrationId;
}
@Override
public IdentityKeyPair getIdentityKeyPair() {
return identityKeyPair;
}
@Override
public int getLocalRegistrationId() {
return localRegistrationId;
}
@Override
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) {
IdentityKey existing = trustedKeys.get(address);
if (!identityKey.equals(existing)) {
trustedKeys.put(address, identityKey);
return true;
} else {
return false;
}
}
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
IdentityKey trusted = trustedKeys.get(address);
return (trusted == null || trusted.equals(identityKey));
}
@Override
public IdentityKey getIdentity(SignalProtocolAddress address) {
return trustedKeys.get(address);
}
}

View File

@@ -0,0 +1,47 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state.impl;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.state.PreKeyRecord;
import org.session.libsignal.libsignal.state.PreKeyStore;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class InMemoryPreKeyStore implements PreKeyStore {
private final Map<Integer, byte[]> store = new HashMap<Integer, byte[]>();
@Override
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
try {
if (!store.containsKey(preKeyId)) {
throw new InvalidKeyIdException("No such prekeyrecord!");
}
return new PreKeyRecord(store.get(preKeyId));
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
public void storePreKey(int preKeyId, PreKeyRecord record) {
store.put(preKeyId, record.serialize());
}
@Override
public boolean containsPreKey(int preKeyId) {
return store.containsKey(preKeyId);
}
@Override
public void removePreKey(int preKeyId) {
store.remove(preKeyId);
}
}

View File

@@ -0,0 +1,75 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state.impl;
import org.session.libsignal.libsignal.SignalProtocolAddress;
import org.session.libsignal.libsignal.state.SessionRecord;
import org.session.libsignal.libsignal.state.SessionStore;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class InMemorySessionStore implements SessionStore {
private Map<SignalProtocolAddress, byte[]> sessions = new HashMap<SignalProtocolAddress, byte[]>();
public InMemorySessionStore() {}
@Override
public synchronized SessionRecord loadSession(SignalProtocolAddress remoteAddress) {
try {
if (containsSession(remoteAddress)) {
return new SessionRecord(sessions.get(remoteAddress));
} else {
return new SessionRecord();
}
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
public synchronized List<Integer> getSubDeviceSessions(String name) {
List<Integer> deviceIds = new LinkedList<Integer>();
for (SignalProtocolAddress key : sessions.keySet()) {
if (key.getName().equals(name) &&
key.getDeviceId() != 1)
{
deviceIds.add(key.getDeviceId());
}
}
return deviceIds;
}
@Override
public synchronized void storeSession(SignalProtocolAddress address, SessionRecord record) {
sessions.put(address, record.serialize());
}
@Override
public synchronized boolean containsSession(SignalProtocolAddress address) {
return sessions.containsKey(address);
}
@Override
public synchronized void deleteSession(SignalProtocolAddress address) {
sessions.remove(address);
}
@Override
public synchronized void deleteAllSessions(String name) {
for (SignalProtocolAddress key : sessions.keySet()) {
if (key.getName().equals(name)) {
sessions.remove(key);
}
}
}
}

View File

@@ -0,0 +1,130 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state.impl;
import org.session.libsignal.libsignal.SignalProtocolAddress;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.state.SignalProtocolStore;
import org.session.libsignal.libsignal.state.PreKeyRecord;
import org.session.libsignal.libsignal.state.SessionRecord;
import org.session.libsignal.libsignal.state.SignedPreKeyRecord;
import java.util.List;
public class InMemorySignalProtocolStore implements SignalProtocolStore {
private final InMemoryPreKeyStore preKeyStore = new InMemoryPreKeyStore();
private final InMemorySessionStore sessionStore = new InMemorySessionStore();
private final InMemorySignedPreKeyStore signedPreKeyStore = new InMemorySignedPreKeyStore();
private final InMemoryIdentityKeyStore identityKeyStore;
public InMemorySignalProtocolStore(IdentityKeyPair identityKeyPair, int registrationId) {
this.identityKeyStore = new InMemoryIdentityKeyStore(identityKeyPair, registrationId);
}
@Override
public IdentityKeyPair getIdentityKeyPair() {
return identityKeyStore.getIdentityKeyPair();
}
@Override
public int getLocalRegistrationId() {
return identityKeyStore.getLocalRegistrationId();
}
@Override
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) {
return identityKeyStore.saveIdentity(address, identityKey);
}
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
return identityKeyStore.isTrustedIdentity(address, identityKey, direction);
}
@Override
public IdentityKey getIdentity(SignalProtocolAddress address) {
return identityKeyStore.getIdentity(address);
}
@Override
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
return preKeyStore.loadPreKey(preKeyId);
}
@Override
public void storePreKey(int preKeyId, PreKeyRecord record) {
preKeyStore.storePreKey(preKeyId, record);
}
@Override
public boolean containsPreKey(int preKeyId) {
return preKeyStore.containsPreKey(preKeyId);
}
@Override
public void removePreKey(int preKeyId) {
preKeyStore.removePreKey(preKeyId);
}
@Override
public SessionRecord loadSession(SignalProtocolAddress address) {
return sessionStore.loadSession(address);
}
@Override
public List<Integer> getSubDeviceSessions(String name) {
return sessionStore.getSubDeviceSessions(name);
}
@Override
public void storeSession(SignalProtocolAddress address, SessionRecord record) {
sessionStore.storeSession(address, record);
}
@Override
public boolean containsSession(SignalProtocolAddress address) {
return sessionStore.containsSession(address);
}
@Override
public void deleteSession(SignalProtocolAddress address) {
sessionStore.deleteSession(address);
}
@Override
public void deleteAllSessions(String name) {
sessionStore.deleteAllSessions(name);
}
@Override
public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
return signedPreKeyStore.loadSignedPreKey(signedPreKeyId);
}
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {
return signedPreKeyStore.loadSignedPreKeys();
}
@Override
public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
}
@Override
public boolean containsSignedPreKey(int signedPreKeyId) {
return signedPreKeyStore.containsSignedPreKey(signedPreKeyId);
}
@Override
public void removeSignedPreKey(int signedPreKeyId) {
signedPreKeyStore.removeSignedPreKey(signedPreKeyId);
}
}

View File

@@ -0,0 +1,64 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.state.impl;
import org.session.libsignal.libsignal.InvalidKeyIdException;
import org.session.libsignal.libsignal.state.SignedPreKeyRecord;
import org.session.libsignal.libsignal.state.SignedPreKeyStore;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class InMemorySignedPreKeyStore implements SignedPreKeyStore {
private final Map<Integer, byte[]> store = new HashMap<Integer, byte[]>();
@Override
public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
try {
if (!store.containsKey(signedPreKeyId)) {
throw new InvalidKeyIdException("No such signedprekeyrecord! " + signedPreKeyId);
}
return new SignedPreKeyRecord(store.get(signedPreKeyId));
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {
try {
List<SignedPreKeyRecord> results = new LinkedList<SignedPreKeyRecord>();
for (byte[] serialized : store.values()) {
results.add(new SignedPreKeyRecord(serialized));
}
return results;
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
store.put(signedPreKeyId, record.serialize());
}
@Override
public boolean containsSignedPreKey(int signedPreKeyId) {
return store.containsKey(signedPreKeyId);
}
@Override
public void removeSignedPreKey(int signedPreKeyId) {
store.remove(signedPreKeyId);
}
}

View File

@@ -0,0 +1,18 @@
package org.session.libsignal.libsignal.util;
public abstract class ByteArrayComparator {
protected int compare(byte[] left, byte[] right) {
for (int i = 0, j = 0; i < left.length && j < right.length; i++, j++) {
int a = (left[i] & 0xff);
int b = (right[j] & 0xff);
if (a != b) {
return a - b;
}
}
return left.length - right.length;
}
}

View File

@@ -0,0 +1,246 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
public class ByteUtil {
public static byte[] combine(byte[]... elements) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (byte[] element : elements) {
baos.write(element);
}
return baos.toByteArray();
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static byte[][] split(byte[] input, int firstLength, int secondLength) {
byte[][] parts = new byte[2][];
parts[0] = new byte[firstLength];
System.arraycopy(input, 0, parts[0], 0, firstLength);
parts[1] = new byte[secondLength];
System.arraycopy(input, firstLength, parts[1], 0, secondLength);
return parts;
}
public static byte[][] split(byte[] input, int firstLength, int secondLength, int thirdLength)
throws ParseException
{
if (input == null || firstLength < 0 || secondLength < 0 || thirdLength < 0 ||
input.length < firstLength + secondLength + thirdLength)
{
throw new ParseException("Input too small: " + (input == null ? null : Hex.toString(input)), 0);
}
byte[][] parts = new byte[3][];
parts[0] = new byte[firstLength];
System.arraycopy(input, 0, parts[0], 0, firstLength);
parts[1] = new byte[secondLength];
System.arraycopy(input, firstLength, parts[1], 0, secondLength);
parts[2] = new byte[thirdLength];
System.arraycopy(input, firstLength + secondLength, parts[2], 0, thirdLength);
return parts;
}
public static byte[] trim(byte[] input, int length) {
byte[] result = new byte[length];
System.arraycopy(input, 0, result, 0, result.length);
return result;
}
public static byte[] copyFrom(byte[] input) {
byte[] output = new byte[input.length];
System.arraycopy(input, 0, output, 0, output.length);
return output;
}
public static byte intsToByteHighAndLow(int highValue, int lowValue) {
return (byte)((highValue << 4 | lowValue) & 0xFF);
}
public static int highBitsToInt(byte value) {
return (value & 0xFF) >> 4;
}
public static int lowBitsToInt(byte value) {
return (value & 0xF);
}
public static int highBitsToMedium(int value) {
return (value >> 12);
}
public static int lowBitsToMedium(int value) {
return (value & 0xFFF);
}
public static byte[] shortToByteArray(int value) {
byte[] bytes = new byte[2];
shortToByteArray(bytes, 0, value);
return bytes;
}
public static int shortToByteArray(byte[] bytes, int offset, int value) {
bytes[offset+1] = (byte)value;
bytes[offset] = (byte)(value >> 8);
return 2;
}
public static int shortToLittleEndianByteArray(byte[] bytes, int offset, int value) {
bytes[offset] = (byte)value;
bytes[offset+1] = (byte)(value >> 8);
return 2;
}
public static byte[] mediumToByteArray(int value) {
byte[] bytes = new byte[3];
mediumToByteArray(bytes, 0, value);
return bytes;
}
public static int mediumToByteArray(byte[] bytes, int offset, int value) {
bytes[offset + 2] = (byte)value;
bytes[offset + 1] = (byte)(value >> 8);
bytes[offset] = (byte)(value >> 16);
return 3;
}
public static byte[] intToByteArray(int value) {
byte[] bytes = new byte[4];
intToByteArray(bytes, 0, value);
return bytes;
}
public static int intToByteArray(byte[] bytes, int offset, int value) {
bytes[offset + 3] = (byte)value;
bytes[offset + 2] = (byte)(value >> 8);
bytes[offset + 1] = (byte)(value >> 16);
bytes[offset] = (byte)(value >> 24);
return 4;
}
public static int intToLittleEndianByteArray(byte[] bytes, int offset, int value) {
bytes[offset] = (byte)value;
bytes[offset+1] = (byte)(value >> 8);
bytes[offset+2] = (byte)(value >> 16);
bytes[offset+3] = (byte)(value >> 24);
return 4;
}
public static byte[] longToByteArray(long l) {
byte[] bytes = new byte[8];
longToByteArray(bytes, 0, l);
return bytes;
}
public static int longToByteArray(byte[] bytes, int offset, long value) {
bytes[offset + 7] = (byte)value;
bytes[offset + 6] = (byte)(value >> 8);
bytes[offset + 5] = (byte)(value >> 16);
bytes[offset + 4] = (byte)(value >> 24);
bytes[offset + 3] = (byte)(value >> 32);
bytes[offset + 2] = (byte)(value >> 40);
bytes[offset + 1] = (byte)(value >> 48);
bytes[offset] = (byte)(value >> 56);
return 8;
}
public static int longTo4ByteArray(byte[] bytes, int offset, long value) {
bytes[offset + 3] = (byte)value;
bytes[offset + 2] = (byte)(value >> 8);
bytes[offset + 1] = (byte)(value >> 16);
bytes[offset + 0] = (byte)(value >> 24);
return 4;
}
public static int byteArrayToShort(byte[] bytes) {
return byteArrayToShort(bytes, 0);
}
public static int byteArrayToShort(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 8 | (bytes[offset + 1] & 0xff);
}
// The SSL patented 3-byte Value.
public static int byteArrayToMedium(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 16 |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset + 2] & 0xff);
}
public static int byteArrayToInt(byte[] bytes) {
return byteArrayToInt(bytes, 0);
}
public static int byteArrayToInt(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 24 |
(bytes[offset + 1] & 0xff) << 16 |
(bytes[offset + 2] & 0xff) << 8 |
(bytes[offset + 3] & 0xff);
}
public static int byteArrayToIntLittleEndian(byte[] bytes, int offset) {
return
(bytes[offset + 3] & 0xff) << 24 |
(bytes[offset + 2] & 0xff) << 16 |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset] & 0xff);
}
public static long byteArrayToLong(byte[] bytes) {
return byteArrayToLong(bytes, 0);
}
public static long byteArray4ToLong(byte[] bytes, int offset) {
return
((bytes[offset + 0] & 0xffL) << 24) |
((bytes[offset + 1] & 0xffL) << 16) |
((bytes[offset + 2] & 0xffL) << 8) |
((bytes[offset + 3] & 0xffL));
}
public static long byteArray5ToLong(byte[] bytes, int offset) {
return
((bytes[offset] & 0xffL) << 32) |
((bytes[offset + 1] & 0xffL) << 24) |
((bytes[offset + 2] & 0xffL) << 16) |
((bytes[offset + 3] & 0xffL) << 8) |
((bytes[offset + 4] & 0xffL));
}
public static long byteArrayToLong(byte[] bytes, int offset) {
return
((bytes[offset] & 0xffL) << 56) |
((bytes[offset + 1] & 0xffL) << 48) |
((bytes[offset + 2] & 0xffL) << 40) |
((bytes[offset + 3] & 0xffL) << 32) |
((bytes[offset + 4] & 0xffL) << 24) |
((bytes[offset + 5] & 0xffL) << 16) |
((bytes[offset + 6] & 0xffL) << 8) |
((bytes[offset + 7] & 0xffL));
}
}

View File

@@ -0,0 +1,67 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.util;
import java.io.IOException;
/**
* Utility for generating hex dumps.
*/
public class Hex {
private final static char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
public static String toString(byte[] bytes) {
return toString(bytes, 0, bytes.length);
}
public static String toString(byte[] bytes, int offset, int length) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < length; i++) {
appendHexChar(buf, bytes[offset + i]);
buf.append(", ");
}
return buf.toString();
}
public static String toStringCondensed(byte[] bytes) {
StringBuffer buf = new StringBuffer();
for (int i=0;i<bytes.length;i++) {
appendHexChar(buf, bytes[i]);
}
return buf.toString();
}
public static byte[] fromStringCondensed(String encoded) throws IOException {
final char[] data = encoded.toCharArray();
final int len = data.length;
if ((len & 0x01) != 0) {
throw new IOException("Odd number of characters.");
}
final byte[] out = new byte[len >> 1];
for (int i = 0, j = 0; j < len; i++) {
int f = Character.digit(data[j], 16) << 4;
j++;
f = f | Character.digit(data[j], 16);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
private static void appendHexChar(StringBuffer buf, int b) {
buf.append("(byte)0x");
buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.append(HEX_DIGITS[b & 0xf]);
}
}

View File

@@ -0,0 +1,13 @@
package org.session.libsignal.libsignal.util;
import org.session.libsignal.libsignal.IdentityKey;
import java.util.Comparator;
public class IdentityKeyComparator extends ByteArrayComparator implements Comparator<IdentityKey> {
@Override
public int compare(IdentityKey first, IdentityKey second) {
return compare(first.getPublicKey().serialize(), second.getPublicKey().serialize());
}
}

View File

@@ -0,0 +1,137 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.util;
import org.session.libsignal.libsignal.IdentityKey;
import org.session.libsignal.libsignal.IdentityKeyPair;
import org.session.libsignal.libsignal.InvalidKeyException;
import org.session.libsignal.libsignal.ecc.Curve;
import org.session.libsignal.libsignal.ecc.ECKeyPair;
import org.session.libsignal.libsignal.state.PreKeyRecord;
import org.session.libsignal.libsignal.state.SignedPreKeyRecord;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class for generating keys of different types.
*
* @author Moxie Marlinspike
*/
public class KeyHelper {
private KeyHelper() {}
/**
* Generate an identity key pair. Clients should only do this once,
* at install time.
*
* @return the generated IdentityKeyPair.
*/
public static IdentityKeyPair generateIdentityKeyPair() {
ECKeyPair keyPair = Curve.generateKeyPair();
IdentityKey publicKey = new IdentityKey(keyPair.getPublicKey());
return new IdentityKeyPair(publicKey, keyPair.getPrivateKey());
}
/**
* Generate a registration ID. Clients should only do this once,
* at install time.
*
* @param extendedRange By default (false), the generated registration
* ID is sized to require the minimal possible protobuf
* encoding overhead. Specify true if the caller needs
* the full range of MAX_INT at the cost of slightly
* higher encoding overhead.
* @return the generated registration ID.
*/
public static int generateRegistrationId(boolean extendedRange) {
try {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
if (extendedRange) return secureRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
else return secureRandom.nextInt(16380) + 1;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public static int getRandomSequence(int max) {
try {
return SecureRandom.getInstance("SHA1PRNG").nextInt(max);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
/**
* Generate a list of PreKeys. Clients should do this at install time, and
* subsequently any time the list of PreKeys stored on the server runs low.
* <p>
* PreKey IDs are shorts, so they will eventually be repeated. Clients should
* store PreKeys in a circular buffer, so that they are repeated as infrequently
* as possible.
*
* @param start The starting PreKey ID, inclusive.
* @param count The number of PreKeys to generate.
* @return the list of generated PreKeyRecords.
*/
public static List<PreKeyRecord> generatePreKeys(int start, int count) {
List<PreKeyRecord> results = new LinkedList<PreKeyRecord>();
start--;
for (int i=0;i<count;i++) {
results.add(new PreKeyRecord(((start + i) % (Medium.MAX_VALUE-1)) + 1, Curve.generateKeyPair()));
}
return results;
}
/**
* Generate a signed PreKey
*
* @param identityKeyPair The local client's identity key pair.
* @param signedPreKeyId The PreKey id to assign the generated signed PreKey
*
* @return the generated signed PreKey
* @throws InvalidKeyException when the provided identity key is invalid
*/
public static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair, int signedPreKeyId)
throws InvalidKeyException
{
ECKeyPair keyPair = Curve.generateKeyPair();
byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
return new SignedPreKeyRecord(signedPreKeyId, System.currentTimeMillis(), keyPair, signature);
}
public static ECKeyPair generateSenderSigningKey() {
return Curve.generateKeyPair();
}
public static byte[] generateSenderKey() {
try {
byte[] key = new byte[32];
SecureRandom.getInstance("SHA1PRNG").nextBytes(key);
return key;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public static int generateSenderKeyId() {
try {
return SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.util;
public class Medium {
public static int MAX_VALUE = 0xFFFFFF;
}

View File

@@ -0,0 +1,40 @@
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.session.libsignal.libsignal.util;
public class Pair<T1, T2> {
private final T1 v1;
private final T2 v2;
public Pair(T1 v1, T2 v2) {
this.v1 = v1;
this.v2 = v2;
}
public T1 first(){
return v1;
}
public T2 second(){
return v2;
}
public boolean equals(Object o) {
return o instanceof Pair &&
equal(((Pair) o).first(), first()) &&
equal(((Pair) o).second(), second());
}
public int hashCode() {
return first().hashCode() ^ second().hashCode();
}
private boolean equal(Object first, Object second) {
if (first == null && second == null) return true;
if (first == null || second == null) return false;
return first.equals(second);
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.session.libsignal.libsignal.util.guava;
import org.session.libsignal.libsignal.util.guava.Function;
import org.session.libsignal.libsignal.util.guava.Optional;
import org.session.libsignal.libsignal.util.guava.Supplier;
import static org.session.libsignal.libsignal.util.guava.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.Set;
/**
* Implementation of an {@link Optional} not containing a reference.
*/
final class Absent extends Optional<Object> {
static final Absent INSTANCE = new Absent();
@Override public boolean isPresent() {
return false;
}
@Override public Object get() {
throw new IllegalStateException("value is absent");
}
@Override public Object or(Object defaultValue) {
return checkNotNull(defaultValue, "use orNull() instead of or(null)");
}
@SuppressWarnings("unchecked") // safe covariant cast
@Override public Optional<Object> or(Optional<?> secondChoice) {
return (Optional) checkNotNull(secondChoice);
}
@Override public Object or(Supplier<?> supplier) {
return checkNotNull(supplier.get(),
"use orNull() instead of a Supplier that returns null");
}
@Override public Object orNull() {
return null;
}
@Override public Set<Object> asSet() {
return Collections.emptySet();
}
@Override
public <V> Optional<V> transform(Function<? super Object, V> function) {
checkNotNull(function);
return Optional.absent();
}
@Override public boolean equals(Object object) {
return object == this;
}
@Override public int hashCode() {
return 0x598df91c;
}
@Override public String toString() {
return "Optional.absent()";
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 0;
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.session.libsignal.libsignal.util.guava;
/**
* Determines an output value based on an input value.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
* Function}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
public interface Function<F, T> {
/**
* Returns the result of applying this function to {@code input}. This method is <i>generally
* expected</i>, but not absolutely required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (a, b)} implies that {@code Objects.equal(function.apply(a),
* function.apply(b))}.
* </ul>
*
* @throws NullPointerException if {@code input} is null and this function does not accept null
* arguments
*/
T apply(F input);
/**
* Indicates whether another object is equal to this function.
*
* <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
* However, an implementation may also choose to return {@code true} whenever {@code object} is a
* {@link Function} that it considers <i>interchangeable</i> with this one. "Interchangeable"
* <i>typically</i> means that {@code Objects.equal(this.apply(f), that.apply(f))} is true for all
* {@code f} of type {@code F}. Note that a {@code false} result from this method does not imply
* that the functions are known <i>not</i> to be interchangeable.
*/
@Override
boolean equals(Object object);
}

View File

@@ -0,0 +1,234 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.session.libsignal.libsignal.util.guava;
import org.session.libsignal.libsignal.util.guava.Supplier;
import static org.session.libsignal.libsignal.util.guava.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
/**
* An immutable object that may contain a non-null reference to another object. Each
* instance of this type either contains a non-null reference, or contains nothing (in
* which case we say that the reference is "absent"); it is never said to "contain {@code
* null}".
*
* <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable
* {@code T} reference. It allows you to represent "a {@code T} that must be present" and
* a "a {@code T} that might be absent" as two distinct types in your program, which can
* aid clarity.
*
* <p>Some uses of this class include
*
* <ul>
* <li>As a method return type, as an alternative to returning {@code null} to indicate
* that no value was available
* <li>To distinguish between "unknown" (for example, not present in a map) and "known to
* have no value" (present in the map, with value {@code Optional.absent()})
* <li>To wrap nullable references for storage in a collection that does not support
* {@code null} (though there are
* <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections">
* several other approaches to this</a> that should be considered first)
* </ul>
*
* <p>A common alternative to using this class is to find or create a suitable
* <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the
* type in question.
*
* <p>This class is not intended as a direct analogue of any existing "option" or "maybe"
* construct from other programming environments, though it may bear some similarities.
*
* <p>See the Guava User Guide article on <a
* href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional">
* using {@code Optional}</a>.
*
* @param <T> the type of instance that can be contained. {@code Optional} is naturally
* covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
* Optional<S>} for any supertype {@code S} of {@code T}.
* @author Kurt Alfred Kluever
* @author Kevin Bourrillion
* @since 10.0
*/
public abstract class Optional<T> implements Serializable {
/**
* Returns an {@code Optional} instance with no contained reference.
*/
@SuppressWarnings("unchecked")
public static <T> Optional<T> absent() {
return (Optional<T>) Absent.INSTANCE;
}
/**
* Returns an {@code Optional} instance containing the given non-null reference.
*/
public static <T> Optional<T> of(T reference) {
return new Present<T>(checkNotNull(reference));
}
/**
* If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
* reference; otherwise returns {@link Optional#absent}.
*/
public static <T> Optional<T> fromNullable(T nullableReference) {
return (nullableReference == null)
? Optional.<T>absent()
: new Present<T>(nullableReference);
}
Optional() {}
/**
* Returns {@code true} if this holder contains a (non-null) instance.
*/
public abstract boolean isPresent();
/**
* Returns the contained instance, which must be present. If the instance might be
* absent, use {@link #or(Object)} or {@link #orNull} instead.
*
* @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
* {@code false})
*/
public abstract T get();
/**
* Returns the contained instance if it is present; {@code defaultValue} otherwise. If
* no default value should be required because the instance is known to be present, use
* {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}.
*
* <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
* restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
* Java. As a result, some sensible operations involving subtypes are compile errors:
* <pre> {@code
*
* Optional<Integer> optionalInt = getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // error
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<? extends Number> first = numbers.first();
* Number value = first.or(0.5); // error}</pre>
*
* As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
* Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
* Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
* <pre> {@code
*
* Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // fine
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<Number> first = (Optional) numbers.first();
* Number value = first.or(0.5); // fine}</pre>
*/
public abstract T or(T defaultValue);
/**
* Returns this {@code Optional} if it has a value present; {@code secondChoice}
* otherwise.
*/
public abstract Optional<T> or(Optional<? extends T> secondChoice);
/**
* Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the
* supplier returns {@code null}, a {@link NullPointerException} is thrown.
*
* @throws NullPointerException if the supplier returns {@code null}
*/
public abstract T or(Supplier<? extends T> supplier);
/**
* Returns the contained instance if it is present; {@code null} otherwise. If the
* instance is known to be present, use {@link #get()} instead.
*/
public abstract T orNull();
/**
* Returns an immutable singleton {@link Set} whose only element is the contained instance
* if it is present; an empty immutable {@link Set} otherwise.
*
* @since 11.0
*/
public abstract Set<T> asSet();
/**
* If the instance is present, it is transformed with the given {@link Function}; otherwise,
* {@link Optional#absent} is returned. If the function returns {@code null}, a
* {@link NullPointerException} is thrown.
*
* @throws NullPointerException if the function returns {@code null}
*
* @since 12.0
*/
public abstract <V> Optional<V> transform(Function<? super T, V> function);
/**
* Returns {@code true} if {@code object} is an {@code Optional} instance, and either
* the contained references are {@linkplain Object#equals equal} to each other or both
* are absent. Note that {@code Optional} instances of differing parameterized types can
* be equal.
*/
@Override public abstract boolean equals(Object object);
/**
* Returns a hash code for this instance.
*/
@Override public abstract int hashCode();
/**
* Returns a string representation for this instance. The form of this string
* representation is unspecified.
*/
@Override public abstract String toString();
/**
* Returns the value of each present instance from the supplied {@code optionals}, in order,
* skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
* evaluated lazily.
*
* @since 11.0 (generics widened in 13.0)
*/
// public static <T> Iterable<T> presentInstances(
// final Iterable<? extends Optional<? extends T>> optionals) {
// checkNotNull(optionals);
// return new Iterable<T>() {
// @Override public Iterator<T> iterator() {
// return new AbstractIterator<T>() {
// private final Iterator<? extends Optional<? extends T>> iterator =
// checkNotNull(optionals.iterator());
//
// @Override protected T computeNext() {
// while (iterator.hasNext()) {
// Optional<? extends T> optional = iterator.next();
// if (optional.isPresent()) {
// return optional.get();
// }
// }
// return endOfData();
// }
// };
// };
// };
// }
private static final long serialVersionUID = 0;
}

View File

@@ -0,0 +1,447 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.session.libsignal.libsignal.util.guava;
import java.util.NoSuchElementException;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
*
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
*
* Note that the sense of the expression is inverted; with {@code Preconditions}
* you declare what you expect to be <i>true</i>, just as you do with an
* <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html">
* {@code assert}</a> or a JUnit {@code assertTrue} call.
*
* <p><b>Warning:</b> only the {@code "%s"} specifier is recognized as a
* placeholder in these messages, not the full range of {@link
* String#format(String, Object[])} specifiers.
*
* <p>Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link
* UnsupportedOperationException} and others -- are used to signal that the
* <i>calling method</i> has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps ever. Postcondition or other invariant failures should not throw
* these types of exceptions.
*
* <p>See the Guava User Guide on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">
* using {@code Preconditions}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(
boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkArgument(boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(
boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkState(boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate
* String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...));
* }
*
* The alternative natural refactorings into void or Exception-returning
* methods are much slower. This is a big deal - we're talking factors of
* 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer
* bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList.
* There is a RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this class want to throw different exceptions,
* depending on the args, so it appears that this pattern is not directly
* applicable. But we can use the ridiculous, devious trick of throwing an
* exception in the middle of the construction of another exception.
* Hotspot is fine with that.
*/
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(
int index, int size, String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
private static String badElementIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(
int index, int size, String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
private static String badPositionIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index > size
return format("%s (%s) must not be greater than size (%s)",
desc, index, size);
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
* in an array, list or string of size {@code size}, and are in order. A
* position index may range from zero to {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an
* array, list or string
* @param end a user-supplied index identifying a ending position in an array,
* list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is
* greater than {@code size}, or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badPositionIndexes(int start, int end, int size) {
if (start < 0 || start > size) {
return badPositionIndex(start, size, "start index");
}
if (end < 0 || end > size) {
return badPositionIndex(end, size, "end index");
}
// end < start
return format("end index (%s) must not be less than start index (%s)",
end, start);
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
static String format(String template,
Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.session.libsignal.libsignal.util.guava;
import org.session.libsignal.libsignal.util.guava.Function;
import org.session.libsignal.libsignal.util.guava.Optional;
import org.session.libsignal.libsignal.util.guava.Supplier;
import static org.session.libsignal.libsignal.util.guava.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.Set;
/**
* Implementation of an {@link Optional} containing a reference.
*/
final class Present<T> extends Optional<T> {
private final T reference;
Present(T reference) {
this.reference = reference;
}
@Override public boolean isPresent() {
return true;
}
@Override public T get() {
return reference;
}
@Override public T or(T defaultValue) {
checkNotNull(defaultValue, "use orNull() instead of or(null)");
return reference;
}
@Override public Optional<T> or(Optional<? extends T> secondChoice) {
checkNotNull(secondChoice);
return this;
}
@Override public T or(Supplier<? extends T> supplier) {
checkNotNull(supplier);
return reference;
}
@Override public T orNull() {
return reference;
}
@Override public Set<T> asSet() {
return Collections.singleton(reference);
}
@Override public <V> Optional<V> transform(Function<? super T, V> function) {
return new Present<V>(checkNotNull(function.apply(reference),
"Transformation function cannot return null."));
}
@Override public boolean equals(Object object) {
if (object instanceof Present) {
Present<?> other = (Present<?>) object;
return reference.equals(other.reference);
}
return false;
}
@Override public int hashCode() {
return 0x598df91c + reference.hashCode();
}
@Override public String toString() {
return "Optional.of(" + reference + ")";
}
private static final long serialVersionUID = 0;
}

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