├── settings.gradle ├── .gitignore ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ └── de │ │ └── thoffbauer │ │ └── signal4j │ │ └── store │ │ └── whisper.store │ └── java │ └── de │ └── thoffbauer │ └── signal4j │ ├── exceptions │ └── NoGroupFoundException.java │ ├── store │ ├── WhisperTrustStore.java │ ├── serialize │ │ ├── GroupIdKeyDeserializer.java │ │ ├── SignalProtocolAddressDeserializer.java │ │ ├── GroupIdKeySerializer.java │ │ ├── SignalProtocolAddressSerializer.java │ │ ├── GroupIdDeserializer.java │ │ ├── GroupIdSerializer.java │ │ ├── IdentityKeySerializer.java │ │ ├── PreKeyRecordDeserializer.java │ │ ├── PreKeyRecordSerializer.java │ │ ├── SessionRecordDeserializer.java │ │ ├── SessionRecordSerializer.java │ │ ├── IdentityKeyPairSerializer.java │ │ ├── SignedPreKeyRecordDeserializer.java │ │ ├── SignedPreKeyRecordSerializer.java │ │ ├── IdentityKeyDeserializer.java │ │ └── IdentityKeyPairDeserializer.java │ ├── DataStore.java │ ├── GroupId.java │ ├── User.java │ ├── Group.java │ ├── JsonDataStore.java │ ├── SignalStore.java │ └── JsonSignalStore.java │ ├── listener │ ├── SecurityExceptionListener.java │ └── ConversationListener.java │ ├── util │ ├── SecretUtil.java │ └── Base64.java │ └── SignalService.java ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'signal4j' 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle/ 3 | build/ 4 | 5 | # Eclipse 6 | .classpath 7 | .project 8 | .settings/ 9 | bin/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Turakar/signal4j/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/de/thoffbauer/signal4j/store/whisper.store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Turakar/signal4j/HEAD/src/main/resources/de/thoffbauer/signal4j/store/whisper.store -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 17 15:12:03 CEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip 7 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/exceptions/NoGroupFoundException.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.exceptions; 2 | 3 | import de.thoffbauer.signal4j.store.GroupId; 4 | 5 | @SuppressWarnings("serial") 6 | public class NoGroupFoundException extends Exception { 7 | 8 | private GroupId id; 9 | 10 | public NoGroupFoundException(String message, GroupId id) { 11 | super(message); 12 | this.id = id; 13 | } 14 | 15 | public GroupId getId() { 16 | return id; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/WhisperTrustStore.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | 4 | import java.io.InputStream; 5 | 6 | import org.whispersystems.signalservice.api.push.TrustStore; 7 | 8 | public class WhisperTrustStore implements TrustStore { 9 | 10 | @Override 11 | public InputStream getKeyStoreInputStream() { 12 | InputStream in = WhisperTrustStore.class.getResourceAsStream("whisper.store"); 13 | if(in == null) { 14 | throw new RuntimeException("Could not load whisper store!"); 15 | } 16 | return in; 17 | } 18 | 19 | @Override 20 | public String getKeyStorePassword() { 21 | return "whisper"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/GroupIdKeyDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.DeserializationContext; 7 | import com.fasterxml.jackson.databind.KeyDeserializer; 8 | 9 | import de.thoffbauer.signal4j.store.GroupId; 10 | import de.thoffbauer.signal4j.util.Base64; 11 | 12 | public class GroupIdKeyDeserializer extends KeyDeserializer { 13 | 14 | @Override 15 | public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { 16 | return new GroupId(Base64.decode(key)); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/listener/SecurityExceptionListener.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.listener; 2 | 3 | import de.thoffbauer.signal4j.store.User; 4 | 5 | public interface SecurityExceptionListener { 6 | 7 | /** 8 | * Called if a security relevant exception rises during message decrypting or attachment downloading. 9 | * The message will not be forwarded to the conversation listeners. 10 | * @param user the user from whom the invalid message came 11 | * @param e one of InvalidVersionException, InvalidMessageException, InvalidKeyException, DuplicateMessageException, InvalidKeyIdException, UntrustedIdentityException, UnregisteredUserException or LegacyMessageException 12 | */ 13 | void onSecurityException(User user, Exception e); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/DataStore.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Collection; 6 | import java.util.List; 7 | 8 | public abstract class DataStore { 9 | 10 | public abstract User getContact(String number); 11 | public abstract void addContact(User contact); 12 | public abstract void overwriteContacts(List contacts); 13 | public abstract Collection getContacts(); 14 | 15 | public abstract Group getGroup(GroupId id); 16 | public abstract void addGroup(Group group); 17 | public abstract void overwriteGroups(List groups); 18 | public abstract Collection getGroups(); 19 | 20 | public abstract void save(File file) throws IOException; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SignalProtocolAddressDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.SignalProtocolAddress; 6 | 7 | import com.fasterxml.jackson.core.JsonProcessingException; 8 | import com.fasterxml.jackson.databind.DeserializationContext; 9 | import com.fasterxml.jackson.databind.KeyDeserializer; 10 | 11 | public class SignalProtocolAddressDeserializer extends KeyDeserializer { 12 | 13 | @Override 14 | public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { 15 | String[] split = key.split("\\."); 16 | return new SignalProtocolAddress(split[0], Integer.valueOf(split[1])); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/GroupIdKeySerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import com.fasterxml.jackson.core.JsonGenerator; 6 | import com.fasterxml.jackson.databind.SerializerProvider; 7 | import com.fasterxml.jackson.databind.ser.std.StdKeySerializer; 8 | 9 | import de.thoffbauer.signal4j.store.GroupId; 10 | import de.thoffbauer.signal4j.util.Base64; 11 | 12 | @SuppressWarnings("serial") 13 | public class GroupIdKeySerializer extends StdKeySerializer { 14 | 15 | @Override 16 | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { 17 | GroupId id = (GroupId) value; 18 | jgen.writeFieldName(Base64.encodeBytes(id.getId())); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SignalProtocolAddressSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.SignalProtocolAddress; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerator; 8 | import com.fasterxml.jackson.databind.SerializerProvider; 9 | import com.fasterxml.jackson.databind.ser.std.StdKeySerializer; 10 | 11 | @SuppressWarnings("serial") 12 | public class SignalProtocolAddressSerializer extends StdKeySerializer { 13 | 14 | @Override 15 | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { 16 | SignalProtocolAddress address = (SignalProtocolAddress) value; 17 | jgen.writeFieldName(address.getName() + "." + address.getDeviceId()); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/util/SecretUtil.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.util; 2 | 3 | 4 | import java.security.NoSuchAlgorithmException; 5 | import java.security.SecureRandom; 6 | 7 | public class SecretUtil { 8 | public static String getSecret(int size) { 9 | byte[] secret = getSecretBytes(size); 10 | return Base64.encodeBytes(secret); 11 | } 12 | 13 | public static byte[] getSecretBytes(int size) { 14 | byte[] secret = new byte[size]; 15 | getSecureRandom().nextBytes(secret); 16 | return secret; 17 | } 18 | 19 | private static SecureRandom getSecureRandom() { 20 | try { 21 | return SecureRandom.getInstance("SHA1PRNG"); 22 | } catch (NoSuchAlgorithmException e) { 23 | throw new AssertionError(e); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/GroupIdDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import com.fasterxml.jackson.core.JsonParser; 6 | import com.fasterxml.jackson.core.JsonProcessingException; 7 | import com.fasterxml.jackson.databind.DeserializationContext; 8 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 9 | 10 | import de.thoffbauer.signal4j.store.GroupId; 11 | import de.thoffbauer.signal4j.util.Base64; 12 | 13 | @SuppressWarnings("serial") 14 | public class GroupIdDeserializer extends StdDeserializer { 15 | 16 | public GroupIdDeserializer() { 17 | super(GroupId.class); 18 | } 19 | 20 | @Override 21 | public GroupId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { 22 | return new GroupId(Base64.decode(p.getValueAsString())); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/GroupIdSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import com.fasterxml.jackson.core.JsonGenerationException; 6 | import com.fasterxml.jackson.core.JsonGenerator; 7 | import com.fasterxml.jackson.databind.SerializerProvider; 8 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 9 | 10 | import de.thoffbauer.signal4j.store.GroupId; 11 | import de.thoffbauer.signal4j.util.Base64; 12 | 13 | @SuppressWarnings("serial") 14 | public class GroupIdSerializer extends StdSerializer { 15 | 16 | public GroupIdSerializer() { 17 | super(GroupId.class); 18 | } 19 | 20 | @Override 21 | public void serialize(GroupId value, JsonGenerator jgen, SerializerProvider provider) 22 | throws IOException, JsonGenerationException { 23 | jgen.writeString(Base64.encodeBytes(value.getId())); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/IdentityKeySerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.IdentityKey; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerationException; 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.databind.SerializerProvider; 10 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class IdentityKeySerializer extends StdSerializer { 16 | 17 | public IdentityKeySerializer() { 18 | super(IdentityKey.class); 19 | } 20 | 21 | @Override 22 | public void serialize(IdentityKey value, JsonGenerator jgen, SerializerProvider provider) 23 | throws IOException, JsonGenerationException { 24 | jgen.writeString(Base64.encodeBytes(value.serialize())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/PreKeyRecordDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.PreKeyRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonParser; 8 | import com.fasterxml.jackson.core.JsonProcessingException; 9 | import com.fasterxml.jackson.databind.DeserializationContext; 10 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class PreKeyRecordDeserializer extends StdDeserializer { 16 | 17 | public PreKeyRecordDeserializer() { 18 | super(PreKeyRecord.class); 19 | } 20 | 21 | @Override 22 | public PreKeyRecord deserialize(JsonParser p, DeserializationContext ctxt) 23 | throws IOException, JsonProcessingException { 24 | return new PreKeyRecord(Base64.decode(p.getValueAsString())); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/PreKeyRecordSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.PreKeyRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerationException; 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.databind.SerializerProvider; 10 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class PreKeyRecordSerializer extends StdSerializer { 16 | 17 | public PreKeyRecordSerializer() { 18 | super(PreKeyRecord.class); 19 | } 20 | 21 | @Override 22 | public void serialize(PreKeyRecord value, JsonGenerator jgen, SerializerProvider provider) 23 | throws IOException, JsonGenerationException { 24 | jgen.writeString(Base64.encodeBytes(value.serialize())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SessionRecordDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.SessionRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonParser; 8 | import com.fasterxml.jackson.core.JsonProcessingException; 9 | import com.fasterxml.jackson.databind.DeserializationContext; 10 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class SessionRecordDeserializer extends StdDeserializer { 16 | 17 | public SessionRecordDeserializer() { 18 | super(SessionRecord.class); 19 | } 20 | 21 | @Override 22 | public SessionRecord deserialize(JsonParser p, DeserializationContext ctxt) 23 | throws IOException, JsonProcessingException { 24 | return new SessionRecord(Base64.decode(p.getValueAsString())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SessionRecordSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.SessionRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerationException; 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.databind.SerializerProvider; 10 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class SessionRecordSerializer extends StdSerializer { 16 | 17 | public SessionRecordSerializer() { 18 | super(SessionRecord.class); 19 | } 20 | 21 | @Override 22 | public void serialize(SessionRecord value, JsonGenerator jgen, SerializerProvider provider) 23 | throws IOException, JsonGenerationException { 24 | jgen.writeString(Base64.encodeBytes(value.serialize())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/IdentityKeyPairSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.IdentityKeyPair; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerationException; 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.databind.SerializerProvider; 10 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class IdentityKeyPairSerializer extends StdSerializer { 16 | 17 | public IdentityKeyPairSerializer() { 18 | super(IdentityKeyPair.class); 19 | } 20 | 21 | @Override 22 | public void serialize(IdentityKeyPair value, JsonGenerator jgen, SerializerProvider provider) 23 | throws IOException, JsonGenerationException { 24 | jgen.writeString(Base64.encodeBytes(value.serialize())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/GroupId.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.util.Arrays; 4 | 5 | public class GroupId { 6 | 7 | public static final int LENGTH = 16; 8 | 9 | private final byte[] id; 10 | 11 | public GroupId(byte[] id) { 12 | this.id = id; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "GroupId [id=" + Arrays.toString(id) + "]"; 18 | } 19 | 20 | @Override 21 | public int hashCode() { 22 | final int prime = 31; 23 | int result = 1; 24 | result = prime * result + Arrays.hashCode(id); 25 | return result; 26 | } 27 | 28 | @Override 29 | public boolean equals(Object obj) { 30 | if (this == obj) 31 | return true; 32 | if (obj == null) 33 | return false; 34 | if (getClass() != obj.getClass()) 35 | return false; 36 | GroupId other = (GroupId) obj; 37 | if (!Arrays.equals(id, other.id)) 38 | return false; 39 | return true; 40 | } 41 | 42 | public byte[] getId() { 43 | return id; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SignedPreKeyRecordDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonParser; 8 | import com.fasterxml.jackson.core.JsonProcessingException; 9 | import com.fasterxml.jackson.databind.DeserializationContext; 10 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class SignedPreKeyRecordDeserializer extends StdDeserializer { 16 | 17 | public SignedPreKeyRecordDeserializer() { 18 | super(SignedPreKeyRecord.class); 19 | } 20 | 21 | @Override 22 | public SignedPreKeyRecord deserialize(JsonParser p, DeserializationContext ctxt) 23 | throws IOException, JsonProcessingException { 24 | return new SignedPreKeyRecord(Base64.decode(p.getValueAsString())); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/SignedPreKeyRecordSerializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerationException; 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.databind.SerializerProvider; 10 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 11 | 12 | import de.thoffbauer.signal4j.util.Base64; 13 | 14 | @SuppressWarnings("serial") 15 | public class SignedPreKeyRecordSerializer extends StdSerializer { 16 | 17 | public SignedPreKeyRecordSerializer() { 18 | super(SignedPreKeyRecord.class); 19 | } 20 | 21 | @Override 22 | public void serialize(SignedPreKeyRecord value, JsonGenerator jgen, SerializerProvider provider) 23 | throws IOException, JsonGenerationException { 24 | jgen.writeString(Base64.encodeBytes(value.serialize())); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/IdentityKeyDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.IdentityKey; 6 | import org.whispersystems.libsignal.InvalidKeyException; 7 | 8 | import com.fasterxml.jackson.core.JsonParser; 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import com.fasterxml.jackson.databind.DeserializationContext; 11 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 12 | 13 | import de.thoffbauer.signal4j.util.Base64; 14 | 15 | @SuppressWarnings("serial") 16 | public class IdentityKeyDeserializer extends StdDeserializer { 17 | 18 | public IdentityKeyDeserializer() { 19 | super(IdentityKey.class); 20 | } 21 | 22 | @Override 23 | public IdentityKey deserialize(JsonParser p, DeserializationContext ctxt) 24 | throws IOException, JsonProcessingException { 25 | try { 26 | return new IdentityKey(Base64.decode(p.getValueAsString()), 0); 27 | } catch (InvalidKeyException e) { 28 | throw new RuntimeException(e); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/serialize/IdentityKeyPairDeserializer.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store.serialize; 2 | 3 | import java.io.IOException; 4 | 5 | import org.whispersystems.libsignal.IdentityKeyPair; 6 | import org.whispersystems.libsignal.InvalidKeyException; 7 | 8 | import com.fasterxml.jackson.core.JsonParser; 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import com.fasterxml.jackson.databind.DeserializationContext; 11 | import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 12 | 13 | import de.thoffbauer.signal4j.util.Base64; 14 | 15 | @SuppressWarnings("serial") 16 | public class IdentityKeyPairDeserializer extends StdDeserializer { 17 | 18 | public IdentityKeyPairDeserializer() { 19 | super(IdentityKeyPair.class); 20 | } 21 | 22 | @Override 23 | public IdentityKeyPair deserialize(JsonParser p, DeserializationContext ctxt) 24 | throws IOException, JsonProcessingException { 25 | String bytes = p.getValueAsString(); 26 | try { 27 | return new IdentityKeyPair(Base64.decode(bytes)); 28 | } catch (InvalidKeyException e) { 29 | throw new RuntimeException(e); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/listener/ConversationListener.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.listener; 2 | 3 | import java.util.List; 4 | 5 | import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage; 6 | import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage; 7 | 8 | import de.thoffbauer.signal4j.store.User; 9 | import de.thoffbauer.signal4j.store.Group; 10 | 11 | public interface ConversationListener { 12 | 13 | /** 14 | * Called every time we receive a message or another device of us sends a message 15 | * @param sender 16 | * @param message 17 | * @param group null if not in a group 18 | */ 19 | void onMessage(User sender, SignalServiceDataMessage message, Group group); 20 | 21 | /** 22 | * Called if the metadata of a contact changes. 23 | * @param contact the new contact 24 | */ 25 | void onContactUpdate(User contact); 26 | 27 | /** 28 | * Called if the metadata of a group changes. 29 | * @param sender who changed the group 30 | * @param group the new group 31 | */ 32 | void onGroupUpdate(User sender, Group group); 33 | 34 | /** 35 | * Send by another device of us once messages are read. Each {@code ReadMessage} contains 36 | * the timestamp and the sender of a read message. 37 | * @param readList 38 | */ 39 | void onReadUpdate(List readList); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/User.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact; 4 | 5 | public class User { 6 | 7 | private String number; 8 | private String name; 9 | private String avatarId; 10 | private String color; 11 | private boolean blocked = false; 12 | private int messageExpirationTime; 13 | 14 | public User() { 15 | 16 | } 17 | 18 | public User(String number) { 19 | this.number = number; 20 | } 21 | 22 | public User(DeviceContact of) { 23 | this.number = of.getNumber(); 24 | this.name = of.getName().orNull(); 25 | this.color = of.getColor().orNull(); 26 | } 27 | 28 | public String getNumber() { 29 | return number; 30 | } 31 | 32 | public void setNumber(String number) { 33 | this.number = number; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | public String getColor() { 45 | return color; 46 | } 47 | 48 | public void setColor(String color) { 49 | this.color = color; 50 | } 51 | 52 | public boolean isBlocked() { 53 | return blocked; 54 | } 55 | 56 | public void setBlocked(boolean blocked) { 57 | this.blocked = blocked; 58 | } 59 | 60 | public String getAvatarId() { 61 | return avatarId; 62 | } 63 | 64 | public void setAvatarId(String avatarId) { 65 | this.avatarId = avatarId; 66 | } 67 | 68 | public int getMessageExpirationTime() { 69 | return messageExpirationTime; 70 | } 71 | 72 | public void setMessageExpirationTime(int messageExpirationTime) { 73 | this.messageExpirationTime = messageExpirationTime; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/Group.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup; 6 | 7 | public class Group { 8 | 9 | private GroupId id; 10 | private String name; 11 | private ArrayList members; 12 | private String avatarId; 13 | private boolean active; 14 | private int messageExpirationTime; 15 | 16 | public Group() { 17 | 18 | } 19 | 20 | public Group(GroupId id) { 21 | this.id = id; 22 | } 23 | 24 | public Group(DeviceGroup of) { 25 | this.id = new GroupId(of.getId()); 26 | this.name = of.getName().orNull(); 27 | this.members = new ArrayList<>(of.getMembers()); 28 | this.active = of.isActive(); 29 | } 30 | 31 | public GroupId getId() { 32 | return id; 33 | } 34 | 35 | public void setId(GroupId id) { 36 | this.id = id; 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public void setName(String name) { 44 | this.name = name; 45 | } 46 | 47 | public ArrayList getMembers() { 48 | return members; 49 | } 50 | 51 | public void setMembers(ArrayList members) { 52 | this.members = members; 53 | } 54 | 55 | public boolean isActive() { 56 | return active; 57 | } 58 | 59 | public void setActive(boolean active) { 60 | this.active = active; 61 | } 62 | 63 | public String getAvatarId() { 64 | return avatarId; 65 | } 66 | 67 | public void setAvatarId(String avatarId) { 68 | this.avatarId = avatarId; 69 | } 70 | 71 | public int getMessageExpirationTime() { 72 | return messageExpirationTime; 73 | } 74 | 75 | public void setMessageExpirationTime(int messageExpirationTime) { 76 | this.messageExpirationTime = messageExpirationTime; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/JsonDataStore.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Collection; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | 9 | import com.fasterxml.jackson.annotation.JsonIgnore; 10 | import com.fasterxml.jackson.annotation.JsonProperty; 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | 13 | public class JsonDataStore extends DataStore { 14 | 15 | @JsonProperty 16 | private HashMap contacts = new HashMap<>(); 17 | @JsonProperty 18 | private HashMap groups = new HashMap<>(); 19 | 20 | @Override 21 | public void save(File file) throws IOException { 22 | ObjectMapper mapper = new ObjectMapper(); 23 | mapper.writeValue(file, this); 24 | } 25 | 26 | @Override 27 | public User getContact(String number) { 28 | return contacts.get(number); 29 | } 30 | 31 | @Override 32 | public void addContact(User contact) { 33 | contacts.put(contact.getNumber(), contact); 34 | } 35 | 36 | @Override 37 | public void overwriteContacts(List contacts) { 38 | this.contacts.clear(); 39 | for(User contact : contacts) { 40 | addContact(contact); 41 | } 42 | } 43 | 44 | @Override 45 | @JsonIgnore 46 | public Collection getContacts() { 47 | return contacts.values(); 48 | } 49 | 50 | @Override 51 | public Group getGroup(GroupId id) { 52 | return groups.get(id); 53 | } 54 | 55 | @Override 56 | public void addGroup(Group group) { 57 | groups.put(group.getId(), group); 58 | } 59 | 60 | @Override 61 | public void overwriteGroups(List groups) { 62 | this.groups.clear(); 63 | for(Group group : groups) { 64 | addGroup(group); 65 | } 66 | } 67 | 68 | @Override 69 | @JsonIgnore 70 | public Collection getGroups() { 71 | return groups.values(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # signal4j 2 | A facade to make using the libsignal-service easy 3 | 4 | ## Installation 5 | 6 | You have to have the JCE Unlimited Strength Policy Files installed if you are using the Oracle JRE. 7 | 8 | ### Gradle 9 | ```gradle 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | compile 'com.github.turakar:signal4j:1.0.0' 16 | } 17 | ``` 18 | ### Maven 19 | ```maven 20 | 21 | com.github.turakar 22 | signal4j 23 | 1.0.0 24 | 25 | ``` 26 | 27 | ## Usage 28 | Central part of the library is the `SignalService` class. 29 | 30 | ### Storage 31 | The library stores all your keys and metadata (not messages themself) inside the store `store.json`. The store is managed and saved on any changes by the library. To reset the state delete the store file. The saved contacts and groups are updated automatically on incoming messages. 32 | 33 | ### Register 34 | You can register as primary or secondary (provisioned) device using the methods `startConnectAsPrimary()`, `finishConnectAsPrimary()`, `startConnectAsSecondary()`, `finishConnectAsSecondary()`. See the javadoc for further details on this. You only have to do this at install time. Do not do this again without deleting the store file. 35 | 36 | ### PreKeys 37 | PreKeys are used for encryption and have to be generated prior to using them. Therefore you can use `checkPreKeys()` which has to be called regularly. 38 | 39 | ### Sync 40 | You can request a sync message (containing contacts, groups and blocked list) using `requestSync()`. This will populate the store file. 41 | 42 | ### Sending Messages 43 | Messages are represented by `SignalServiceDataMessage`. You can either create them using the constructors or using the builder. Attachments should be sent as `SignalServiceAttachmentStream`. To send a message use `sendMessage()`. 44 | 45 | ### Receiving Messages 46 | Receiving is done using `pull()` which is a blocking operation. Messages are processed using `ConversationListener` which has to be added prior to calling `pull()` using `addConversationListener()`. The `ConversationListener` receives all data messages through `onMessage()` (even the ones of another device of you) while associating `User` objects automatically to the sender's phone number. It additionally receives sync updates (those from `requestSync()` too) through `onContactUpdate()` and `onGroupUpdate()`. Using `onReadUpdate()` you can get read notifications from a different device of you. You cannot send read notifications yourself in the moment (WIP). Remember that read notifications are not transmitted to your contacts but only to the devices you use to manage notifications. 47 | #### Downloading attachments 48 | You can download attachments using `saveAttachment()`. The attachments are saved to the folder `attachments` and you get a `File` object pointing at it. There are convenience methods for getting a saved attachment (`getAttachment()`) and deleting a saved attachment (`deleteAttachment()`). The avatars of contacts and groups are downloaded automatically with the sync messages and therefore should be retrieved only using `getAttachment()`. Old avatars are automatically deleted once a new avatar arrives. 49 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/SignalStore.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.Iterator; 7 | import java.util.List; 8 | import java.util.Map.Entry; 9 | 10 | import org.whispersystems.libsignal.IdentityKey; 11 | import org.whispersystems.libsignal.IdentityKeyPair; 12 | import org.whispersystems.libsignal.SignalProtocolAddress; 13 | import org.whispersystems.libsignal.state.PreKeyRecord; 14 | import org.whispersystems.libsignal.state.SessionRecord; 15 | import org.whispersystems.libsignal.state.SignalProtocolStore; 16 | import org.whispersystems.signalservice.api.push.SignalServiceAddress; 17 | 18 | import com.fasterxml.jackson.annotation.JsonIgnore; 19 | 20 | public abstract class SignalStore implements SignalProtocolStore { 21 | 22 | @Override 23 | @JsonIgnore 24 | public boolean isTrustedIdentity(String name, IdentityKey identityKey) { 25 | IdentityKey storedIdentity = getIdentity(name); 26 | return storedIdentity == null || identityKey.equals(storedIdentity); 27 | } 28 | 29 | @Override 30 | @JsonIgnore 31 | public List getSubDeviceSessions(String name) { 32 | List ids = new ArrayList(); 33 | for(Entry entry : getSessions()) { 34 | SignalProtocolAddress address = entry.getKey(); 35 | if(address.getName().equals(name) && 36 | address.getDeviceId() != SignalServiceAddress.DEFAULT_DEVICE_ID) { 37 | ids.add(address.getDeviceId()); 38 | } 39 | } 40 | return ids; 41 | } 42 | 43 | @Override 44 | public void deleteAllSessions(String name) { 45 | for(Iterator> it = getSessions().iterator(); 46 | it.hasNext();) { 47 | if(it.next().getKey().getName().equals(name)) { 48 | it.remove(); 49 | } 50 | } 51 | } 52 | 53 | 54 | @Override 55 | public SessionRecord loadSession(SignalProtocolAddress address) { 56 | SessionRecord session = getSession(address); 57 | if(session == null) { 58 | session = new SessionRecord(); 59 | } 60 | return session; 61 | } 62 | 63 | public abstract void save(File file) throws IOException; 64 | 65 | public abstract DataStore getDataStore(); 66 | 67 | public abstract IdentityKey getIdentity(String name); 68 | public abstract Iterable> getSessions(); 69 | public abstract SessionRecord getSession(SignalProtocolAddress address); 70 | 71 | public abstract String getUrl(); 72 | public abstract void setUrl(String url); 73 | public abstract String getUserAgent(); 74 | public abstract void setUserAgent(String userAgent); 75 | public abstract String getPhoneNumber(); 76 | public abstract void setPhoneNumber(String phoneNumber); 77 | public abstract void setIdentityKeyPair(IdentityKeyPair identityKeyPair); 78 | public abstract String getPassword(); 79 | public abstract void setPassword(String password); 80 | public abstract String getSignalingKey(); 81 | public abstract void setSignalingKey(String signalingKey); 82 | public abstract int getDeviceId(); 83 | public abstract void setDeviceId(int deviceId); 84 | public abstract PreKeyRecord getLastResortPreKey(); 85 | public abstract void setLastResortPreKey(PreKeyRecord lastResortPreKey); 86 | public abstract void setLocalRegistrationId(int localRegistrationId); 87 | public abstract int getNextPreKeyId(); 88 | public abstract void setNextPreKeyId(int nextPreKeyId); 89 | public abstract int getNextSignedPreKeyId(); 90 | public abstract void setNextSignedPreKeyId(int nextSignedPreKeyId); 91 | } 92 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 165 | if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then 166 | cd "$(dirname "$0")" 167 | fi 168 | 169 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 170 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/store/JsonSignalStore.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.store; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map.Entry; 9 | 10 | import org.whispersystems.libsignal.IdentityKey; 11 | import org.whispersystems.libsignal.IdentityKeyPair; 12 | import org.whispersystems.libsignal.InvalidKeyIdException; 13 | import org.whispersystems.libsignal.SignalProtocolAddress; 14 | import org.whispersystems.libsignal.state.PreKeyRecord; 15 | import org.whispersystems.libsignal.state.SessionRecord; 16 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 17 | 18 | import com.fasterxml.jackson.annotation.JsonIgnore; 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.SerializationFeature; 22 | import com.fasterxml.jackson.databind.module.SimpleModule; 23 | 24 | import de.thoffbauer.signal4j.store.serialize.GroupIdDeserializer; 25 | import de.thoffbauer.signal4j.store.serialize.GroupIdKeyDeserializer; 26 | import de.thoffbauer.signal4j.store.serialize.GroupIdKeySerializer; 27 | import de.thoffbauer.signal4j.store.serialize.GroupIdSerializer; 28 | import de.thoffbauer.signal4j.store.serialize.IdentityKeyDeserializer; 29 | import de.thoffbauer.signal4j.store.serialize.IdentityKeyPairDeserializer; 30 | import de.thoffbauer.signal4j.store.serialize.IdentityKeyPairSerializer; 31 | import de.thoffbauer.signal4j.store.serialize.IdentityKeySerializer; 32 | import de.thoffbauer.signal4j.store.serialize.PreKeyRecordDeserializer; 33 | import de.thoffbauer.signal4j.store.serialize.PreKeyRecordSerializer; 34 | import de.thoffbauer.signal4j.store.serialize.SessionRecordDeserializer; 35 | import de.thoffbauer.signal4j.store.serialize.SessionRecordSerializer; 36 | import de.thoffbauer.signal4j.store.serialize.SignalProtocolAddressDeserializer; 37 | import de.thoffbauer.signal4j.store.serialize.SignalProtocolAddressSerializer; 38 | import de.thoffbauer.signal4j.store.serialize.SignedPreKeyRecordDeserializer; 39 | import de.thoffbauer.signal4j.store.serialize.SignedPreKeyRecordSerializer; 40 | 41 | public class JsonSignalStore extends SignalStore { 42 | 43 | @JsonProperty 44 | private IdentityKeyPair identityKeyPair; 45 | @JsonProperty 46 | private int registrationId; 47 | @JsonProperty 48 | private String password; 49 | @JsonProperty 50 | private String signalingKey; 51 | @JsonProperty 52 | private String phoneNumber; 53 | @JsonProperty 54 | private String userAgent; 55 | @JsonProperty 56 | private String url; 57 | @JsonProperty 58 | private int deviceId; 59 | @JsonProperty 60 | private PreKeyRecord lastResortPreKey; 61 | @JsonProperty 62 | private int nextPreKeyId; 63 | @JsonProperty 64 | private int nextSignedPreKeyId; 65 | 66 | @JsonProperty 67 | private HashMap identities = new HashMap<>(); 68 | @JsonProperty 69 | private HashMap preKeys = new HashMap<>(); 70 | @JsonProperty 71 | private HashMap signedPreKeys = new HashMap<>(); 72 | @JsonProperty 73 | private HashMap sessions = new HashMap<>(); 74 | 75 | @JsonProperty("data") 76 | private JsonDataStore dataStore = new JsonDataStore(); 77 | 78 | public static JsonSignalStore load(File file) throws IOException { 79 | SimpleModule module = new SimpleModule(); 80 | module.addDeserializer(IdentityKeyPair.class, new IdentityKeyPairDeserializer()); 81 | module.addDeserializer(IdentityKey.class, new IdentityKeyDeserializer()); 82 | module.addDeserializer(PreKeyRecord.class, new PreKeyRecordDeserializer()); 83 | module.addDeserializer(SignedPreKeyRecord.class, new SignedPreKeyRecordDeserializer()); 84 | module.addDeserializer(SessionRecord.class, new SessionRecordDeserializer()); 85 | module.addDeserializer(GroupId.class, new GroupIdDeserializer()); 86 | module.addKeyDeserializer(SignalProtocolAddress.class, new SignalProtocolAddressDeserializer()); 87 | module.addKeyDeserializer(GroupId.class, new GroupIdKeyDeserializer()); 88 | ObjectMapper mapper = new ObjectMapper(); 89 | mapper.registerModule(module); 90 | return mapper.readValue(file, JsonSignalStore.class); 91 | } 92 | 93 | public void save(File file) throws IOException { 94 | SimpleModule module = new SimpleModule(); 95 | module.addSerializer(IdentityKeyPair.class, new IdentityKeyPairSerializer()); 96 | module.addSerializer(IdentityKey.class, new IdentityKeySerializer()); 97 | module.addSerializer(PreKeyRecord.class, new PreKeyRecordSerializer()); 98 | module.addSerializer(SignedPreKeyRecord.class, new SignedPreKeyRecordSerializer()); 99 | module.addSerializer(SessionRecord.class, new SessionRecordSerializer()); 100 | module.addSerializer(GroupId.class, new GroupIdSerializer()); 101 | module.addKeySerializer(SignalProtocolAddress.class, new SignalProtocolAddressSerializer()); 102 | module.addKeySerializer(GroupId.class, new GroupIdKeySerializer()); 103 | ObjectMapper mapper = new ObjectMapper(); 104 | mapper.registerModule(module); 105 | mapper.enable(SerializationFeature.INDENT_OUTPUT); 106 | mapper.writeValue(file, this); 107 | } 108 | 109 | @Override 110 | public DataStore getDataStore() { 111 | return dataStore; 112 | } 113 | 114 | @Override 115 | @JsonIgnore 116 | public IdentityKeyPair getIdentityKeyPair() { 117 | return identityKeyPair; 118 | } 119 | 120 | @JsonIgnore 121 | public void setIdentityKeyPair(IdentityKeyPair identityKeyPair) { 122 | this.identityKeyPair = identityKeyPair; 123 | } 124 | 125 | @Override 126 | @JsonIgnore 127 | public int getLocalRegistrationId() { 128 | return registrationId; 129 | } 130 | 131 | @Override 132 | @JsonIgnore 133 | public void saveIdentity(String name, IdentityKey identityKey) { 134 | identities.put(name, identityKey); 135 | } 136 | 137 | @Override 138 | @JsonIgnore 139 | public IdentityKey getIdentity(String name) { 140 | return identities.get(name); 141 | } 142 | 143 | @Override 144 | @JsonIgnore 145 | public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException { 146 | PreKeyRecord record = preKeys.get(preKeyId); 147 | return record; 148 | } 149 | 150 | @Override 151 | @JsonIgnore 152 | public void storePreKey(int preKeyId, PreKeyRecord record) { 153 | preKeys.put(preKeyId, record); 154 | } 155 | 156 | @Override 157 | @JsonIgnore 158 | public boolean containsPreKey(int preKeyId) { 159 | return preKeys.containsKey(preKeyId); 160 | } 161 | 162 | @Override 163 | @JsonIgnore 164 | public void removePreKey(int preKeyId) { 165 | preKeys.remove(preKeyId); 166 | } 167 | 168 | @Override 169 | @JsonIgnore 170 | public SessionRecord getSession(SignalProtocolAddress address) { 171 | return sessions.get(address); 172 | } 173 | 174 | @Override 175 | @JsonIgnore 176 | public Iterable> getSessions() { 177 | return sessions.entrySet(); 178 | } 179 | 180 | @Override 181 | @JsonIgnore 182 | public void storeSession(SignalProtocolAddress address, SessionRecord record) { 183 | sessions.put(address, record); 184 | } 185 | 186 | @Override 187 | @JsonIgnore 188 | public boolean containsSession(SignalProtocolAddress address) { 189 | return sessions.containsKey(address); 190 | } 191 | 192 | @Override 193 | @JsonIgnore 194 | public void deleteSession(SignalProtocolAddress address) { 195 | sessions.remove(address); 196 | } 197 | 198 | @Override 199 | @JsonIgnore 200 | public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException { 201 | return signedPreKeys.get(signedPreKeyId); 202 | } 203 | 204 | @Override 205 | @JsonIgnore 206 | public List loadSignedPreKeys() { 207 | return new ArrayList(signedPreKeys.values()); 208 | } 209 | 210 | @Override 211 | @JsonIgnore 212 | public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) { 213 | signedPreKeys.put(signedPreKeyId, record); 214 | } 215 | 216 | @Override 217 | @JsonIgnore 218 | public boolean containsSignedPreKey(int signedPreKeyId) { 219 | return signedPreKeys.containsKey(signedPreKeyId); 220 | } 221 | 222 | @Override 223 | @JsonIgnore 224 | public void removeSignedPreKey(int signedPreKeyId) { 225 | signedPreKeys.remove(signedPreKeyId); 226 | } 227 | 228 | public String getPassword() { 229 | return password; 230 | } 231 | 232 | public void setPassword(String password) { 233 | this.password = password; 234 | } 235 | 236 | public String getSignalingKey() { 237 | return signalingKey; 238 | } 239 | 240 | public void setSignalingKey(String signalingKey) { 241 | this.signalingKey = signalingKey; 242 | } 243 | 244 | public String getPhoneNumber() { 245 | return phoneNumber; 246 | } 247 | 248 | public void setPhoneNumber(String phoneNumber) { 249 | this.phoneNumber = phoneNumber; 250 | } 251 | 252 | public String getUserAgent() { 253 | return userAgent; 254 | } 255 | 256 | public void setUserAgent(String userAgent) { 257 | this.userAgent = userAgent; 258 | } 259 | 260 | public String getUrl() { 261 | return url; 262 | } 263 | 264 | public void setUrl(String url) { 265 | this.url = url; 266 | } 267 | 268 | public int getDeviceId() { 269 | return deviceId; 270 | } 271 | 272 | public void setDeviceId(int deviceId) { 273 | this.deviceId = deviceId; 274 | } 275 | 276 | public void setLocalRegistrationId(int registrationId) { 277 | this.registrationId = registrationId; 278 | } 279 | 280 | public PreKeyRecord getLastResortPreKey() { 281 | return lastResortPreKey; 282 | } 283 | 284 | public void setLastResortPreKey(PreKeyRecord lastResortPreKey) { 285 | this.lastResortPreKey = lastResortPreKey; 286 | } 287 | 288 | public int getNextPreKeyId() { 289 | return nextPreKeyId; 290 | } 291 | 292 | public void setNextPreKeyId(int nextPreKeyId) { 293 | this.nextPreKeyId = nextPreKeyId; 294 | } 295 | 296 | public int getNextSignedPreKeyId() { 297 | return nextSignedPreKeyId; 298 | } 299 | 300 | public void setNextSignedPreKeyId(int nextSignedPreKeyId) { 301 | this.nextSignedPreKeyId = nextSignedPreKeyId; 302 | } 303 | 304 | } 305 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/SignalService.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.net.URLEncoder; 9 | import java.nio.file.Files; 10 | import java.nio.file.Paths; 11 | import java.nio.file.StandardCopyOption; 12 | import java.security.Security; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Random; 16 | import java.util.UUID; 17 | import java.util.concurrent.TimeUnit; 18 | import java.util.concurrent.TimeoutException; 19 | import java.util.stream.Collectors; 20 | 21 | import org.whispersystems.libsignal.DuplicateMessageException; 22 | import org.whispersystems.libsignal.IdentityKeyPair; 23 | import org.whispersystems.libsignal.InvalidKeyException; 24 | import org.whispersystems.libsignal.InvalidKeyIdException; 25 | import org.whispersystems.libsignal.InvalidMessageException; 26 | import org.whispersystems.libsignal.InvalidVersionException; 27 | import org.whispersystems.libsignal.LegacyMessageException; 28 | import org.whispersystems.libsignal.NoSessionException; 29 | import org.whispersystems.libsignal.ecc.Curve; 30 | import org.whispersystems.libsignal.state.PreKeyRecord; 31 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 32 | import org.whispersystems.libsignal.util.KeyHelper; 33 | import org.whispersystems.libsignal.util.Medium; 34 | import org.whispersystems.libsignal.util.guava.Optional; 35 | import org.whispersystems.signalservice.api.SignalServiceAccountManager; 36 | import org.whispersystems.signalservice.api.SignalServiceAccountManager.NewDeviceRegistrationReturn; 37 | import org.whispersystems.signalservice.api.SignalServiceMessagePipe; 38 | import org.whispersystems.signalservice.api.SignalServiceMessageReceiver; 39 | import org.whispersystems.signalservice.api.SignalServiceMessageSender; 40 | import org.whispersystems.signalservice.api.crypto.SignalServiceCipher; 41 | import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; 42 | import org.whispersystems.signalservice.api.messages.SignalServiceAttachment; 43 | import org.whispersystems.signalservice.api.messages.SignalServiceAttachment.ProgressListener; 44 | import org.whispersystems.signalservice.api.messages.SignalServiceContent; 45 | import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage; 46 | import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope; 47 | import org.whispersystems.signalservice.api.messages.SignalServiceGroup; 48 | import org.whispersystems.signalservice.api.messages.SignalServiceGroup.Type; 49 | import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage; 50 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact; 51 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream; 52 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup; 53 | import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsInputStream; 54 | import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage; 55 | import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage; 56 | import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage; 57 | import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; 58 | import org.whispersystems.signalservice.api.push.SignalServiceAddress; 59 | import org.whispersystems.signalservice.api.push.TrustStore; 60 | import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions; 61 | import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException; 62 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos.SyncMessage.Request; 63 | 64 | import de.thoffbauer.signal4j.exceptions.NoGroupFoundException; 65 | import de.thoffbauer.signal4j.listener.ConversationListener; 66 | import de.thoffbauer.signal4j.listener.SecurityExceptionListener; 67 | import de.thoffbauer.signal4j.store.DataStore; 68 | import de.thoffbauer.signal4j.store.Group; 69 | import de.thoffbauer.signal4j.store.GroupId; 70 | import de.thoffbauer.signal4j.store.JsonSignalStore; 71 | import de.thoffbauer.signal4j.store.SignalStore; 72 | import de.thoffbauer.signal4j.store.User; 73 | import de.thoffbauer.signal4j.store.WhisperTrustStore; 74 | import de.thoffbauer.signal4j.util.Base64; 75 | import de.thoffbauer.signal4j.util.SecretUtil; 76 | 77 | public class SignalService { 78 | 79 | /** 80 | * Path to main store file. Contains all keys etc. 81 | */ 82 | private final String STORE_PATH; 83 | /** 84 | * Folder to save attachments to 85 | */ 86 | private final String ATTACHMENTS_PATH; 87 | 88 | private static final int PASSWORD_LENGTH = 18; 89 | private static final int SIGNALING_KEY_LENGTH = 52; 90 | private static final int MAX_REGISTRATION_ID = 8192; 91 | private static final int PREKEYS_BATCH_SIZE = 100; 92 | private static final int MAX_PREKEY_ID = Medium.MAX_VALUE; 93 | 94 | private final TrustStore trustStore = new WhisperTrustStore(); 95 | 96 | private SignalServiceAccountManager accountManager; 97 | private SignalServiceMessageSender messageSender; 98 | private SignalServiceMessagePipe messagePipe; 99 | private SignalServiceMessageReceiver messageReceiver; 100 | private SignalServiceCipher cipher; 101 | private SignalStore store; 102 | private IdentityKeyPair tempIdentity; 103 | 104 | private ArrayList conversationListeners = new ArrayList<>(); 105 | private ArrayList securityExceptionListeners = new ArrayList<>(); 106 | 107 | /** 108 | * Create a new instance. This will load storePath as the data store if it exists, or create it if it doesn't. The attachments folder location path is also set via attachmentsPath. 109 | * @param storePath the path to the data store, ending in .json 110 | * @param attachmentsPath the path to the attachments folder, where attachments, avatars and general media is stored 111 | * @throws IOException can be thrown while loading the store 112 | */ 113 | public SignalService(String storePath, String attachmentsPath) throws IOException { 114 | // Add bouncycastle 115 | Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1); 116 | 117 | // Set location of store.json and attachments folder from arguments 118 | this.STORE_PATH = storePath; 119 | this.ATTACHMENTS_PATH = attachmentsPath; 120 | 121 | File storeFile = new File(STORE_PATH); 122 | if(storeFile.isFile()) { 123 | store = JsonSignalStore.load(storeFile); 124 | accountManager = new SignalServiceAccountManager(store.getUrl(), trustStore, store.getPhoneNumber(), 125 | store.getPassword(), store.getDeviceId(), store.getUserAgent()); 126 | } else { 127 | store = new JsonSignalStore(); 128 | } 129 | } 130 | 131 | /** 132 | * Create a new instance. No arguments will cause this constructor to set the store path to "store.json" and the attachments folder to "attachments". If "store.json" does not exist, it will be created. 133 | * @throws IOException can be thrown while loading the store 134 | */ 135 | public SignalService() throws IOException { 136 | this("store.json", "attachments"); 137 | } 138 | 139 | /** 140 | * Starts the connection and registration as the primary device. This creates a new Signal account with this number. 141 | * @param url the url of the signal server 142 | * @param userAgent human-readable name of the user agent 143 | * @param phoneNumber the user's phone number 144 | * @param voice whether to call (true) or to message (false) for verification 145 | * @throws IOException 146 | */ 147 | public void startConnectAsPrimary(String url, String userAgent, String phoneNumber, boolean voice) throws IOException { 148 | if(accountManager != null) { 149 | throw new IllegalStateException("Already started a connection!"); 150 | } 151 | store.setUrl(url); 152 | store.setUserAgent(userAgent); 153 | store.setPhoneNumber(phoneNumber); 154 | createPasswords(); 155 | store.setDeviceId(SignalServiceAddress.DEFAULT_DEVICE_ID); 156 | accountManager = new SignalServiceAccountManager(url, trustStore, phoneNumber, 157 | store.getPassword(), userAgent); 158 | if(voice) { 159 | accountManager.requestVoiceVerificationCode(); 160 | } else { 161 | accountManager.requestSmsVerificationCode(); 162 | } 163 | } 164 | 165 | /** 166 | * Finish the connection and registration as primary device with the received verification code 167 | * @param verificationCode the verification code without the - 168 | * @throws IOException 169 | */ 170 | public void finishConnectAsPrimary(String verificationCode) throws IOException { 171 | if(accountManager == null) { 172 | throw new IllegalStateException("Cannot finish: No connection started!"); 173 | } else if(isRegistered()) { 174 | throw new IllegalStateException("Already registered!"); 175 | } 176 | createRegistrationId(); 177 | accountManager.verifyAccountWithCode(verificationCode, store.getSignalingKey(), 178 | store.getLocalRegistrationId(), false, true); 179 | IdentityKeyPair identityKeyPair = KeyHelper.generateIdentityKeyPair(); 180 | store.setIdentityKeyPair(identityKeyPair); 181 | store.setLastResortPreKey(KeyHelper.generateLastResortPreKey()); 182 | checkPreKeys(-1); 183 | save(); 184 | } 185 | 186 | /** 187 | * Start connection and registration as secondary device. The device will be linked with the device scanning accepting the code. 188 | * @param url the url of the signal server 189 | * @param userAgent human-readable name of the user agent 190 | * @param phoneNumber the user's phone number 191 | * @return a url which must be shown as a QR code to the android app for provisioning 192 | * @throws IOException 193 | * @throws TimeoutException 194 | */ 195 | public String startConnectAsSecondary(String url, String userAgent, String phoneNumber) throws IOException, TimeoutException { 196 | if(accountManager != null) { 197 | throw new IllegalStateException("Already started a connection!"); 198 | } 199 | store.setUrl(url); 200 | store.setUserAgent(userAgent); 201 | store.setPhoneNumber(phoneNumber); 202 | createPasswords(); 203 | createRegistrationId(); 204 | accountManager = new SignalServiceAccountManager(url, trustStore, phoneNumber, 205 | store.getPassword(), userAgent); 206 | String uuid = accountManager.getNewDeviceUuid(); 207 | 208 | tempIdentity = KeyHelper.generateIdentityKeyPair(); 209 | byte[] publicKeyBytes = tempIdentity.getPublicKey().serialize(); 210 | String publicKeyBase64 = Base64.encodeBytesWithoutPadding(publicKeyBytes); 211 | 212 | String qrString = "tsdevice:/?uuid=" + URLEncoder.encode(uuid, "UTF-8") + 213 | "&pub_key=" + URLEncoder.encode(publicKeyBase64, "UTF-8"); 214 | return qrString; 215 | } 216 | 217 | /** 218 | * Blocking call. Call this directly after {@code startConnectAsSecondary()} and this method will wait 219 | * for the master device accepting this device. 220 | * @param deviceName a name for this device (not the user agent) 221 | * @param supportsSms whether this device can receive and send SMS 222 | * @throws IOException 223 | * @throws TimeoutException 224 | */ 225 | public void finishConnectAsSecondary(String deviceName, boolean supportsSms) throws IOException, TimeoutException { 226 | if(accountManager == null) { 227 | throw new IllegalStateException("Cannot finish: No connection started!"); 228 | } else if(isRegistered()) { 229 | throw new IllegalStateException("Already registered!"); 230 | } 231 | try { 232 | NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(tempIdentity, 233 | store.getSignalingKey(), supportsSms, true, store.getLocalRegistrationId(), deviceName); 234 | store.setDeviceId(ret.getDeviceId()); 235 | store.setIdentityKeyPair(ret.getIdentity()); 236 | } catch (InvalidKeyException e) { 237 | throw new RuntimeException("This can not happen - theoretically", e); 238 | } 239 | store.setLastResortPreKey(KeyHelper.generateLastResortPreKey()); 240 | checkPreKeys(-1); 241 | save(); 242 | } 243 | 244 | /** 245 | * Send a data, i.e. "normal" message 246 | * @param address 247 | * @param message 248 | * @throws IOException 249 | */ 250 | public void sendMessage(String address, SignalServiceDataMessage message) throws IOException { 251 | checkRegistered(); 252 | checkMessageSender(); 253 | try { 254 | messageSender.sendMessage(new SignalServiceAddress(address), message); 255 | } catch (UntrustedIdentityException e) { 256 | fireSecurityException(new SignalServiceAddress(address), e); 257 | } 258 | save(); 259 | } 260 | 261 | /** 262 | * Send a data, i.e. "normal" message to a group 263 | * @param addresses 264 | * @param message 265 | * @throws IOException 266 | */ 267 | public void sendMessage(List addresses, SignalServiceDataMessage message) throws IOException { 268 | checkRegistered(); 269 | checkMessageSender(); 270 | List signalServiceAddresses = addresses.stream() 271 | .filter(v -> !v.equals(store.getPhoneNumber())) 272 | .map(v -> new SignalServiceAddress(v)) 273 | .collect(Collectors.toList()); 274 | try { 275 | messageSender.sendMessage(signalServiceAddresses, message); 276 | } catch (EncapsulatedExceptions e) { 277 | for(UntrustedIdentityException ex : e.getUntrustedIdentityExceptions()) { 278 | fireSecurityException(new SignalServiceAddress(ex.getE164Number()), ex); 279 | } 280 | for(UnregisteredUserException ex : e.getUnregisteredUserExceptions()) { 281 | fireSecurityException(new SignalServiceAddress(ex.getE164Number()), ex); 282 | } 283 | if(!e.getNetworkExceptions().isEmpty()) { 284 | throw new IOException(e.getNetworkExceptions().size() + " network exception(s)! One is following.", 285 | e.getNetworkExceptions().get(0)); 286 | } 287 | } 288 | save(); 289 | } 290 | 291 | /** 292 | * Notify other devices that these messages have been read. 293 | * @param messages 294 | * @throws IOException 295 | */ 296 | public void markRead(List messages) throws IOException { 297 | checkRegistered(); 298 | checkMessageSender(); 299 | try { 300 | SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forRead(messages); 301 | messageSender.sendMessage(syncMessage); 302 | } catch (UntrustedIdentityException e) { 303 | fireSecurityException(new SignalServiceAddress(store.getPhoneNumber()), e); 304 | } 305 | } 306 | 307 | /** 308 | * Request sync messages from primary device. They are received using the listeners 309 | * @throws IOException 310 | * @throws UntrustedIdentityException 311 | */ 312 | public void requestSync() throws IOException { 313 | try { 314 | checkRegistered(); 315 | checkMessageSender(); 316 | Request.Type[] types = new Request.Type[] {Request.Type.CONTACTS, Request.Type.GROUPS, Request.Type.BLOCKED}; 317 | for(Request.Type type : types) { 318 | RequestMessage request = new RequestMessage(Request.newBuilder().setType(type).build()); 319 | SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forRequest(request); 320 | messageSender.sendMessage(syncMessage); 321 | } 322 | } catch(UntrustedIdentityException e) { 323 | fireSecurityException(new SignalServiceAddress(store.getPhoneNumber()), e); 324 | } 325 | } 326 | 327 | private void checkMessageSender() { 328 | if(messageSender == null) { 329 | messageSender = new SignalServiceMessageSender(store.getUrl(), trustStore, 330 | store.getPhoneNumber(), store.getPassword(), store.getDeviceId(), store, 331 | store.getUserAgent(), Optional.absent()); 332 | } 333 | } 334 | 335 | private void checkRegistered() { 336 | if(!isRegistered()) { 337 | throw new IllegalStateException("Not registered!"); 338 | } 339 | } 340 | 341 | /** 342 | * Returns true if this device is registered. This does not necessarily 343 | * mean that no other device has registered with this number. 344 | * @return whether this device is registered 345 | */ 346 | public boolean isRegistered() { 347 | return store.getIdentityKeyPair() != null; 348 | } 349 | 350 | private void createPasswords() { 351 | String password = SecretUtil.getSecret(PASSWORD_LENGTH); 352 | store.setPassword(password); 353 | String signalingKey= SecretUtil.getSecret(SIGNALING_KEY_LENGTH); 354 | store.setSignalingKey(signalingKey); 355 | } 356 | 357 | private void createRegistrationId() { 358 | int registrationId = new Random().nextInt(MAX_REGISTRATION_ID); 359 | store.setLocalRegistrationId(registrationId); 360 | } 361 | 362 | /** 363 | * Saves the store. As this is done automatically inside the library, 364 | * you only need to call this if you change something manually. 365 | * @throws IOException 366 | */ 367 | public void save() throws IOException { 368 | store.save(new File(STORE_PATH)); 369 | } 370 | 371 | public void addConversationListener(ConversationListener listener) { 372 | conversationListeners.add(listener); 373 | } 374 | 375 | public void removeConversationListener(ConversationListener listener) { 376 | conversationListeners.remove(listener); 377 | } 378 | 379 | /** 380 | * Add a listener for exceptions regarding the security of communication. 381 | * @param listener 382 | */ 383 | public void addSecurityExceptionListener(SecurityExceptionListener listener) { 384 | securityExceptionListeners.add(listener); 385 | } 386 | 387 | /** 388 | * Remove a security exception listener 389 | * @param listener 390 | */ 391 | public void removeSecurityExceptionListener(SecurityExceptionListener listener) { 392 | securityExceptionListeners.remove(listener); 393 | } 394 | 395 | /** 396 | * Wait for incoming messages. This method returns silently if the timeout passes. 397 | * If a message arrives, the conversation listeners are called and the method returns. 398 | * @param timeoutMillis time to wait for messages 399 | * @throws IOException 400 | */ 401 | public void pull(int timeoutMillis) throws IOException { 402 | checkRegistered(); 403 | if(messagePipe == null) { 404 | messageReceiver = new SignalServiceMessageReceiver(store.getUrl(), 405 | trustStore, store.getPhoneNumber(), store.getPassword(), store.getDeviceId(), 406 | store.getSignalingKey(), store.getUserAgent()); 407 | messagePipe = messageReceiver.createMessagePipe(); 408 | } 409 | SignalServiceEnvelope envelope = null; 410 | try { 411 | try { 412 | envelope = messagePipe.read(timeoutMillis, TimeUnit.MILLISECONDS); 413 | } catch (TimeoutException e) { 414 | return; 415 | } 416 | if(!envelope.isReceipt() && (envelope.hasContent() || envelope.hasLegacyMessage())) { 417 | if(cipher == null) { 418 | cipher = new SignalServiceCipher(new SignalServiceAddress(store.getPhoneNumber()), store); 419 | } 420 | SignalServiceContent content = cipher.decrypt(envelope); 421 | if(content.getDataMessage().isPresent()) { 422 | SignalServiceDataMessage dataMessage = content.getDataMessage().get(); 423 | handleDataMessage(envelope, dataMessage); 424 | } else if(content.getSyncMessage().isPresent()) { 425 | SignalServiceSyncMessage syncMessage = content.getSyncMessage().get(); 426 | handleSyncMessage(envelope, syncMessage); 427 | } 428 | } 429 | save(); 430 | } catch (InvalidVersionException | InvalidMessageException | InvalidKeyException | DuplicateMessageException | InvalidKeyIdException | org.whispersystems.libsignal.UntrustedIdentityException | LegacyMessageException e) { 431 | fireSecurityException(envelope != null ? envelope.getSourceAddress() : null, e); 432 | } catch(NoSessionException e) { 433 | throw new RuntimeException("The store file seems to be corrupt!", e); 434 | } 435 | } 436 | 437 | private void handleDataMessage(SignalServiceEnvelope envelope, SignalServiceDataMessage dataMessage) throws IOException { 438 | Group group = null; 439 | if(dataMessage.getGroupInfo().isPresent()) { 440 | SignalServiceGroup groupInfo = dataMessage.getGroupInfo().get(); 441 | GroupId id = new GroupId(groupInfo.getGroupId()); 442 | group = store.getDataStore().getGroup(id); 443 | if(groupInfo.getType() == SignalServiceGroup.Type.UPDATE) { 444 | if(group == null) { 445 | group = new Group(id); 446 | group.setActive(true); 447 | store.getDataStore().addGroup(group); 448 | } 449 | if(groupInfo.getName().isPresent()) { 450 | group.setName(groupInfo.getName().get()); 451 | } 452 | if(groupInfo.getMembers().isPresent()) { 453 | group.setMembers(new ArrayList<>(groupInfo.getMembers().get())); 454 | } 455 | if(groupInfo.getAvatar().isPresent()) { 456 | SignalServiceAttachment attachment = groupInfo.getAvatar().get(); 457 | String avatarId = UUID.randomUUID().toString(); 458 | saveAttachment(toUser(envelope.getSourceAddress()), attachment, null, avatarId); 459 | if(group.getAvatarId() != null) { 460 | deleteAttachment(group.getAvatarId()); 461 | } 462 | group.setAvatarId(avatarId); 463 | } 464 | fireGroupUpdate(envelope.getSourceAddress(), group); 465 | } else if(groupInfo.getType() == SignalServiceGroup.Type.QUIT) { 466 | if(group != null) { 467 | if(envelope.getSourceAddress().getNumber().equals(store.getPhoneNumber())) { 468 | group.setActive(false); 469 | } 470 | group.getMembers().remove(envelope.getSourceAddress().getNumber()); 471 | fireGroupUpdate(envelope.getSourceAddress(), group); 472 | } 473 | } else { 474 | if(group == null) { 475 | fireSecurityException(envelope.getSourceAddress(), new NoGroupFoundException("No group known for ID", id)); 476 | } 477 | } 478 | } 479 | 480 | if (dataMessage.isExpirationUpdate() || dataMessage.getBody().isPresent()) { 481 | if(group != null) { 482 | group.setMessageExpirationTime(dataMessage.getExpiresInSeconds()); 483 | } else { 484 | User user = toUser(envelope.getSourceAddress()); 485 | user.setMessageExpirationTime(dataMessage.getExpiresInSeconds()); 486 | } 487 | } 488 | 489 | 490 | fireMessage(envelope.getSourceAddress(), dataMessage,group); 491 | 492 | } 493 | 494 | private void handleSyncMessage(SignalServiceEnvelope envelope, SignalServiceSyncMessage syncMessage) 495 | throws IOException, FileNotFoundException { 496 | if(syncMessage.getContacts().isPresent()) { 497 | File file = saveAttachment(envelope.getSourceAddress(), syncMessage.getContacts().get(), null); 498 | DeviceContactsInputStream in = new DeviceContactsInputStream(new FileInputStream(file)); 499 | ArrayList contacts = new ArrayList<>(); 500 | while(true) { 501 | DeviceContact deviceContact = in.read(); 502 | if(deviceContact == null) { 503 | //EOF 504 | break; 505 | } 506 | User contact = new User(deviceContact); 507 | contacts.add(contact); 508 | if(deviceContact.getAvatar().isPresent()) { 509 | String id = UUID.randomUUID().toString(); 510 | saveAttachment(toUser(envelope.getSourceAddress()), deviceContact.getAvatar().get(), 511 | null, id); 512 | contact.setAvatarId(id); 513 | } 514 | } 515 | file.delete(); 516 | store.getDataStore().getContacts().stream() 517 | .filter(v -> v.getAvatarId() != null) 518 | .forEach(v -> deleteAttachment(v.getAvatarId())); 519 | store.getDataStore().overwriteContacts(contacts); 520 | for(User contact : contacts) { 521 | fireContactUpdate(contact); 522 | } 523 | } else if(syncMessage.getGroups().isPresent()) { 524 | File file = saveAttachment(envelope.getSourceAddress(), syncMessage.getGroups().get(), null); 525 | DeviceGroupsInputStream in = new DeviceGroupsInputStream(new FileInputStream(file)); 526 | List groups = new ArrayList<>(); 527 | while(true) { 528 | DeviceGroup deviceGroup = in.read(); 529 | if(deviceGroup == null) { 530 | //EOF 531 | break; 532 | } 533 | Group group = new Group(deviceGroup); 534 | groups.add(group); 535 | if(deviceGroup.getAvatar().isPresent()) { 536 | String id = UUID.randomUUID().toString(); 537 | saveAttachment(toUser(envelope.getSourceAddress()), deviceGroup.getAvatar().get(), 538 | null, id); 539 | group.setAvatarId(id); 540 | } 541 | } 542 | file.delete(); 543 | store.getDataStore().getGroups().stream() 544 | .filter(v -> v.getAvatarId() != null) 545 | .forEach(v -> deleteAttachment(v.getAvatarId())); 546 | store.getDataStore().overwriteGroups(groups); 547 | for(Group group : groups) { 548 | fireGroupUpdate(envelope.getSourceAddress(), group); 549 | } 550 | } else if(syncMessage.getBlockedList().isPresent()) { 551 | BlockedListMessage blockedMessage = syncMessage.getBlockedList().get(); 552 | List blocked = blockedMessage.getNumbers(); 553 | for(User contact : store.getDataStore().getContacts()) { 554 | boolean isNewBlocked = blocked.contains(contact.getNumber()); 555 | if(contact.isBlocked() && !isNewBlocked) { 556 | contact.setBlocked(false); 557 | fireContactUpdate(contact); 558 | } else if(!contact.isBlocked() && isNewBlocked) { 559 | contact.setBlocked(true); 560 | fireContactUpdate(contact); 561 | } 562 | } 563 | } else if(syncMessage.getRead().isPresent()) { 564 | List reads = syncMessage.getRead().get(); 565 | fireReadUpdate(reads); 566 | } else if(syncMessage.getSent().isPresent()) { 567 | SentTranscriptMessage transcript = syncMessage.getSent().get(); 568 | handleDataMessage(envelope, transcript.getMessage()); 569 | } 570 | } 571 | 572 | private void fireContactUpdate(User contact) throws IOException { 573 | for(ConversationListener listener : conversationListeners) { 574 | listener.onContactUpdate(contact); 575 | } 576 | } 577 | 578 | private void fireMessage(SignalServiceAddress address, SignalServiceDataMessage dataMessage, Group group) { 579 | for(ConversationListener listener : conversationListeners) { 580 | listener.onMessage(toUser(address), dataMessage, group); 581 | } 582 | } 583 | 584 | private void fireGroupUpdate(SignalServiceAddress address, Group group) throws IOException { 585 | for(ConversationListener listener : conversationListeners) { 586 | listener.onGroupUpdate(toUser(address), group); 587 | } 588 | } 589 | 590 | private void fireReadUpdate(List readList) { 591 | for(ConversationListener listener : conversationListeners) { 592 | listener.onReadUpdate(readList); 593 | } 594 | } 595 | 596 | private void fireSecurityException(SignalServiceAddress sender, Exception e) { 597 | fireSecurityException(toUser(sender), e); 598 | } 599 | 600 | private void fireSecurityException(User sender, Exception e) { 601 | for(SecurityExceptionListener listener : securityExceptionListeners) { 602 | listener.onSecurityException(sender, e); 603 | } 604 | } 605 | 606 | /** 607 | * Tries to find the address in the stored contacts and creates new user if necessary (but does not store it). 608 | * @param address 609 | * @return the found contact or the new user 610 | */ 611 | public User toUser(SignalServiceAddress address) { 612 | if(address == null) { 613 | return null; 614 | } 615 | User user = store.getDataStore().getContact(address.getNumber()); 616 | if(user == null) { 617 | user = new User(address.getNumber()); 618 | } 619 | return user; 620 | } 621 | 622 | /** 623 | * Ensures that there are enough prekeys available. Has to be called regularly.
624 | * Every time somebody sends you a message, he uses one of your prekeys which you have uploaded earlier. 625 | * To always have one prekey available, you also upload a last resort key. You should always 626 | * have enough prekeys to prevent key reusing. 627 | * @param minimumKeys the minimum amount of keys to register. Must be below 100. 628 | * @throws IOException 629 | */ 630 | public void checkPreKeys(int minimumKeys) throws IOException { 631 | if(minimumKeys > PREKEYS_BATCH_SIZE) { 632 | throw new IllegalArgumentException("PreKeys count must be below or equal to " + PREKEYS_BATCH_SIZE); 633 | } 634 | checkRegistered(); 635 | int preKeysCount = accountManager.getPreKeysCount(); 636 | if(preKeysCount < minimumKeys || minimumKeys < 0) { 637 | try { 638 | // generate prekeys 639 | int nextPreKeyId = store.getNextPreKeyId(); 640 | ArrayList preKeys = new ArrayList<>(); 641 | for(int i = 0; i < PREKEYS_BATCH_SIZE; i++) { 642 | PreKeyRecord record = new PreKeyRecord(nextPreKeyId, Curve.generateKeyPair()); 643 | store.storePreKey(record.getId(), record); 644 | preKeys.add(record); 645 | nextPreKeyId = (nextPreKeyId + 1) % MAX_PREKEY_ID; 646 | } 647 | store.setNextPreKeyId(nextPreKeyId); 648 | 649 | // generate signed prekey 650 | int nextSignedPreKeyId = store.getNextSignedPreKeyId(); 651 | SignedPreKeyRecord signedPreKey = KeyHelper.generateSignedPreKey(store.getIdentityKeyPair(), nextSignedPreKeyId); 652 | store.storeSignedPreKey(signedPreKey.getId(), signedPreKey); 653 | store.setNextSignedPreKeyId((nextSignedPreKeyId + 1) % MAX_PREKEY_ID); 654 | 655 | // upload 656 | accountManager.setPreKeys(store.getIdentityKeyPair().getPublicKey(), store.getLastResortPreKey(), 657 | signedPreKey, preKeys); 658 | } catch (InvalidKeyException e) { 659 | throw new RuntimeException("Stored identity corrupt!", e); 660 | } 661 | save(); 662 | } 663 | } 664 | 665 | /** 666 | * Save an attachment to the attachments folder specified by {@code ATTACHMENTS_PATH}. 667 | * The file name is chosen automatically based on the attachment id. 668 | * @param sender for mapping an exception which might occur to the sender 669 | * @param attachment the attachment to download 670 | * @param progressListener an optional download progress listener 671 | * @return the file descriptor for the saved attachment 672 | * @throws IOException 673 | */ 674 | public File saveAttachment(SignalServiceAddress sender, SignalServiceAttachment attachment, ProgressListener progressListener) 675 | throws IOException { 676 | return saveAttachment(toUser(sender), attachment, progressListener); 677 | } 678 | /** 679 | * Save an attachment to the attachments folder specified by {@code ATTACHMENTS_PATH}. 680 | * The file name is chosen automatically based on the attachment id. 681 | * @param sender for mapping an exception which might occur to the sender 682 | * @param attachment the attachment to download 683 | * @param progressListener an optional download progress listener 684 | * @return the file descriptor for the saved attachment 685 | * @throws IOException 686 | */ 687 | public File saveAttachment(User sender, SignalServiceAttachment attachment, ProgressListener progressListener) 688 | throws IOException { 689 | String attachmentId = String.valueOf(attachment.asPointer().getId()); 690 | return saveAttachment(sender, attachment, progressListener, attachmentId); 691 | } 692 | private File saveAttachment(User sender, SignalServiceAttachment attachment, 693 | ProgressListener progressListener, String attachmentId) throws IOException { 694 | File attachmentsDir = new File(ATTACHMENTS_PATH); 695 | if(!attachmentsDir.exists()) { 696 | boolean success = attachmentsDir.mkdirs(); 697 | if(!success) { 698 | throw new IOException("Could not create attachments directory!"); 699 | } 700 | } 701 | File file = Paths.get(attachmentsDir.getAbsolutePath(), attachmentId).toFile(); 702 | if(file.exists()) { 703 | return file; 704 | } 705 | File buffer = Paths.get(attachmentsDir.getAbsolutePath(), attachmentId + ".part").toFile(); 706 | InputStream in = null; 707 | if(attachment.isPointer()) { 708 | try { 709 | in = messageReceiver.retrieveAttachment(attachment.asPointer(), buffer, progressListener); 710 | } catch (InvalidMessageException e) { 711 | fireSecurityException(sender, e); 712 | } 713 | } else { 714 | in = attachment.asStream().getInputStream(); 715 | } 716 | Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); 717 | 718 | buffer.delete(); 719 | return file; 720 | } 721 | 722 | /** 723 | * Convenience method to delete attachments 724 | * @param id 725 | */ 726 | public void deleteAttachment(String id) { 727 | File attachment = Paths.get(ATTACHMENTS_PATH, id).toFile(); 728 | if(attachment.exists()) { 729 | attachment.delete(); 730 | } 731 | } 732 | 733 | /** 734 | * Convenience method to get a file handle for an already saved attachment. 735 | * @param id 736 | * @return the file or null if no corresponding file is cached 737 | */ 738 | public File getAttachment(String id) { 739 | File attachment = Paths.get(ATTACHMENTS_PATH, id).toFile(); 740 | if(attachment.exists()) { 741 | return attachment; 742 | } else { 743 | return null; 744 | } 745 | } 746 | 747 | /** 748 | * Returns the data store where the contacts and groups are stored.
749 | * There are two stores (key store (private) and data store), both saved in {@code STORE_PATH}. Both stores are managed by the library, 750 | * so you should only use this store for reading it. If you have to change something manually, call {@code save()} 751 | * afterwards. 752 | * @return the data store 753 | */ 754 | public DataStore getDataStore() { 755 | return store.getDataStore(); 756 | } 757 | 758 | /** 759 | * Leaves the group.

760 | * Hack: You can use a custom crafted group. This can be useful to leave a group where you lost the store for. 761 | * @param group 762 | * @throws IOException 763 | */ 764 | public void leaveGroup(Group group) throws IOException { 765 | SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder() 766 | .withTimestamp(System.currentTimeMillis()) 767 | .asGroupMessage(SignalServiceGroup.newBuilder(Type.QUIT) 768 | .withId(group.getId().getId()) 769 | .build()) 770 | .withExpiration(group.getMessageExpirationTime()) 771 | .build(); 772 | sendMessage(group.getMembers(), message); 773 | } 774 | 775 | } 776 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/main/java/de/thoffbauer/signal4j/util/Base64.java: -------------------------------------------------------------------------------- 1 | package de.thoffbauer.signal4j.util; 2 | 3 | 4 | /** 5 | *

Encodes and decodes to and from Base64 notation.

6 | *

Homepage: http://iharder.net/base64.

7 | * 8 | *

Example:

9 | * 10 | * String encoded = Base64.encode( myByteArray ); 11 | *
12 | * byte[] myByteArray = Base64.decode( encoded ); 13 | * 14 | *

The options parameter, which appears in a few places, is used to pass 15 | * several pieces of information to the encoder. In the "higher level" methods such as 16 | * encodeBytes( bytes, options ) the options parameter can be used to indicate such 17 | * things as first gzipping the bytes before encoding them, not inserting linefeeds, 18 | * and encoding using the URL-safe and Ordered dialects.

19 | * 20 | *

Note, according to RFC3548, 21 | * Section 2.1, implementations should not add line feeds unless explicitly told 22 | * to do so. I've got Base64 set to this behavior now, although earlier versions 23 | * broke lines by default.

24 | * 25 | *

The constants defined in Base64 can be OR-ed together to combine options, so you 26 | * might make a call like this:

27 | * 28 | * String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES ); 29 | *

to compress the data before encoding it and then making the output have newline characters.

30 | *

Also...

31 | * String encoded = Base64.encodeBytes( crazyString.getBytes() ); 32 | * 33 | * 34 | * 35 | *

36 | * Change Log: 37 | *

38 | *
    39 | *
  • v2.3.4 - Fixed bug when working with gzipped streams whereby flushing 40 | * the Base64.OutputStream closed the Base64 encoding (by padding with equals 41 | * signs) too soon. Also added an option to suppress the automatic decoding 42 | * of gzipped streams. Also added experimental support for specifying a 43 | * class loader when using the 44 | * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} 45 | * method.
  • 46 | *
  • v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java 47 | * footprint with its CharEncoders and so forth. Fixed some javadocs that were 48 | * inconsistent. Removed imports and specified things like java.io.IOException 49 | * explicitly inline.
  • 50 | *
  • v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the 51 | * final encoded data will be so that the code doesn't have to create two output 52 | * arrays: an oversized initial one and then a final, exact-sized one. Big win 53 | * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not 54 | * using the gzip options which uses a different mechanism with streams and stuff).
  • 55 | *
  • v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some 56 | * similar helper methods to be more efficient with memory by not returning a 57 | * String but just a byte array.
  • 58 | *
  • v2.3 - This is not a drop-in replacement! This is two years of comments 59 | * and bug fixes queued up and finally executed. Thanks to everyone who sent 60 | * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. 61 | * Much bad coding was cleaned up including throwing exceptions where necessary 62 | * instead of returning null values or something similar. Here are some changes 63 | * that may affect you: 64 | *
      65 | *
    • Does not break lines, by default. This is to keep in compliance with 66 | * RFC3548.
    • 67 | *
    • Throws exceptions instead of returning null values. Because some operations 68 | * (especially those that may permit the GZIP option) use IO streams, there 69 | * is a possiblity of an java.io.IOException being thrown. After some discussion and 70 | * thought, I've changed the behavior of the methods to throw java.io.IOExceptions 71 | * rather than return null if ever there's an error. I think this is more 72 | * appropriate, though it will require some changes to your code. Sorry, 73 | * it should have been done this way to begin with.
    • 74 | *
    • Removed all references to System.out, System.err, and the like. 75 | * Shame on me. All I can say is sorry they were ever there.
    • 76 | *
    • Throws NullPointerExceptions and IllegalArgumentExceptions as needed 77 | * such as when passed arrays are null or offsets are invalid.
    • 78 | *
    • Cleaned up as much javadoc as I could to avoid any javadoc warnings. 79 | * This was especially annoying before for people who were thorough in their 80 | * own projects and then had gobs of javadoc warnings on this file.
    • 81 | *
    82 | *
  • v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug 83 | * when using very small files (~< 40 bytes).
  • 84 | *
  • v2.2 - Added some helper methods for encoding/decoding directly from 85 | * one file to the next. Also added a main() method to support command line 86 | * encoding/decoding from one file to the next. Also added these Base64 dialects: 87 | *
      88 | *
    1. The default is RFC3548 format.
    2. 89 | *
    3. Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates 90 | * URL and file name friendly format as described in Section 4 of RFC3548. 91 | * http://www.faqs.org/rfcs/rfc3548.html
    4. 92 | *
    5. Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates 93 | * URL and file name friendly format that preserves lexical ordering as described 94 | * in http://www.faqs.org/qa/rfcc-1940.html
    6. 95 | *
    96 | * Special thanks to Jim Kellerman at http://www.powerset.com/ 97 | * for contributing the new Base64 dialects. 98 | *
  • 99 | * 100 | *
  • v2.1 - Cleaned up javadoc comments and unused variables and methods. Added 101 | * some convenience methods for reading and writing to and from files.
  • 102 | *
  • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems 103 | * with other encodings (like EBCDIC).
  • 104 | *
  • v2.0.1 - Fixed an error when decoding a single byte, that is, when the 105 | * encoded data was a single byte.
  • 106 | *
  • v2.0 - I got rid of methods that used booleans to set options. 107 | * Now everything is more consolidated and cleaner. The code now detects 108 | * when data that's being decoded is gzip-compressed and will decompress it 109 | * automatically. Generally things are cleaner. You'll probably have to 110 | * change some method calls that you were making to support the new 111 | * options format (ints that you "OR" together).
  • 112 | *
  • v1.5.1 - Fixed bug when decompressing and decoding to a 113 | * byte[] using decode( String s, boolean gzipCompressed ). 114 | * Added the ability to "suspend" encoding in the Output Stream so 115 | * you can turn on and off the encoding if you need to embed base64 116 | * data in an otherwise "normal" stream (like an XML file).
  • 117 | *
  • v1.5 - Output stream pases on flush() command but doesn't do anything itself. 118 | * This helps when using GZIP streams. 119 | * Added the ability to GZip-compress objects before encoding them.
  • 120 | *
  • v1.4 - Added helper methods to read/write files.
  • 121 | *
  • v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
  • 122 | *
  • v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream 123 | * where last buffer being read, if not completely full, was not returned.
  • 124 | *
  • v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.
  • 125 | *
  • v1.3.3 - Fixed I/O streams which were totally messed up.
  • 126 | *
127 | * 128 | *

129 | * I am placing this code in the Public Domain. Do with it as you will. 130 | * This software comes with no guarantees or warranties but with 131 | * plenty of well-wishing instead! 132 | * Please visit http://iharder.net/base64 133 | * periodically to check for updates or to contribute improvements. 134 | *

135 | * 136 | * @author Robert Harder 137 | * @author rob@iharder.net 138 | * @version 2.3.3 139 | */ 140 | public class Base64 { 141 | 142 | /* ******** P U B L I C F I E L D S ******** */ 143 | 144 | 145 | /** 146 | * No options specified. Value is zero. 147 | */ 148 | public final static int NO_OPTIONS = 0; 149 | 150 | /** 151 | * Specify encoding in first bit. Value is one. 152 | */ 153 | public final static int ENCODE = 1; 154 | 155 | 156 | /** 157 | * Specify decoding in first bit. Value is zero. 158 | */ 159 | public final static int DECODE = 0; 160 | 161 | 162 | /** 163 | * Specify that data should be gzip-compressed in second bit. Value is two. 164 | */ 165 | public final static int GZIP = 2; 166 | 167 | /** 168 | * Specify that gzipped data should not be automatically gunzipped. 169 | */ 170 | public final static int DONT_GUNZIP = 4; 171 | 172 | 173 | /** 174 | * Do break lines when encoding. Value is 8. 175 | */ 176 | public final static int DO_BREAK_LINES = 8; 177 | 178 | /** 179 | * Encode using Base64-like encoding that is URL- and Filename-safe as described 180 | * in Section 4 of RFC3548: 181 | * http://www.faqs.org/rfcs/rfc3548.html. 182 | * It is important to note that data encoded this way is not officially valid Base64, 183 | * or at the very least should not be called Base64 without also specifying that is 184 | * was encoded using the URL- and Filename-safe dialect. 185 | */ 186 | public final static int URL_SAFE = 16; 187 | 188 | 189 | /** 190 | * Encode using the special "ordered" dialect of Base64 described here: 191 | * http://www.faqs.org/qa/rfcc-1940.html. 192 | */ 193 | public final static int ORDERED = 32; 194 | 195 | 196 | /* ******** P R I V A T E F I E L D S ******** */ 197 | 198 | 199 | /** 200 | * Maximum line length (76) of Base64 output. 201 | */ 202 | private final static int MAX_LINE_LENGTH = 76; 203 | 204 | 205 | /** 206 | * The equals sign (=) as a byte. 207 | */ 208 | private final static byte EQUALS_SIGN = (byte) '='; 209 | 210 | 211 | /** 212 | * The new line character (\n) as a byte. 213 | */ 214 | private final static byte NEW_LINE = (byte) '\n'; 215 | 216 | 217 | /** 218 | * Preferred encoding. 219 | */ 220 | private final static String PREFERRED_ENCODING = "US-ASCII"; 221 | 222 | 223 | private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding 224 | private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding 225 | 226 | 227 | /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ 228 | 229 | /** 230 | * The 64 valid Base64 values. 231 | */ 232 | /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ 233 | private final static byte[] _STANDARD_ALPHABET = { 234 | (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', 235 | (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', 236 | (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', 237 | (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', 238 | (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', 239 | (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', 240 | (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', 241 | (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', 242 | (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', 243 | (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' 244 | }; 245 | 246 | 247 | /** 248 | * Translates a Base64 value to either its 6-bit reconstruction value 249 | * or a negative number indicating some other meaning. 250 | */ 251 | private final static byte[] _STANDARD_DECODABET = { 252 | -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 253 | -5, -5, // Whitespace: Tab and Linefeed 254 | -9, -9, // Decimal 11 - 12 255 | -5, // Whitespace: Carriage Return 256 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 257 | -9, -9, -9, -9, -9, // Decimal 27 - 31 258 | -5, // Whitespace: Space 259 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 260 | 62, // Plus sign at decimal 43 261 | -9, -9, -9, // Decimal 44 - 46 262 | 63, // Slash at decimal 47 263 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine 264 | -9, -9, -9, // Decimal 58 - 60 265 | -1, // Equals sign at decimal 61 266 | -9, -9, -9, // Decimal 62 - 64 267 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 268 | 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' 269 | -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 270 | 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 271 | 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' 272 | -9, -9, -9, -9 // Decimal 123 - 126 273 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 274 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 275 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 276 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 277 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 278 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 279 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 280 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 281 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 282 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 283 | }; 284 | 285 | 286 | /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ 287 | 288 | /** 289 | * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: 290 | * http://www.faqs.org/rfcs/rfc3548.html. 291 | * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." 292 | */ 293 | private final static byte[] _URL_SAFE_ALPHABET = { 294 | (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', 295 | (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', 296 | (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', 297 | (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', 298 | (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', 299 | (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', 300 | (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', 301 | (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', 302 | (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', 303 | (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' 304 | }; 305 | 306 | /** 307 | * Used in decoding URL- and Filename-safe dialects of Base64. 308 | */ 309 | private final static byte[] _URL_SAFE_DECODABET = { 310 | -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 311 | -5, -5, // Whitespace: Tab and Linefeed 312 | -9, -9, // Decimal 11 - 12 313 | -5, // Whitespace: Carriage Return 314 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 315 | -9, -9, -9, -9, -9, // Decimal 27 - 31 316 | -5, // Whitespace: Space 317 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 318 | -9, // Plus sign at decimal 43 319 | -9, // Decimal 44 320 | 62, // Minus sign at decimal 45 321 | -9, // Decimal 46 322 | -9, // Slash at decimal 47 323 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine 324 | -9, -9, -9, // Decimal 58 - 60 325 | -1, // Equals sign at decimal 61 326 | -9, -9, -9, // Decimal 62 - 64 327 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 328 | 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' 329 | -9, -9, -9, -9, // Decimal 91 - 94 330 | 63, // Underscore at decimal 95 331 | -9, // Decimal 96 332 | 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 333 | 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' 334 | -9, -9, -9, -9 // Decimal 123 - 126 335 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 336 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 337 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 338 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 339 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 340 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 341 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 342 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 343 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 344 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 345 | }; 346 | 347 | 348 | 349 | /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ 350 | 351 | /** 352 | * I don't get the point of this technique, but someone requested it, 353 | * and it is described here: 354 | * http://www.faqs.org/qa/rfcc-1940.html. 355 | */ 356 | private final static byte[] _ORDERED_ALPHABET = { 357 | (byte) '-', 358 | (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', 359 | (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', 360 | (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', 361 | (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', 362 | (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', 363 | (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', 364 | (byte) '_', 365 | (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', 366 | (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', 367 | (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', 368 | (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' 369 | }; 370 | 371 | /** 372 | * Used in decoding the "ordered" dialect of Base64. 373 | */ 374 | private final static byte[] _ORDERED_DECODABET = { 375 | -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 376 | -5, -5, // Whitespace: Tab and Linefeed 377 | -9, -9, // Decimal 11 - 12 378 | -5, // Whitespace: Carriage Return 379 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 380 | -9, -9, -9, -9, -9, // Decimal 27 - 31 381 | -5, // Whitespace: Space 382 | -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 383 | -9, // Plus sign at decimal 43 384 | -9, // Decimal 44 385 | 0, // Minus sign at decimal 45 386 | -9, // Decimal 46 387 | -9, // Slash at decimal 47 388 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine 389 | -9, -9, -9, // Decimal 58 - 60 390 | -1, // Equals sign at decimal 61 391 | -9, -9, -9, // Decimal 62 - 64 392 | 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' 393 | 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' 394 | -9, -9, -9, -9, // Decimal 91 - 94 395 | 37, // Underscore at decimal 95 396 | -9, // Decimal 96 397 | 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' 398 | 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' 399 | -9, -9, -9, -9 // Decimal 123 - 126 400 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 401 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 402 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 403 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 404 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 405 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 406 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 407 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 408 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 409 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 410 | }; 411 | 412 | 413 | /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ 414 | 415 | 416 | /** 417 | * Returns one of the _SOMETHING_ALPHABET byte arrays depending on 418 | * the options specified. 419 | * It's possible, though silly, to specify ORDERED and URLSAFE 420 | * in which case one of them will be picked, though there is 421 | * no guarantee as to which one will be picked. 422 | */ 423 | private final static byte[] getAlphabet(int options) { 424 | if ((options & URL_SAFE) == URL_SAFE) { 425 | return _URL_SAFE_ALPHABET; 426 | } else if ((options & ORDERED) == ORDERED) { 427 | return _ORDERED_ALPHABET; 428 | } else { 429 | return _STANDARD_ALPHABET; 430 | } 431 | } // end getAlphabet 432 | 433 | 434 | /** 435 | * Returns one of the _SOMETHING_DECODABET byte arrays depending on 436 | * the options specified. 437 | * It's possible, though silly, to specify ORDERED and URL_SAFE 438 | * in which case one of them will be picked, though there is 439 | * no guarantee as to which one will be picked. 440 | */ 441 | private final static byte[] getDecodabet(int options) { 442 | if ((options & URL_SAFE) == URL_SAFE) { 443 | return _URL_SAFE_DECODABET; 444 | } else if ((options & ORDERED) == ORDERED) { 445 | return _ORDERED_DECODABET; 446 | } else { 447 | return _STANDARD_DECODABET; 448 | } 449 | } // end getAlphabet 450 | 451 | 452 | /** 453 | * Defeats instantiation. 454 | */ 455 | private Base64() { 456 | } 457 | 458 | 459 | public static int getEncodedLengthWithoutPadding(int unencodedLength) { 460 | int remainderBytes = unencodedLength % 3; 461 | int paddingBytes = 0; 462 | 463 | if (remainderBytes != 0) 464 | paddingBytes = 3 - remainderBytes; 465 | 466 | return (((int) ((unencodedLength + 2) / 3)) * 4) - paddingBytes; 467 | } 468 | 469 | public static int getEncodedBytesForTarget(int targetSize) { 470 | return ((int) (targetSize * 3)) / 4; 471 | } 472 | 473 | 474 | /* ******** E N C O D I N G M E T H O D S ******** */ 475 | 476 | 477 | /** 478 | * Encodes up to the first three bytes of array threeBytes 479 | * and returns a four-byte array in Base64 notation. 480 | * The actual number of significant bytes in your array is 481 | * given by numSigBytes. 482 | * The array threeBytes needs only be as big as 483 | * numSigBytes. 484 | * Code can reuse a byte array by passing a four-byte array as b4. 485 | * 486 | * @param b4 A reusable byte array to reduce array instantiation 487 | * @param threeBytes the array to convert 488 | * @param numSigBytes the number of significant bytes in your array 489 | * @return four byte array in Base64 notation. 490 | * @since 1.5.1 491 | */ 492 | private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) { 493 | encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); 494 | return b4; 495 | } // end encode3to4 496 | 497 | 498 | /** 499 | *

Encodes up to three bytes of the array source 500 | * and writes the resulting four Base64 bytes to destination. 501 | * The source and destination arrays can be manipulated 502 | * anywhere along their length by specifying 503 | * srcOffset and destOffset. 504 | * This method does not check to make sure your arrays 505 | * are large enough to accomodate srcOffset + 3 for 506 | * the source array or destOffset + 4 for 507 | * the destination array. 508 | * The actual number of significant bytes in your array is 509 | * given by numSigBytes.

510 | *

This is the lowest level of the encoding methods with 511 | * all possible parameters.

512 | * 513 | * @param source the array to convert 514 | * @param srcOffset the index where conversion begins 515 | * @param numSigBytes the number of significant bytes in your array 516 | * @param destination the array to hold the conversion 517 | * @param destOffset the index where output will be put 518 | * @return the destination array 519 | * @since 1.3 520 | */ 521 | private static byte[] encode3to4( 522 | byte[] source, int srcOffset, int numSigBytes, 523 | byte[] destination, int destOffset, int options) { 524 | 525 | byte[] ALPHABET = getAlphabet(options); 526 | 527 | // 1 2 3 528 | // 01234567890123456789012345678901 Bit position 529 | // --------000000001111111122222222 Array position from threeBytes 530 | // --------| || || || | Six bit groups to index ALPHABET 531 | // >>18 >>12 >> 6 >> 0 Right shift necessary 532 | // 0x3f 0x3f 0x3f Additional AND 533 | 534 | // Create buffer with zero-padding if there are only one or two 535 | // significant bytes passed in the array. 536 | // We have to shift left 24 in order to flush out the 1's that appear 537 | // when Java treats a value as negative that is cast from a byte to an int. 538 | int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) 539 | | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) 540 | | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); 541 | 542 | switch (numSigBytes) { 543 | case 3: 544 | destination[destOffset] = ALPHABET[(inBuff >>> 18)]; 545 | destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; 546 | destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; 547 | destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; 548 | return destination; 549 | 550 | case 2: 551 | destination[destOffset] = ALPHABET[(inBuff >>> 18)]; 552 | destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; 553 | destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; 554 | destination[destOffset + 3] = EQUALS_SIGN; 555 | return destination; 556 | 557 | case 1: 558 | destination[destOffset] = ALPHABET[(inBuff >>> 18)]; 559 | destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; 560 | destination[destOffset + 2] = EQUALS_SIGN; 561 | destination[destOffset + 3] = EQUALS_SIGN; 562 | return destination; 563 | 564 | default: 565 | return destination; 566 | } // end switch 567 | } // end encode3to4 568 | 569 | 570 | /** 571 | * Performs Base64 encoding on the raw ByteBuffer, 572 | * writing it to the encoded ByteBuffer. 573 | * This is an experimental feature. Currently it does not 574 | * pass along any options (such as {@link #DO_BREAK_LINES} 575 | * or {@link #GZIP}. 576 | * 577 | * @param raw input buffer 578 | * @param encoded output buffer 579 | * @since 2.3 580 | */ 581 | public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) { 582 | byte[] raw3 = new byte[3]; 583 | byte[] enc4 = new byte[4]; 584 | 585 | while (raw.hasRemaining()) { 586 | int rem = Math.min(3, raw.remaining()); 587 | raw.get(raw3, 0, rem); 588 | Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); 589 | encoded.put(enc4); 590 | } // end input remaining 591 | } 592 | 593 | 594 | /** 595 | * Performs Base64 encoding on the raw ByteBuffer, 596 | * writing it to the encoded CharBuffer. 597 | * This is an experimental feature. Currently it does not 598 | * pass along any options (such as {@link #DO_BREAK_LINES} 599 | * or {@link #GZIP}. 600 | * 601 | * @param raw input buffer 602 | * @param encoded output buffer 603 | * @since 2.3 604 | */ 605 | public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) { 606 | byte[] raw3 = new byte[3]; 607 | byte[] enc4 = new byte[4]; 608 | 609 | while (raw.hasRemaining()) { 610 | int rem = Math.min(3, raw.remaining()); 611 | raw.get(raw3, 0, rem); 612 | Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); 613 | for (int i = 0; i < 4; i++) { 614 | encoded.put((char) (enc4[i] & 0xFF)); 615 | } 616 | } // end input remaining 617 | } 618 | 619 | 620 | /** 621 | * Serializes an object and returns the Base64-encoded 622 | * version of that serialized object. 623 | * 624 | *

As of v 2.3, if the object 625 | * cannot be serialized or there is another error, 626 | * the method will throw an java.io.IOException. This is new to v2.3! 627 | * In earlier versions, it just returned a null value, but 628 | * in retrospect that's a pretty poor way to handle it.

629 | * 630 | * The object is not GZip-compressed before being encoded. 631 | * 632 | * @param serializableObject The object to encode 633 | * @return The Base64-encoded object 634 | * @throws java.io.IOException if there is an error 635 | * @throws NullPointerException if serializedObject is null 636 | * @since 1.4 637 | */ 638 | public static String encodeObject(java.io.Serializable serializableObject) 639 | throws java.io.IOException { 640 | return encodeObject(serializableObject, NO_OPTIONS); 641 | } // end encodeObject 642 | 643 | 644 | /** 645 | * Serializes an object and returns the Base64-encoded 646 | * version of that serialized object. 647 | * 648 | *

As of v 2.3, if the object 649 | * cannot be serialized or there is another error, 650 | * the method will throw an java.io.IOException. This is new to v2.3! 651 | * In earlier versions, it just returned a null value, but 652 | * in retrospect that's a pretty poor way to handle it.

653 | * 654 | * The object is not GZip-compressed before being encoded. 655 | * 656 | * Example options:
 657 |      *   GZIP: gzip-compresses object before encoding it.
 658 |      *   DO_BREAK_LINES: break lines at 76 characters
 659 |      * 
660 | * 661 | * Example: encodeObject( myObj, Base64.GZIP ) or 662 | * 663 | * Example: encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES ) 664 | * 665 | * @param serializableObject The object to encode 666 | * @param options Specified options 667 | * @return The Base64-encoded object 668 | * @throws java.io.IOException if there is an error 669 | * @see Base64#GZIP 670 | * @see Base64#DO_BREAK_LINES 671 | * @since 2.0 672 | */ 673 | public static String encodeObject(java.io.Serializable serializableObject, int options) 674 | throws java.io.IOException { 675 | 676 | if (serializableObject == null) { 677 | throw new NullPointerException("Cannot serialize a null object."); 678 | } // end if: null 679 | 680 | // Streams 681 | java.io.ByteArrayOutputStream baos = null; 682 | java.io.OutputStream b64os = null; 683 | java.util.zip.GZIPOutputStream gzos = null; 684 | java.io.ObjectOutputStream oos = null; 685 | 686 | 687 | try { 688 | // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream 689 | baos = new java.io.ByteArrayOutputStream(); 690 | b64os = new Base64.OutputStream(baos, ENCODE | options); 691 | if ((options & GZIP) != 0) { 692 | // Gzip 693 | gzos = new java.util.zip.GZIPOutputStream(b64os); 694 | oos = new java.io.ObjectOutputStream(gzos); 695 | } else { 696 | // Not gzipped 697 | oos = new java.io.ObjectOutputStream(b64os); 698 | } 699 | oos.writeObject(serializableObject); 700 | } // end try 701 | catch (java.io.IOException e) { 702 | // Catch it and then throw it immediately so that 703 | // the finally{} block is called for cleanup. 704 | throw e; 705 | } // end catch 706 | finally { 707 | try { 708 | oos.close(); 709 | } catch (Exception e) { 710 | } 711 | try { 712 | gzos.close(); 713 | } catch (Exception e) { 714 | } 715 | try { 716 | b64os.close(); 717 | } catch (Exception e) { 718 | } 719 | try { 720 | baos.close(); 721 | } catch (Exception e) { 722 | } 723 | } // end finally 724 | 725 | // Return value according to relevant encoding. 726 | try { 727 | return new String(baos.toByteArray(), PREFERRED_ENCODING); 728 | } // end try 729 | catch (java.io.UnsupportedEncodingException uue) { 730 | // Fall back to some Java default 731 | return new String(baos.toByteArray()); 732 | } // end catch 733 | 734 | } // end encode 735 | 736 | 737 | /** 738 | * Encodes a byte array into Base64 notation. 739 | * Does not GZip-compress data. 740 | * 741 | * @param source The data to convert 742 | * @return The data in Base64-encoded form 743 | * @throws NullPointerException if source array is null 744 | * @since 1.4 745 | */ 746 | public static String encodeBytes(byte[] source) { 747 | // Since we're not going to have the GZIP encoding turned on, 748 | // we're not going to have an java.io.IOException thrown, so 749 | // we should not force the user to have to catch it. 750 | String encoded = null; 751 | try { 752 | encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); 753 | } catch (java.io.IOException ex) { 754 | assert false : ex.getMessage(); 755 | } // end catch 756 | assert encoded != null; 757 | return encoded; 758 | } // end encodeBytes 759 | 760 | 761 | public static String encodeBytesWithoutPadding(byte[] source, int offset, int length) { 762 | String encoded = null; 763 | 764 | try { 765 | encoded = encodeBytes(source, offset, length, NO_OPTIONS); 766 | } catch (java.io.IOException ex) { 767 | assert false : ex.getMessage(); 768 | } 769 | 770 | assert encoded != null; 771 | 772 | if (encoded.charAt(encoded.length() - 2) == '=') 773 | return encoded.substring(0, encoded.length() - 2); 774 | else if (encoded.charAt(encoded.length() - 1) == '=') 775 | return encoded.substring(0, encoded.length() - 1); 776 | else return encoded; 777 | 778 | } 779 | 780 | public static String encodeBytesWithoutPadding(byte[] source) { 781 | return encodeBytesWithoutPadding(source, 0, source.length); 782 | } 783 | 784 | 785 | /** 786 | * Encodes a byte array into Base64 notation. 787 | *

788 | * Example options:

 789 |      *   GZIP: gzip-compresses object before encoding it.
 790 |      *   DO_BREAK_LINES: break lines at 76 characters
 791 |      *     Note: Technically, this makes your encoding non-compliant.
 792 |      * 
793 | *

794 | * Example: encodeBytes( myData, Base64.GZIP ) or 795 | *

796 | * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) 797 | * 798 | * 799 | *

As of v 2.3, if there is an error with the GZIP stream, 800 | * the method will throw an java.io.IOException. This is new to v2.3! 801 | * In earlier versions, it just returned a null value, but 802 | * in retrospect that's a pretty poor way to handle it.

803 | * 804 | * @param source The data to convert 805 | * @param options Specified options 806 | * @return The Base64-encoded data as a String 807 | * @throws java.io.IOException if there is an error 808 | * @throws NullPointerException if source array is null 809 | * @see Base64#GZIP 810 | * @see Base64#DO_BREAK_LINES 811 | * @since 2.0 812 | */ 813 | public static String encodeBytes(byte[] source, int options) throws java.io.IOException { 814 | return encodeBytes(source, 0, source.length, options); 815 | } // end encodeBytes 816 | 817 | 818 | /** 819 | * Encodes a byte array into Base64 notation. 820 | * Does not GZip-compress data. 821 | * 822 | *

As of v 2.3, if there is an error, 823 | * the method will throw an java.io.IOException. This is new to v2.3! 824 | * In earlier versions, it just returned a null value, but 825 | * in retrospect that's a pretty poor way to handle it.

826 | * 827 | * @param source The data to convert 828 | * @param off Offset in array where conversion should begin 829 | * @param len Length of data to convert 830 | * @return The Base64-encoded data as a String 831 | * @throws NullPointerException if source array is null 832 | * @throws IllegalArgumentException if source array, offset, or length are invalid 833 | * @since 1.4 834 | */ 835 | public static String encodeBytes(byte[] source, int off, int len) { 836 | // Since we're not going to have the GZIP encoding turned on, 837 | // we're not going to have an java.io.IOException thrown, so 838 | // we should not force the user to have to catch it. 839 | String encoded = null; 840 | try { 841 | encoded = encodeBytes(source, off, len, NO_OPTIONS); 842 | } catch (java.io.IOException ex) { 843 | assert false : ex.getMessage(); 844 | } // end catch 845 | assert encoded != null; 846 | return encoded; 847 | } // end encodeBytes 848 | 849 | 850 | /** 851 | * Encodes a byte array into Base64 notation. 852 | *

853 | * Example options:

 854 |      *   GZIP: gzip-compresses object before encoding it.
 855 |      *   DO_BREAK_LINES: break lines at 76 characters
 856 |      *     Note: Technically, this makes your encoding non-compliant.
 857 |      * 
858 | *

859 | * Example: encodeBytes( myData, Base64.GZIP ) or 860 | *

861 | * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) 862 | * 863 | * 864 | *

As of v 2.3, if there is an error with the GZIP stream, 865 | * the method will throw an java.io.IOException. This is new to v2.3! 866 | * In earlier versions, it just returned a null value, but 867 | * in retrospect that's a pretty poor way to handle it.

868 | * 869 | * @param source The data to convert 870 | * @param off Offset in array where conversion should begin 871 | * @param len Length of data to convert 872 | * @param options Specified options 873 | * @return The Base64-encoded data as a String 874 | * @throws java.io.IOException if there is an error 875 | * @throws NullPointerException if source array is null 876 | * @throws IllegalArgumentException if source array, offset, or length are invalid 877 | * @see Base64#GZIP 878 | * @see Base64#DO_BREAK_LINES 879 | * @since 2.0 880 | */ 881 | public static String encodeBytes(byte[] source, int off, int len, int options) throws java.io.IOException { 882 | byte[] encoded = encodeBytesToBytes(source, off, len, options); 883 | 884 | // Return value according to relevant encoding. 885 | try { 886 | return new String(encoded, PREFERRED_ENCODING); 887 | } // end try 888 | catch (java.io.UnsupportedEncodingException uue) { 889 | return new String(encoded); 890 | } // end catch 891 | 892 | } // end encodeBytes 893 | 894 | 895 | /** 896 | * Similar to {@link #encodeBytes(byte[])} but returns 897 | * a byte array instead of instantiating a String. This is more efficient 898 | * if you're working with I/O streams and have large data sets to encode. 899 | * 900 | * @param source The data to convert 901 | * @return The Base64-encoded data as a byte[] (of ASCII characters) 902 | * @throws NullPointerException if source array is null 903 | * @since 2.3.1 904 | */ 905 | public static byte[] encodeBytesToBytes(byte[] source) { 906 | byte[] encoded = null; 907 | try { 908 | encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS); 909 | } catch (java.io.IOException ex) { 910 | assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 911 | } 912 | return encoded; 913 | } 914 | 915 | 916 | /** 917 | * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns 918 | * a byte array instead of instantiating a String. This is more efficient 919 | * if you're working with I/O streams and have large data sets to encode. 920 | * 921 | * @param source The data to convert 922 | * @param off Offset in array where conversion should begin 923 | * @param len Length of data to convert 924 | * @param options Specified options 925 | * @return The Base64-encoded data as a String 926 | * @throws java.io.IOException if there is an error 927 | * @throws NullPointerException if source array is null 928 | * @throws IllegalArgumentException if source array, offset, or length are invalid 929 | * @see Base64#GZIP 930 | * @see Base64#DO_BREAK_LINES 931 | * @since 2.3.1 932 | */ 933 | public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException { 934 | 935 | if (source == null) { 936 | throw new NullPointerException("Cannot serialize a null array."); 937 | } // end if: null 938 | 939 | if (off < 0) { 940 | throw new IllegalArgumentException("Cannot have negative offset: " + off); 941 | } // end if: off < 0 942 | 943 | if (len < 0) { 944 | throw new IllegalArgumentException("Cannot have length offset: " + len); 945 | } // end if: len < 0 946 | 947 | if (off + len > source.length) { 948 | throw new IllegalArgumentException( 949 | String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); 950 | } // end if: off < 0 951 | 952 | 953 | // Compress? 954 | if ((options & GZIP) != 0) { 955 | java.io.ByteArrayOutputStream baos = null; 956 | java.util.zip.GZIPOutputStream gzos = null; 957 | Base64.OutputStream b64os = null; 958 | 959 | try { 960 | // GZip -> Base64 -> ByteArray 961 | baos = new java.io.ByteArrayOutputStream(); 962 | b64os = new Base64.OutputStream(baos, ENCODE | options); 963 | gzos = new java.util.zip.GZIPOutputStream(b64os); 964 | 965 | gzos.write(source, off, len); 966 | gzos.close(); 967 | } // end try 968 | catch (java.io.IOException e) { 969 | // Catch it and then throw it immediately so that 970 | // the finally{} block is called for cleanup. 971 | throw e; 972 | } // end catch 973 | finally { 974 | try { 975 | gzos.close(); 976 | } catch (Exception e) { 977 | } 978 | try { 979 | b64os.close(); 980 | } catch (Exception e) { 981 | } 982 | try { 983 | baos.close(); 984 | } catch (Exception e) { 985 | } 986 | } // end finally 987 | 988 | return baos.toByteArray(); 989 | } // end if: compress 990 | 991 | // Else, don't compress. Better not to use streams at all then. 992 | else { 993 | boolean breakLines = (options & DO_BREAK_LINES) > 0; 994 | 995 | //int len43 = len * 4 / 3; 996 | //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 997 | // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding 998 | // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines 999 | // Try to determine more precisely how big the array needs to be. 1000 | // If we get it right, we don't have to do an array copy, and 1001 | // we save a bunch of memory. 1002 | int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding 1003 | if (breakLines) { 1004 | encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters 1005 | } 1006 | byte[] outBuff = new byte[encLen]; 1007 | 1008 | 1009 | int d = 0; 1010 | int e = 0; 1011 | int len2 = len - 2; 1012 | int lineLength = 0; 1013 | for (; d < len2; d += 3, e += 4) { 1014 | encode3to4(source, d + off, 3, outBuff, e, options); 1015 | 1016 | lineLength += 4; 1017 | if (breakLines && lineLength >= MAX_LINE_LENGTH) { 1018 | outBuff[e + 4] = NEW_LINE; 1019 | e++; 1020 | lineLength = 0; 1021 | } // end if: end of line 1022 | } // en dfor: each piece of array 1023 | 1024 | if (d < len) { 1025 | encode3to4(source, d + off, len - d, outBuff, e, options); 1026 | e += 4; 1027 | } // end if: some padding needed 1028 | 1029 | 1030 | // Only resize array if we didn't guess it right. 1031 | if (e < outBuff.length - 1) { 1032 | byte[] finalOut = new byte[e]; 1033 | System.arraycopy(outBuff, 0, finalOut, 0, e); 1034 | //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); 1035 | return finalOut; 1036 | } else { 1037 | //System.err.println("No need to resize array."); 1038 | return outBuff; 1039 | } 1040 | 1041 | } // end else: don't compress 1042 | 1043 | } // end encodeBytesToBytes 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | /* ******** D E C O D I N G M E T H O D S ******** */ 1050 | 1051 | 1052 | /** 1053 | * Decodes four bytes from array source 1054 | * and writes the resulting bytes (up to three of them) 1055 | * to destination. 1056 | * The source and destination arrays can be manipulated 1057 | * anywhere along their length by specifying 1058 | * srcOffset and destOffset. 1059 | * This method does not check to make sure your arrays 1060 | * are large enough to accomodate srcOffset + 4 for 1061 | * the source array or destOffset + 3 for 1062 | * the destination array. 1063 | * This method returns the actual number of bytes that 1064 | * were converted from the Base64 encoding. 1065 | *

This is the lowest level of the decoding methods with 1066 | * all possible parameters.

1067 | * 1068 | * @param source the array to convert 1069 | * @param srcOffset the index where conversion begins 1070 | * @param destination the array to hold the conversion 1071 | * @param destOffset the index where output will be put 1072 | * @param options alphabet type is pulled from this (standard, url-safe, ordered) 1073 | * @return the number of decoded bytes converted 1074 | * @throws NullPointerException if source or destination arrays are null 1075 | * @throws IllegalArgumentException if srcOffset or destOffset are invalid 1076 | * or there is not enough room in the array. 1077 | * @since 1.3 1078 | */ 1079 | private static int decode4to3( 1080 | byte[] source, int srcOffset, 1081 | byte[] destination, int destOffset, int options) { 1082 | 1083 | // Lots of error checking and exception throwing 1084 | if (source == null) { 1085 | throw new NullPointerException("Source array was null."); 1086 | } // end if 1087 | if (destination == null) { 1088 | throw new NullPointerException("Destination array was null."); 1089 | } // end if 1090 | if (srcOffset < 0 || srcOffset + 3 >= source.length) { 1091 | throw new IllegalArgumentException(String.format( 1092 | "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); 1093 | } // end if 1094 | if (destOffset < 0 || destOffset + 2 >= destination.length) { 1095 | throw new IllegalArgumentException(String.format( 1096 | "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); 1097 | } // end if 1098 | 1099 | 1100 | byte[] DECODABET = getDecodabet(options); 1101 | 1102 | // Example: Dk== 1103 | if (source[srcOffset + 2] == EQUALS_SIGN) { 1104 | // Two ways to do the same thing. Don't know which way I like best. 1105 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1106 | // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); 1107 | int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) 1108 | | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); 1109 | 1110 | destination[destOffset] = (byte) (outBuff >>> 16); 1111 | return 1; 1112 | } 1113 | 1114 | // Example: DkL= 1115 | else if (source[srcOffset + 3] == EQUALS_SIGN) { 1116 | // Two ways to do the same thing. Don't know which way I like best. 1117 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1118 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1119 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); 1120 | int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) 1121 | | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) 1122 | | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); 1123 | 1124 | destination[destOffset] = (byte) (outBuff >>> 16); 1125 | destination[destOffset + 1] = (byte) (outBuff >>> 8); 1126 | return 2; 1127 | } 1128 | 1129 | // Example: DkLE 1130 | else { 1131 | // Two ways to do the same thing. Don't know which way I like best. 1132 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1133 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1134 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) 1135 | // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); 1136 | int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) 1137 | | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) 1138 | | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) 1139 | | ((DECODABET[source[srcOffset + 3]] & 0xFF)); 1140 | 1141 | 1142 | destination[destOffset] = (byte) (outBuff >> 16); 1143 | destination[destOffset + 1] = (byte) (outBuff >> 8); 1144 | destination[destOffset + 2] = (byte) (outBuff); 1145 | 1146 | return 3; 1147 | } 1148 | } // end decodeToBytes 1149 | 1150 | 1151 | /** 1152 | * Low-level access to decoding ASCII characters in 1153 | * the form of a byte array. Ignores GUNZIP option, if 1154 | * it's set. This is not generally a recommended method, 1155 | * although it is used internally as part of the decoding process. 1156 | * Special case: if len = 0, an empty array is returned. Still, 1157 | * if you need more speed and reduced memory footprint (and aren't 1158 | * gzipping), consider this method. 1159 | * 1160 | * @param source The Base64 encoded data 1161 | * @return decoded data 1162 | * @since 2.3.1 1163 | */ 1164 | public static byte[] decode(byte[] source) { 1165 | byte[] decoded = null; 1166 | try { 1167 | decoded = decode(source, 0, source.length, Base64.NO_OPTIONS); 1168 | } catch (java.io.IOException ex) { 1169 | assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 1170 | } 1171 | return decoded; 1172 | } 1173 | 1174 | 1175 | /** 1176 | * Low-level access to decoding ASCII characters in 1177 | * the form of a byte array. Ignores GUNZIP option, if 1178 | * it's set. This is not generally a recommended method, 1179 | * although it is used internally as part of the decoding process. 1180 | * Special case: if len = 0, an empty array is returned. Still, 1181 | * if you need more speed and reduced memory footprint (and aren't 1182 | * gzipping), consider this method. 1183 | * 1184 | * @param source The Base64 encoded data 1185 | * @param off The offset of where to begin decoding 1186 | * @param len The length of characters to decode 1187 | * @param options Can specify options such as alphabet type to use 1188 | * @return decoded data 1189 | * @throws java.io.IOException If bogus characters exist in source data 1190 | * @since 1.3 1191 | */ 1192 | public static byte[] decode(byte[] source, int off, int len, int options) 1193 | throws java.io.IOException { 1194 | 1195 | // Lots of error checking and exception throwing 1196 | if (source == null) { 1197 | throw new NullPointerException("Cannot decode null source array."); 1198 | } // end if 1199 | if (off < 0 || off + len > source.length) { 1200 | throw new IllegalArgumentException(String.format( 1201 | "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len)); 1202 | } // end if 1203 | 1204 | if (len == 0) { 1205 | return new byte[0]; 1206 | } else if (len < 4) { 1207 | throw new IllegalArgumentException( 1208 | "Base64-encoded string must have at least four characters, but length specified was " + len); 1209 | } // end if 1210 | 1211 | byte[] DECODABET = getDecodabet(options); 1212 | 1213 | int len34 = len * 3 / 4; // Estimate on array size 1214 | byte[] outBuff = new byte[len34]; // Upper limit on size of output 1215 | int outBuffPosn = 0; // Keep track of where we're writing 1216 | 1217 | byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space 1218 | int b4Posn = 0; // Keep track of four byte input buffer 1219 | int i = 0; // Source array counter 1220 | byte sbiCrop = 0; // Low seven bits (ASCII) of input 1221 | byte sbiDecode = 0; // Special value from DECODABET 1222 | 1223 | for (i = off; i < off + len; i++) { // Loop through source 1224 | 1225 | sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits 1226 | sbiDecode = DECODABET[sbiCrop]; // Special value 1227 | 1228 | // White space, Equals sign, or legit Base64 character 1229 | // Note the values such as -5 and -9 in the 1230 | // DECODABETs at the top of the file. 1231 | if (sbiDecode >= WHITE_SPACE_ENC) { 1232 | if (sbiDecode >= EQUALS_SIGN_ENC) { 1233 | b4[b4Posn++] = sbiCrop; // Save non-whitespace 1234 | if (b4Posn > 3) { // Time to decode? 1235 | outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options); 1236 | b4Posn = 0; 1237 | 1238 | // If that was the equals sign, break out of 'for' loop 1239 | if (sbiCrop == EQUALS_SIGN) { 1240 | break; 1241 | } // end if: equals sign 1242 | } // end if: quartet built 1243 | } // end if: equals sign or better 1244 | } // end if: white space, equals sign or better 1245 | else { 1246 | // There's a bad input character in the Base64 stream. 1247 | throw new java.io.IOException(String.format( 1248 | "Bad Base64 input character '%c' in array position %d", source[i], i)); 1249 | } // end else: 1250 | } // each input character 1251 | 1252 | byte[] out = new byte[outBuffPosn]; 1253 | System.arraycopy(outBuff, 0, out, 0, outBuffPosn); 1254 | return out; 1255 | } // end decode 1256 | 1257 | 1258 | /** 1259 | * Decodes data from Base64 notation, automatically 1260 | * detecting gzip-compressed data and decompressing it. 1261 | * 1262 | * @param s the string to decode 1263 | * @return the decoded data 1264 | * @throws java.io.IOException If there is a problem 1265 | * @since 1.4 1266 | */ 1267 | public static byte[] decode(String s) throws java.io.IOException { 1268 | return decode(s, NO_OPTIONS); 1269 | } 1270 | 1271 | 1272 | public static byte[] decodeWithoutPadding(String source) throws java.io.IOException { 1273 | int padding = source.length() % 4; 1274 | 1275 | if (padding == 1) source = source + "="; 1276 | else if (padding == 2) source = source + "=="; 1277 | else if (padding == 3) source = source + "="; 1278 | 1279 | return decode(source); 1280 | } 1281 | 1282 | 1283 | /** 1284 | * Decodes data from Base64 notation, automatically 1285 | * detecting gzip-compressed data and decompressing it. 1286 | * 1287 | * @param s the string to decode 1288 | * @param options encode options such as URL_SAFE 1289 | * @return the decoded data 1290 | * @throws java.io.IOException if there is an error 1291 | * @throws NullPointerException if s is null 1292 | * @since 1.4 1293 | */ 1294 | public static byte[] decode(String s, int options) throws java.io.IOException { 1295 | 1296 | if (s == null) { 1297 | throw new NullPointerException("Input string was null."); 1298 | } // end if 1299 | 1300 | byte[] bytes; 1301 | try { 1302 | bytes = s.getBytes(PREFERRED_ENCODING); 1303 | } // end try 1304 | catch (java.io.UnsupportedEncodingException uee) { 1305 | bytes = s.getBytes(); 1306 | } // end catch 1307 | // 1308 | 1309 | // Decode 1310 | bytes = decode(bytes, 0, bytes.length, options); 1311 | 1312 | // Check to see if it's gzip-compressed 1313 | // GZIP Magic Two-Byte Number: 0x8b1f (35615) 1314 | boolean dontGunzip = (options & DONT_GUNZIP) != 0; 1315 | if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) { 1316 | 1317 | int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); 1318 | if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { 1319 | java.io.ByteArrayInputStream bais = null; 1320 | java.util.zip.GZIPInputStream gzis = null; 1321 | java.io.ByteArrayOutputStream baos = null; 1322 | byte[] buffer = new byte[2048]; 1323 | int length = 0; 1324 | 1325 | try { 1326 | baos = new java.io.ByteArrayOutputStream(); 1327 | bais = new java.io.ByteArrayInputStream(bytes); 1328 | gzis = new java.util.zip.GZIPInputStream(bais); 1329 | 1330 | while ((length = gzis.read(buffer)) >= 0) { 1331 | baos.write(buffer, 0, length); 1332 | } // end while: reading input 1333 | 1334 | // No error? Get new bytes. 1335 | bytes = baos.toByteArray(); 1336 | 1337 | } // end try 1338 | catch (java.io.IOException e) { 1339 | e.printStackTrace(); 1340 | // Just return originally-decoded bytes 1341 | } // end catch 1342 | finally { 1343 | try { 1344 | baos.close(); 1345 | } catch (Exception e) { 1346 | } 1347 | try { 1348 | gzis.close(); 1349 | } catch (Exception e) { 1350 | } 1351 | try { 1352 | bais.close(); 1353 | } catch (Exception e) { 1354 | } 1355 | } // end finally 1356 | 1357 | } // end if: gzipped 1358 | } // end if: bytes.length >= 2 1359 | 1360 | return bytes; 1361 | } // end decode 1362 | 1363 | 1364 | /** 1365 | * Attempts to decode Base64 data and deserialize a Java 1366 | * Object within. Returns null if there was an error. 1367 | * 1368 | * @param encodedObject The Base64 data to decode 1369 | * @return The decoded and deserialized object 1370 | * @throws NullPointerException if encodedObject is null 1371 | * @throws java.io.IOException if there is a general error 1372 | * @throws ClassNotFoundException if the decoded object is of a 1373 | * class that cannot be found by the JVM 1374 | * @since 1.5 1375 | */ 1376 | public static Object decodeToObject(String encodedObject) 1377 | throws java.io.IOException, java.lang.ClassNotFoundException { 1378 | return decodeToObject(encodedObject, NO_OPTIONS, null); 1379 | } 1380 | 1381 | 1382 | /** 1383 | * Attempts to decode Base64 data and deserialize a Java 1384 | * Object within. Returns null if there was an error. 1385 | * If loader is not null, it will be the class loader 1386 | * used when deserializing. 1387 | * 1388 | * @param encodedObject The Base64 data to decode 1389 | * @param options Various parameters related to decoding 1390 | * @param loader Optional class loader to use in deserializing classes. 1391 | * @return The decoded and deserialized object 1392 | * @throws NullPointerException if encodedObject is null 1393 | * @throws java.io.IOException if there is a general error 1394 | * @throws ClassNotFoundException if the decoded object is of a 1395 | * class that cannot be found by the JVM 1396 | * @since 2.3.4 1397 | */ 1398 | public static Object decodeToObject( 1399 | String encodedObject, int options, final ClassLoader loader) 1400 | throws java.io.IOException, java.lang.ClassNotFoundException { 1401 | 1402 | // Decode and gunzip if necessary 1403 | byte[] objBytes = decode(encodedObject, options); 1404 | 1405 | java.io.ByteArrayInputStream bais = null; 1406 | java.io.ObjectInputStream ois = null; 1407 | Object obj = null; 1408 | 1409 | try { 1410 | bais = new java.io.ByteArrayInputStream(objBytes); 1411 | 1412 | // If no custom class loader is provided, use Java's builtin OIS. 1413 | if (loader == null) { 1414 | ois = new java.io.ObjectInputStream(bais); 1415 | } // end if: no loader provided 1416 | 1417 | // Else make a customized object input stream that uses 1418 | // the provided class loader. 1419 | else { 1420 | ois = new java.io.ObjectInputStream(bais) { 1421 | @Override 1422 | public Class resolveClass(java.io.ObjectStreamClass streamClass) 1423 | throws java.io.IOException, ClassNotFoundException { 1424 | Class c = Class.forName(streamClass.getName(), false, loader); 1425 | if (c == null) { 1426 | return super.resolveClass(streamClass); 1427 | } else { 1428 | return c; // Class loader knows of this class. 1429 | } // end else: not null 1430 | } // end resolveClass 1431 | }; // end ois 1432 | } // end else: no custom class loader 1433 | 1434 | obj = ois.readObject(); 1435 | } // end try 1436 | catch (java.io.IOException e) { 1437 | throw e; // Catch and throw in order to execute finally{} 1438 | } // end catch 1439 | catch (java.lang.ClassNotFoundException e) { 1440 | throw e; // Catch and throw in order to execute finally{} 1441 | } // end catch 1442 | finally { 1443 | try { 1444 | bais.close(); 1445 | } catch (Exception e) { 1446 | } 1447 | try { 1448 | ois.close(); 1449 | } catch (Exception e) { 1450 | } 1451 | } // end finally 1452 | 1453 | return obj; 1454 | } // end decodeObject 1455 | 1456 | 1457 | /** 1458 | * Convenience method for encoding data to a file. 1459 | * 1460 | *

As of v 2.3, if there is a error, 1461 | * the method will throw an java.io.IOException. This is new to v2.3! 1462 | * In earlier versions, it just returned false, but 1463 | * in retrospect that's a pretty poor way to handle it.

1464 | * 1465 | * @param dataToEncode byte array of data to encode in base64 form 1466 | * @param filename Filename for saving encoded data 1467 | * @throws java.io.IOException if there is an error 1468 | * @throws NullPointerException if dataToEncode is null 1469 | * @since 2.1 1470 | */ 1471 | public static void encodeToFile(byte[] dataToEncode, String filename) 1472 | throws java.io.IOException { 1473 | 1474 | if (dataToEncode == null) { 1475 | throw new NullPointerException("Data to encode was null."); 1476 | } // end iff 1477 | 1478 | Base64.OutputStream bos = null; 1479 | try { 1480 | bos = new Base64.OutputStream( 1481 | new java.io.FileOutputStream(filename), Base64.ENCODE); 1482 | bos.write(dataToEncode); 1483 | } // end try 1484 | catch (java.io.IOException e) { 1485 | throw e; // Catch and throw to execute finally{} block 1486 | } // end catch: java.io.IOException 1487 | finally { 1488 | try { 1489 | bos.close(); 1490 | } catch (Exception e) { 1491 | } 1492 | } // end finally 1493 | 1494 | } // end encodeToFile 1495 | 1496 | 1497 | /** 1498 | * Convenience method for decoding data to a file. 1499 | * 1500 | *

As of v 2.3, if there is a error, 1501 | * the method will throw an java.io.IOException. This is new to v2.3! 1502 | * In earlier versions, it just returned false, but 1503 | * in retrospect that's a pretty poor way to handle it.

1504 | * 1505 | * @param dataToDecode Base64-encoded data as a string 1506 | * @param filename Filename for saving decoded data 1507 | * @throws java.io.IOException if there is an error 1508 | * @since 2.1 1509 | */ 1510 | public static void decodeToFile(String dataToDecode, String filename) 1511 | throws java.io.IOException { 1512 | 1513 | Base64.OutputStream bos = null; 1514 | try { 1515 | bos = new Base64.OutputStream( 1516 | new java.io.FileOutputStream(filename), Base64.DECODE); 1517 | bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); 1518 | } // end try 1519 | catch (java.io.IOException e) { 1520 | throw e; // Catch and throw to execute finally{} block 1521 | } // end catch: java.io.IOException 1522 | finally { 1523 | try { 1524 | bos.close(); 1525 | } catch (Exception e) { 1526 | } 1527 | } // end finally 1528 | 1529 | } // end decodeToFile 1530 | 1531 | 1532 | /** 1533 | * Convenience method for reading a base64-encoded 1534 | * file and decoding it. 1535 | * 1536 | *

As of v 2.3, if there is a error, 1537 | * the method will throw an java.io.IOException. This is new to v2.3! 1538 | * In earlier versions, it just returned false, but 1539 | * in retrospect that's a pretty poor way to handle it.

1540 | * 1541 | * @param filename Filename for reading encoded data 1542 | * @return decoded byte array 1543 | * @throws java.io.IOException if there is an error 1544 | * @since 2.1 1545 | */ 1546 | public static byte[] decodeFromFile(String filename) 1547 | throws java.io.IOException { 1548 | 1549 | byte[] decodedData = null; 1550 | Base64.InputStream bis = null; 1551 | try { 1552 | // Set up some useful variables 1553 | java.io.File file = new java.io.File(filename); 1554 | byte[] buffer = null; 1555 | int length = 0; 1556 | int numBytes = 0; 1557 | 1558 | // Check for size of file 1559 | if (file.length() > Integer.MAX_VALUE) { 1560 | throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes)."); 1561 | } // end if: file too big for int index 1562 | buffer = new byte[(int) file.length()]; 1563 | 1564 | // Open a stream 1565 | bis = new Base64.InputStream( 1566 | new java.io.BufferedInputStream( 1567 | new java.io.FileInputStream(file)), Base64.DECODE); 1568 | 1569 | // Read until done 1570 | while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { 1571 | length += numBytes; 1572 | } // end while 1573 | 1574 | // Save in a variable to return 1575 | decodedData = new byte[length]; 1576 | System.arraycopy(buffer, 0, decodedData, 0, length); 1577 | 1578 | } // end try 1579 | catch (java.io.IOException e) { 1580 | throw e; // Catch and release to execute finally{} 1581 | } // end catch: java.io.IOException 1582 | finally { 1583 | try { 1584 | bis.close(); 1585 | } catch (Exception e) { 1586 | } 1587 | } // end finally 1588 | 1589 | return decodedData; 1590 | } // end decodeFromFile 1591 | 1592 | 1593 | /** 1594 | * Convenience method for reading a binary file 1595 | * and base64-encoding it. 1596 | * 1597 | *

As of v 2.3, if there is a error, 1598 | * the method will throw an java.io.IOException. This is new to v2.3! 1599 | * In earlier versions, it just returned false, but 1600 | * in retrospect that's a pretty poor way to handle it.

1601 | * 1602 | * @param filename Filename for reading binary data 1603 | * @return base64-encoded string 1604 | * @throws java.io.IOException if there is an error 1605 | * @since 2.1 1606 | */ 1607 | public static String encodeFromFile(String filename) 1608 | throws java.io.IOException { 1609 | 1610 | String encodedData = null; 1611 | Base64.InputStream bis = null; 1612 | try { 1613 | // Set up some useful variables 1614 | java.io.File file = new java.io.File(filename); 1615 | byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; // Need max() for math on small files (v2.2.1) 1616 | int length = 0; 1617 | int numBytes = 0; 1618 | 1619 | // Open a stream 1620 | bis = new Base64.InputStream( 1621 | new java.io.BufferedInputStream( 1622 | new java.io.FileInputStream(file)), Base64.ENCODE); 1623 | 1624 | // Read until done 1625 | while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { 1626 | length += numBytes; 1627 | } // end while 1628 | 1629 | // Save in a variable to return 1630 | encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); 1631 | 1632 | } // end try 1633 | catch (java.io.IOException e) { 1634 | throw e; // Catch and release to execute finally{} 1635 | } // end catch: java.io.IOException 1636 | finally { 1637 | try { 1638 | bis.close(); 1639 | } catch (Exception e) { 1640 | } 1641 | } // end finally 1642 | 1643 | return encodedData; 1644 | } // end encodeFromFile 1645 | 1646 | /** 1647 | * Reads infile and encodes it to outfile. 1648 | * 1649 | * @param infile Input file 1650 | * @param outfile Output file 1651 | * @throws java.io.IOException if there is an error 1652 | * @since 2.2 1653 | */ 1654 | public static void encodeFileToFile(String infile, String outfile) 1655 | throws java.io.IOException { 1656 | 1657 | String encoded = Base64.encodeFromFile(infile); 1658 | java.io.OutputStream out = null; 1659 | try { 1660 | out = new java.io.BufferedOutputStream( 1661 | new java.io.FileOutputStream(outfile)); 1662 | out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output. 1663 | } // end try 1664 | catch (java.io.IOException e) { 1665 | throw e; // Catch and release to execute finally{} 1666 | } // end catch 1667 | finally { 1668 | try { 1669 | out.close(); 1670 | } catch (Exception ex) { 1671 | } 1672 | } // end finally 1673 | } // end encodeFileToFile 1674 | 1675 | 1676 | /** 1677 | * Reads infile and decodes it to outfile. 1678 | * 1679 | * @param infile Input file 1680 | * @param outfile Output file 1681 | * @throws java.io.IOException if there is an error 1682 | * @since 2.2 1683 | */ 1684 | public static void decodeFileToFile(String infile, String outfile) 1685 | throws java.io.IOException { 1686 | 1687 | byte[] decoded = Base64.decodeFromFile(infile); 1688 | java.io.OutputStream out = null; 1689 | try { 1690 | out = new java.io.BufferedOutputStream( 1691 | new java.io.FileOutputStream(outfile)); 1692 | out.write(decoded); 1693 | } // end try 1694 | catch (java.io.IOException e) { 1695 | throw e; // Catch and release to execute finally{} 1696 | } // end catch 1697 | finally { 1698 | try { 1699 | out.close(); 1700 | } catch (Exception ex) { 1701 | } 1702 | } // end finally 1703 | } // end decodeFileToFile 1704 | 1705 | 1706 | /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ 1707 | 1708 | 1709 | /** 1710 | * A {@link Base64.InputStream} will read data from another 1711 | * java.io.InputStream, given in the constructor, 1712 | * and encode/decode to/from Base64 notation on the fly. 1713 | * 1714 | * @see Base64 1715 | * @since 1.3 1716 | */ 1717 | public static class InputStream extends java.io.FilterInputStream { 1718 | 1719 | private boolean encode; // Encoding or decoding 1720 | private int position; // Current position in the buffer 1721 | private byte[] buffer; // Small buffer holding converted data 1722 | private int bufferLength; // Length of buffer (3 or 4) 1723 | private int numSigBytes; // Number of meaningful bytes in the buffer 1724 | private int lineLength; 1725 | private boolean breakLines; // Break lines at less than 80 characters 1726 | private int options; // Record options used to create the stream. 1727 | private byte[] decodabet; // Local copies to avoid extra method calls 1728 | 1729 | 1730 | /** 1731 | * Constructs a {@link Base64.InputStream} in DECODE mode. 1732 | * 1733 | * @param in the java.io.InputStream from which to read data. 1734 | * @since 1.3 1735 | */ 1736 | public InputStream(java.io.InputStream in) { 1737 | this(in, DECODE); 1738 | } // end constructor 1739 | 1740 | 1741 | /** 1742 | * Constructs a {@link Base64.InputStream} in 1743 | * either ENCODE or DECODE mode. 1744 | * 1745 | * Valid options:
1746 |          *   ENCODE or DECODE: Encode or Decode as data is read.
1747 |          *   DO_BREAK_LINES: break lines at 76 characters
1748 |          *     (only meaningful when encoding)
1749 |          * 
1750 | * 1751 | * Example: new Base64.InputStream( in, Base64.DECODE ) 1752 | * 1753 | * @param in the java.io.InputStream from which to read data. 1754 | * @param options Specified options 1755 | * @see Base64#ENCODE 1756 | * @see Base64#DECODE 1757 | * @see Base64#DO_BREAK_LINES 1758 | * @since 2.0 1759 | */ 1760 | public InputStream(java.io.InputStream in, int options) { 1761 | 1762 | super(in); 1763 | this.options = options; // Record for later 1764 | this.breakLines = (options & DO_BREAK_LINES) > 0; 1765 | this.encode = (options & ENCODE) > 0; 1766 | this.bufferLength = encode ? 4 : 3; 1767 | this.buffer = new byte[bufferLength]; 1768 | this.position = -1; 1769 | this.lineLength = 0; 1770 | this.decodabet = getDecodabet(options); 1771 | } // end constructor 1772 | 1773 | /** 1774 | * Reads enough of the input stream to convert 1775 | * to/from Base64 and returns the next byte. 1776 | * 1777 | * @return next byte 1778 | * @since 1.3 1779 | */ 1780 | @Override 1781 | public int read() throws java.io.IOException { 1782 | 1783 | // Do we need to get data? 1784 | if (position < 0) { 1785 | if (encode) { 1786 | byte[] b3 = new byte[3]; 1787 | int numBinaryBytes = 0; 1788 | for (int i = 0; i < 3; i++) { 1789 | int b = in.read(); 1790 | 1791 | // If end of stream, b is -1. 1792 | if (b >= 0) { 1793 | b3[i] = (byte) b; 1794 | numBinaryBytes++; 1795 | } else { 1796 | break; // out of for loop 1797 | } // end else: end of stream 1798 | 1799 | } // end for: each needed input byte 1800 | 1801 | if (numBinaryBytes > 0) { 1802 | encode3to4(b3, 0, numBinaryBytes, buffer, 0, options); 1803 | position = 0; 1804 | numSigBytes = 4; 1805 | } // end if: got data 1806 | else { 1807 | return -1; // Must be end of stream 1808 | } // end else 1809 | } // end if: encoding 1810 | 1811 | // Else decoding 1812 | else { 1813 | byte[] b4 = new byte[4]; 1814 | int i = 0; 1815 | for (i = 0; i < 4; i++) { 1816 | // Read four "meaningful" bytes: 1817 | int b = 0; 1818 | do { 1819 | b = in.read(); 1820 | } 1821 | while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC); 1822 | 1823 | if (b < 0) { 1824 | break; // Reads a -1 if end of stream 1825 | } // end if: end of stream 1826 | 1827 | b4[i] = (byte) b; 1828 | } // end for: each needed input byte 1829 | 1830 | if (i == 4) { 1831 | numSigBytes = decode4to3(b4, 0, buffer, 0, options); 1832 | position = 0; 1833 | } // end if: got four characters 1834 | else if (i == 0) { 1835 | return -1; 1836 | } // end else if: also padded correctly 1837 | else { 1838 | // Must have broken out from above. 1839 | throw new java.io.IOException("Improperly padded Base64 input."); 1840 | } // end 1841 | 1842 | } // end else: decode 1843 | } // end else: get data 1844 | 1845 | // Got data? 1846 | if (position >= 0) { 1847 | // End of relevant data? 1848 | if ( /*!encode &&*/ position >= numSigBytes) { 1849 | return -1; 1850 | } // end if: got data 1851 | 1852 | if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { 1853 | lineLength = 0; 1854 | return '\n'; 1855 | } // end if 1856 | else { 1857 | lineLength++; // This isn't important when decoding 1858 | // but throwing an extra "if" seems 1859 | // just as wasteful. 1860 | 1861 | int b = buffer[position++]; 1862 | 1863 | if (position >= bufferLength) { 1864 | position = -1; 1865 | } // end if: end 1866 | 1867 | return b & 0xFF; // This is how you "cast" a byte that's 1868 | // intended to be unsigned. 1869 | } // end else 1870 | } // end if: position >= 0 1871 | 1872 | // Else error 1873 | else { 1874 | throw new java.io.IOException("Error in Base64 code reading stream."); 1875 | } // end else 1876 | } // end read 1877 | 1878 | 1879 | /** 1880 | * Calls {@link #read()} repeatedly until the end of stream 1881 | * is reached or len bytes are read. 1882 | * Returns number of bytes read into array or -1 if 1883 | * end of stream is encountered. 1884 | * 1885 | * @param dest array to hold values 1886 | * @param off offset for array 1887 | * @param len max number of bytes to read into array 1888 | * @return bytes read into array or -1 if end of stream is encountered. 1889 | * @since 1.3 1890 | */ 1891 | @Override 1892 | public int read(byte[] dest, int off, int len) 1893 | throws java.io.IOException { 1894 | int i; 1895 | int b; 1896 | for (i = 0; i < len; i++) { 1897 | b = read(); 1898 | 1899 | if (b >= 0) { 1900 | dest[off + i] = (byte) b; 1901 | } else if (i == 0) { 1902 | return -1; 1903 | } else { 1904 | break; // Out of 'for' loop 1905 | } // Out of 'for' loop 1906 | } // end for: each byte read 1907 | return i; 1908 | } // end read 1909 | 1910 | } // end inner class InputStream 1911 | 1912 | 1913 | 1914 | 1915 | 1916 | 1917 | /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ 1918 | 1919 | 1920 | /** 1921 | * A {@link Base64.OutputStream} will write data to another 1922 | * java.io.OutputStream, given in the constructor, 1923 | * and encode/decode to/from Base64 notation on the fly. 1924 | * 1925 | * @see Base64 1926 | * @since 1.3 1927 | */ 1928 | public static class OutputStream extends java.io.FilterOutputStream { 1929 | 1930 | private boolean encode; 1931 | private int position; 1932 | private byte[] buffer; 1933 | private int bufferLength; 1934 | private int lineLength; 1935 | private boolean breakLines; 1936 | private byte[] b4; // Scratch used in a few places 1937 | private boolean suspendEncoding; 1938 | private int options; // Record for later 1939 | private byte[] decodabet; // Local copies to avoid extra method calls 1940 | 1941 | /** 1942 | * Constructs a {@link Base64.OutputStream} in ENCODE mode. 1943 | * 1944 | * @param out the java.io.OutputStream to which data will be written. 1945 | * @since 1.3 1946 | */ 1947 | public OutputStream(java.io.OutputStream out) { 1948 | this(out, ENCODE); 1949 | } // end constructor 1950 | 1951 | 1952 | /** 1953 | * Constructs a {@link Base64.OutputStream} in 1954 | * either ENCODE or DECODE mode. 1955 | * 1956 | * Valid options:
1957 |          *   ENCODE or DECODE: Encode or Decode as data is read.
1958 |          *   DO_BREAK_LINES: don't break lines at 76 characters
1959 |          *     (only meaningful when encoding)
1960 |          * 
1961 | * 1962 | * Example: new Base64.OutputStream( out, Base64.ENCODE ) 1963 | * 1964 | * @param out the java.io.OutputStream to which data will be written. 1965 | * @param options Specified options. 1966 | * @see Base64#ENCODE 1967 | * @see Base64#DECODE 1968 | * @see Base64#DO_BREAK_LINES 1969 | * @since 1.3 1970 | */ 1971 | public OutputStream(java.io.OutputStream out, int options) { 1972 | super(out); 1973 | this.breakLines = (options & DO_BREAK_LINES) != 0; 1974 | this.encode = (options & ENCODE) != 0; 1975 | this.bufferLength = encode ? 3 : 4; 1976 | this.buffer = new byte[bufferLength]; 1977 | this.position = 0; 1978 | this.lineLength = 0; 1979 | this.suspendEncoding = false; 1980 | this.b4 = new byte[4]; 1981 | this.options = options; 1982 | this.decodabet = getDecodabet(options); 1983 | } // end constructor 1984 | 1985 | 1986 | /** 1987 | * Writes the byte to the output stream after 1988 | * converting to/from Base64 notation. 1989 | * When encoding, bytes are buffered three 1990 | * at a time before the output stream actually 1991 | * gets a write() call. 1992 | * When decoding, bytes are buffered four 1993 | * at a time. 1994 | * 1995 | * @param theByte the byte to write 1996 | * @since 1.3 1997 | */ 1998 | @Override 1999 | public void write(int theByte) 2000 | throws java.io.IOException { 2001 | // Encoding suspended? 2002 | if (suspendEncoding) { 2003 | this.out.write(theByte); 2004 | return; 2005 | } // end if: supsended 2006 | 2007 | // Encode? 2008 | if (encode) { 2009 | buffer[position++] = (byte) theByte; 2010 | if (position >= bufferLength) { // Enough to encode. 2011 | 2012 | this.out.write(encode3to4(b4, buffer, bufferLength, options)); 2013 | 2014 | lineLength += 4; 2015 | if (breakLines && lineLength >= MAX_LINE_LENGTH) { 2016 | this.out.write(NEW_LINE); 2017 | lineLength = 0; 2018 | } // end if: end of line 2019 | 2020 | position = 0; 2021 | } // end if: enough to output 2022 | } // end if: encoding 2023 | 2024 | // Else, Decoding 2025 | else { 2026 | // Meaningful Base64 character? 2027 | if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) { 2028 | buffer[position++] = (byte) theByte; 2029 | if (position >= bufferLength) { // Enough to output. 2030 | 2031 | int len = Base64.decode4to3(buffer, 0, b4, 0, options); 2032 | out.write(b4, 0, len); 2033 | position = 0; 2034 | } // end if: enough to output 2035 | } // end if: meaningful base64 character 2036 | else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) { 2037 | throw new java.io.IOException("Invalid character in Base64 data."); 2038 | } // end else: not white space either 2039 | } // end else: decoding 2040 | } // end write 2041 | 2042 | 2043 | /** 2044 | * Calls {@link #write(int)} repeatedly until len 2045 | * bytes are written. 2046 | * 2047 | * @param theBytes array from which to read bytes 2048 | * @param off offset for array 2049 | * @param len max number of bytes to read into array 2050 | * @since 1.3 2051 | */ 2052 | @Override 2053 | public void write(byte[] theBytes, int off, int len) 2054 | throws java.io.IOException { 2055 | // Encoding suspended? 2056 | if (suspendEncoding) { 2057 | this.out.write(theBytes, off, len); 2058 | return; 2059 | } // end if: supsended 2060 | 2061 | for (int i = 0; i < len; i++) { 2062 | write(theBytes[off + i]); 2063 | } // end for: each byte written 2064 | 2065 | } // end write 2066 | 2067 | 2068 | /** 2069 | * Method added by PHIL. [Thanks, PHIL. -Rob] 2070 | * This pads the buffer without closing the stream. 2071 | * 2072 | * @throws java.io.IOException if there's an error. 2073 | */ 2074 | public void flushBase64() throws java.io.IOException { 2075 | if (position > 0) { 2076 | if (encode) { 2077 | out.write(encode3to4(b4, buffer, position, options)); 2078 | position = 0; 2079 | } // end if: encoding 2080 | else { 2081 | throw new java.io.IOException("Base64 input not properly padded."); 2082 | } // end else: decoding 2083 | } // end if: buffer partially full 2084 | 2085 | } // end flush 2086 | 2087 | 2088 | /** 2089 | * Flushes and closes (I think, in the superclass) the stream. 2090 | * 2091 | * @since 1.3 2092 | */ 2093 | @Override 2094 | public void close() throws java.io.IOException { 2095 | // 1. Ensure that pending characters are written 2096 | flushBase64(); 2097 | 2098 | // 2. Actually close the stream 2099 | // Base class both flushes and closes. 2100 | super.close(); 2101 | 2102 | buffer = null; 2103 | out = null; 2104 | } // end close 2105 | 2106 | 2107 | /** 2108 | * Suspends encoding of the stream. 2109 | * May be helpful if you need to embed a piece of 2110 | * base64-encoded data in a stream. 2111 | * 2112 | * @throws java.io.IOException if there's an error flushing 2113 | * @since 1.5.1 2114 | */ 2115 | public void suspendEncoding() throws java.io.IOException { 2116 | flushBase64(); 2117 | this.suspendEncoding = true; 2118 | } // end suspendEncoding 2119 | 2120 | 2121 | /** 2122 | * Resumes encoding of the stream. 2123 | * May be helpful if you need to embed a piece of 2124 | * base64-encoded data in a stream. 2125 | * 2126 | * @since 1.5.1 2127 | */ 2128 | public void resumeEncoding() { 2129 | this.suspendEncoding = false; 2130 | } // end resumeEncoding 2131 | 2132 | 2133 | } // end inner class OutputStream 2134 | 2135 | 2136 | } // end class Base64 2137 | --------------------------------------------------------------------------------