diff --git a/libs/protobuf-java-2.4.1.jar b/library/libs/protobuf-java-2.4.1.jar similarity index 100% rename from libs/protobuf-java-2.4.1.jar rename to library/libs/protobuf-java-2.4.1.jar diff --git a/library/libs/sc-light-jdk15on-1.47.0.2.jar b/library/libs/sc-light-jdk15on-1.47.0.2.jar new file mode 100644 index 0000000000..7cdbf856e5 Binary files /dev/null and b/library/libs/sc-light-jdk15on-1.47.0.2.jar differ diff --git a/protobuf/Makefile b/library/protobuf/Makefile similarity index 100% rename from protobuf/Makefile rename to library/protobuf/Makefile diff --git a/protobuf/PreKeyEntity.proto b/library/protobuf/PreKeyEntity.proto similarity index 69% rename from protobuf/PreKeyEntity.proto rename to library/protobuf/PreKeyEntity.proto index bce42a3f24..eae28cc31f 100644 --- a/protobuf/PreKeyEntity.proto +++ b/library/protobuf/PreKeyEntity.proto @@ -1,9 +1,9 @@ package textsecure; -option java_package = "org.thoughtcrime.securesms.encoded"; +option java_package = "org.whispersystems.textsecure.encoded"; option java_outer_classname = "PreKeyProtos"; message PreKeyEntity { optional uint64 id = 1; optional bytes key = 2; -} \ No newline at end of file +} diff --git a/src/org/thoughtcrime/securesms/crypto/IdentityKey.java b/library/src/org/whispersystems/textsecure/crypto/IdentityKey.java similarity index 95% rename from src/org/thoughtcrime/securesms/crypto/IdentityKey.java rename to library/src/org/whispersystems/textsecure/crypto/IdentityKey.java index 13a43d1762..2ea71a7fa2 100644 --- a/src/org/thoughtcrime/securesms/crypto/IdentityKey.java +++ b/library/src/org/whispersystems/textsecure/crypto/IdentityKey.java @@ -14,13 +14,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import android.os.Parcel; import android.os.Parcelable; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.thoughtcrime.securesms.util.Hex; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.util.Hex; /** * A class for representing an identity key. diff --git a/src/org/thoughtcrime/securesms/crypto/InvalidKeyException.java b/library/src/org/whispersystems/textsecure/crypto/InvalidKeyException.java similarity index 96% rename from src/org/thoughtcrime/securesms/crypto/InvalidKeyException.java rename to library/src/org/whispersystems/textsecure/crypto/InvalidKeyException.java index 18c1c2a891..144021dc17 100644 --- a/src/org/thoughtcrime/securesms/crypto/InvalidKeyException.java +++ b/library/src/org/whispersystems/textsecure/crypto/InvalidKeyException.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; public class InvalidKeyException extends Exception { diff --git a/src/org/thoughtcrime/securesms/crypto/InvalidMacException.java b/library/src/org/whispersystems/textsecure/crypto/InvalidMacException.java similarity index 96% rename from src/org/thoughtcrime/securesms/crypto/InvalidMacException.java rename to library/src/org/whispersystems/textsecure/crypto/InvalidMacException.java index 8736f091e3..f886ddaa9b 100644 --- a/src/org/thoughtcrime/securesms/crypto/InvalidMacException.java +++ b/library/src/org/whispersystems/textsecure/crypto/InvalidMacException.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; public class InvalidMacException extends Exception { diff --git a/src/org/thoughtcrime/securesms/util/InvalidMessageException.java b/library/src/org/whispersystems/textsecure/crypto/InvalidMessageException.java similarity index 96% rename from src/org/thoughtcrime/securesms/util/InvalidMessageException.java rename to library/src/org/whispersystems/textsecure/crypto/InvalidMessageException.java index 713c19fdd8..a978d60200 100644 --- a/src/org/thoughtcrime/securesms/util/InvalidMessageException.java +++ b/library/src/org/whispersystems/textsecure/crypto/InvalidMessageException.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.util; +package org.whispersystems.textsecure.crypto; public class InvalidMessageException extends Exception { diff --git a/src/org/thoughtcrime/securesms/crypto/KeyPair.java b/library/src/org/whispersystems/textsecure/crypto/KeyPair.java similarity index 90% rename from src/org/thoughtcrime/securesms/crypto/KeyPair.java rename to library/src/org/whispersystems/textsecure/crypto/KeyPair.java index 8614049180..4795e637e2 100644 --- a/src/org/thoughtcrime/securesms/crypto/KeyPair.java +++ b/library/src/org/whispersystems/textsecure/crypto/KeyPair.java @@ -14,12 +14,12 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.thoughtcrime.securesms.util.Hex; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.util.Hex; import android.util.Log; diff --git a/src/org/thoughtcrime/securesms/crypto/KeyUtil.java b/library/src/org/whispersystems/textsecure/crypto/KeyUtil.java similarity index 81% rename from src/org/thoughtcrime/securesms/crypto/KeyUtil.java rename to library/src/org/whispersystems/textsecure/crypto/KeyUtil.java index d45b0bf08b..6fc722fdb8 100644 --- a/src/org/thoughtcrime/securesms/crypto/KeyUtil.java +++ b/library/src/org/whispersystems/textsecure/crypto/KeyUtil.java @@ -14,26 +14,25 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyGenerationParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECFieldElement; -import org.bouncycastle.math.ec.ECPoint; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; -import org.thoughtcrime.securesms.database.keys.PreKeyRecord; -import org.thoughtcrime.securesms.database.keys.RemoteKeyRecord; -import org.thoughtcrime.securesms.database.keys.SessionRecord; -import org.thoughtcrime.securesms.recipients.Recipient; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.agreement.ECDHBasicAgreement; +import org.spongycastle.crypto.generators.ECKeyPairGenerator; +import org.spongycastle.crypto.params.ECDomainParameters; +import org.spongycastle.crypto.params.ECKeyGenerationParameters; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.spongycastle.math.ec.ECCurve; +import org.spongycastle.math.ec.ECFieldElement; +import org.spongycastle.math.ec.ECPoint; +import org.whispersystems.textsecure.storage.CanonicalRecipientAddress; +import org.whispersystems.textsecure.storage.LocalKeyRecord; +import org.whispersystems.textsecure.storage.RemoteKeyRecord; +import org.whispersystems.textsecure.storage.SessionRecord; import android.content.Context; import android.util.Log; @@ -92,7 +91,7 @@ public class KeyUtil { } } - public static void abortSessionFor(Context context, Recipient recipient) { + public static void abortSessionFor(Context context, CanonicalRecipientAddress recipient) { //XXX Obviously we should probably do something more thorough here eventually. Log.w("KeyUtil", "Aborting session, deleting keys..."); LocalKeyRecord.delete(context, recipient); @@ -100,7 +99,7 @@ public class KeyUtil { SessionRecord.delete(context, recipient); } - public static boolean isSessionFor(Context context, Recipient recipient) { + public static boolean isSessionFor(Context context, CanonicalRecipientAddress recipient) { Log.w("KeyUtil", "Checking session..."); return (LocalKeyRecord.hasRecord(context, recipient)) && @@ -110,13 +109,16 @@ public class KeyUtil { public static boolean isIdentityKeyFor(Context context, MasterSecret masterSecret, - Recipient recipient) + CanonicalRecipientAddress recipient) { return isSessionFor(context, recipient) && new SessionRecord(context, masterSecret, recipient).getIdentityKey() != null; } - public static LocalKeyRecord initializeRecordFor(Recipient recipient, Context context, MasterSecret masterSecret) { + public static LocalKeyRecord initializeRecordFor(CanonicalRecipientAddress recipient, + Context context, + MasterSecret masterSecret) + { Log.w("KeyUtil", "Initializing local key pairs..."); try { SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); diff --git a/src/org/thoughtcrime/securesms/crypto/MasterCipher.java b/library/src/org/whispersystems/textsecure/crypto/MasterCipher.java similarity index 97% rename from src/org/thoughtcrime/securesms/crypto/MasterCipher.java rename to library/src/org/whispersystems/textsecure/crypto/MasterCipher.java index 66867212a8..8390c42a79 100644 --- a/src/org/thoughtcrime/securesms/crypto/MasterCipher.java +++ b/library/src/org/whispersystems/textsecure/crypto/MasterCipher.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import java.io.IOException; import java.math.BigInteger; @@ -32,10 +32,9 @@ import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; import org.whispersystems.textsecure.util.Base64; -import org.thoughtcrime.securesms.util.Hex; -import org.thoughtcrime.securesms.util.InvalidMessageException; +import org.whispersystems.textsecure.util.Hex; import android.util.Log; diff --git a/src/org/thoughtcrime/securesms/crypto/MasterSecret.java b/library/src/org/whispersystems/textsecure/crypto/MasterSecret.java similarity index 96% rename from src/org/thoughtcrime/securesms/crypto/MasterSecret.java rename to library/src/org/whispersystems/textsecure/crypto/MasterSecret.java index 4f6259ca9f..495454429b 100644 --- a/src/org/thoughtcrime/securesms/crypto/MasterSecret.java +++ b/library/src/org/whispersystems/textsecure/crypto/MasterSecret.java @@ -14,14 +14,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import android.os.Parcel; import android.os.Parcelable; -import org.bouncycastle.util.Arrays; - import javax.crypto.spec.SecretKeySpec; +import java.util.Arrays; /** * When a user first initializes TextSecure, a few secrets @@ -72,7 +71,7 @@ public class MasterSecret implements Parcelable { this.macKey = new SecretKeySpec(macKeyBytes, "HmacSHA1"); // SecretKeySpec does an internal copy in its constructor. - Arrays.fill(encryptionKeyBytes, (byte)0x00); + Arrays.fill(encryptionKeyBytes, (byte) 0x00); Arrays.fill(macKeyBytes, (byte)0x00); } diff --git a/src/org/thoughtcrime/securesms/crypto/MessageMac.java b/library/src/org/whispersystems/textsecure/crypto/MessageMac.java similarity index 97% rename from src/org/thoughtcrime/securesms/crypto/MessageMac.java rename to library/src/org/whispersystems/textsecure/crypto/MessageMac.java index fc86be79fa..4e237c88bd 100644 --- a/src/org/thoughtcrime/securesms/crypto/MessageMac.java +++ b/library/src/org/whispersystems/textsecure/crypto/MessageMac.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -23,7 +23,7 @@ import java.util.Arrays; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import org.thoughtcrime.securesms.util.Hex; +import org.whispersystems.textsecure.util.Hex; import android.util.Log; diff --git a/src/org/thoughtcrime/securesms/crypto/PreKeyPair.java b/library/src/org/whispersystems/textsecure/crypto/PreKeyPair.java similarity index 77% rename from src/org/thoughtcrime/securesms/crypto/PreKeyPair.java rename to library/src/org/whispersystems/textsecure/crypto/PreKeyPair.java index 717f4510e6..b150a940c4 100644 --- a/src/org/thoughtcrime/securesms/crypto/PreKeyPair.java +++ b/library/src/org/whispersystems/textsecure/crypto/PreKeyPair.java @@ -1,16 +1,15 @@ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.thoughtcrime.securesms.util.Util; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.util.Util; public class PreKeyPair { - private final MasterCipher masterCipher; + private final MasterCipher masterCipher; private final ECPrivateKeyParameters privateKey; - private final ECPublicKeyParameters publicKey; + private final ECPublicKeyParameters publicKey; public PreKeyPair(MasterSecret masterSecret, AsymmetricCipherKeyPair keyPair) { this.masterCipher = new MasterCipher(masterSecret); diff --git a/src/org/thoughtcrime/securesms/crypto/PreKeyUtil.java b/library/src/org/whispersystems/textsecure/crypto/PreKeyUtil.java similarity index 91% rename from src/org/thoughtcrime/securesms/crypto/PreKeyUtil.java rename to library/src/org/whispersystems/textsecure/crypto/PreKeyUtil.java index 42d6c5f18e..fb8a8cf5fa 100644 --- a/src/org/thoughtcrime/securesms/crypto/PreKeyUtil.java +++ b/library/src/org/whispersystems/textsecure/crypto/PreKeyUtil.java @@ -1,13 +1,13 @@ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import android.content.Context; import android.util.Log; import com.google.protobuf.ByteString; -import org.thoughtcrime.securesms.database.keys.InvalidKeyIdException; -import org.thoughtcrime.securesms.database.keys.PreKeyRecord; -import org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity; +import org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity; import org.whispersystems.textsecure.push.PreKeyList; +import org.whispersystems.textsecure.storage.InvalidKeyIdException; +import org.whispersystems.textsecure.storage.PreKeyRecord; import org.whispersystems.textsecure.util.Base64; import java.io.File; @@ -26,7 +26,7 @@ public class PreKeyUtil { for (int i=0;i. */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import android.util.Log; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.thoughtcrime.securesms.util.Hex; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.util.Hex; import org.whispersystems.textsecure.util.Conversions; import java.security.MessageDigest; diff --git a/src/org/thoughtcrime/securesms/crypto/SerializableKey.java b/library/src/org/whispersystems/textsecure/crypto/SerializableKey.java similarity index 94% rename from src/org/thoughtcrime/securesms/crypto/SerializableKey.java rename to library/src/org/whispersystems/textsecure/crypto/SerializableKey.java index 962e171f34..4799be688d 100644 --- a/src/org/thoughtcrime/securesms/crypto/SerializableKey.java +++ b/library/src/org/whispersystems/textsecure/crypto/SerializableKey.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; public interface SerializableKey { public byte[] serialize(); diff --git a/src/org/thoughtcrime/securesms/crypto/SessionCipher.java b/library/src/org/whispersystems/textsecure/crypto/SessionCipher.java similarity index 93% rename from src/org/thoughtcrime/securesms/crypto/SessionCipher.java rename to library/src/org/whispersystems/textsecure/crypto/SessionCipher.java index 3fd4e887c2..773bbfc9a9 100644 --- a/src/org/thoughtcrime/securesms/crypto/SessionCipher.java +++ b/library/src/org/whispersystems/textsecure/crypto/SessionCipher.java @@ -14,14 +14,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import android.content.Context; +import android.util.Log; + +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.agreement.ECDHBasicAgreement; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.protocol.Message; +import org.whispersystems.textsecure.storage.CanonicalRecipientAddress; +import org.whispersystems.textsecure.storage.InvalidKeyIdException; +import org.whispersystems.textsecure.storage.LocalKeyRecord; +import org.whispersystems.textsecure.storage.RemoteKeyRecord; +import org.whispersystems.textsecure.storage.SessionKey; +import org.whispersystems.textsecure.storage.SessionRecord; +import org.whispersystems.textsecure.util.Conversions; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; @@ -29,21 +37,12 @@ import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.thoughtcrime.securesms.database.keys.InvalidKeyIdException; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; -import org.thoughtcrime.securesms.database.keys.RemoteKeyRecord; -import org.thoughtcrime.securesms.database.keys.SessionKey; -import org.thoughtcrime.securesms.database.keys.SessionRecord; -import org.thoughtcrime.securesms.protocol.Message; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.whispersystems.textsecure.util.Conversions; - -import android.content.Context; -import android.util.Log; +import java.io.IOException; +import java.math.BigInteger; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; /** * This is where the session encryption magic happens. Implements a compressed version of the OTR protocol. @@ -64,10 +63,10 @@ public class SessionCipher { private final LocalKeyRecord localRecord; private final RemoteKeyRecord remoteRecord; private final SessionRecord sessionRecord; - private final MasterSecret masterSecret; + private final MasterSecret masterSecret; private final TransportDetails transportDetails; - public SessionCipher(Context context, MasterSecret masterSecret, Recipient recipient, TransportDetails transportDetails) { + public SessionCipher(Context context, MasterSecret masterSecret, CanonicalRecipientAddress recipient, TransportDetails transportDetails) { Log.w("SessionCipher", "Constructing session cipher..."); this.masterSecret = masterSecret; this.localRecord = new LocalKeyRecord(context, masterSecret, recipient); diff --git a/src/org/thoughtcrime/securesms/crypto/TransportDetails.java b/library/src/org/whispersystems/textsecure/crypto/TransportDetails.java similarity index 95% rename from src/org/thoughtcrime/securesms/crypto/TransportDetails.java rename to library/src/org/whispersystems/textsecure/crypto/TransportDetails.java index c5976d6d6a..b03398f9bc 100644 --- a/src/org/thoughtcrime/securesms/crypto/TransportDetails.java +++ b/library/src/org/whispersystems/textsecure/crypto/TransportDetails.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.crypto; +package org.whispersystems.textsecure.crypto; import java.io.IOException; diff --git a/src/org/thoughtcrime/securesms/encoded/PreKeyProtos.java b/library/src/org/whispersystems/textsecure/encoded/PreKeyProtos.java similarity index 79% rename from src/org/thoughtcrime/securesms/encoded/PreKeyProtos.java rename to library/src/org/whispersystems/textsecure/encoded/PreKeyProtos.java index 2694524abb..dd7a9cddce 100644 --- a/src/org/thoughtcrime/securesms/encoded/PreKeyProtos.java +++ b/library/src/org/whispersystems/textsecure/encoded/PreKeyProtos.java @@ -1,7 +1,7 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: PreKeyEntity.proto -package org.thoughtcrime.securesms.encoded; +package org.whispersystems.textsecure.encoded; public final class PreKeyProtos { private PreKeyProtos() {} @@ -39,12 +39,12 @@ public final class PreKeyProtos { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_descriptor; + return org.whispersystems.textsecure.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_fieldAccessorTable; + return org.whispersystems.textsecure.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_fieldAccessorTable; } private int bitField0_; @@ -119,41 +119,41 @@ public final class PreKeyProtos { return super.writeReplace(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom(byte[] data) + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom(java.io.InputStream input) + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseDelimitedFrom(java.io.InputStream input) + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { @@ -162,7 +162,7 @@ public final class PreKeyProtos { return null; } } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseDelimitedFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { @@ -173,12 +173,12 @@ public final class PreKeyProtos { return null; } } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } - public static org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity parseFrom( + public static org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { @@ -188,7 +188,7 @@ public final class PreKeyProtos { public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity prototype) { + public static Builder newBuilder(org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @@ -201,18 +201,18 @@ public final class PreKeyProtos { } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder - implements org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntityOrBuilder { + implements org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntityOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_descriptor; + return org.whispersystems.textsecure.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_fieldAccessorTable; + return org.whispersystems.textsecure.encoded.PreKeyProtos.internal_static_textsecure_PreKeyEntity_fieldAccessorTable; } - // Construct using org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.newBuilder() + // Construct using org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.newBuilder() private Builder() { maybeForceBuilderInitialization(); } @@ -244,24 +244,24 @@ public final class PreKeyProtos { public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.getDescriptor(); + return org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.getDescriptor(); } - public org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity getDefaultInstanceForType() { - return org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.getDefaultInstance(); + public org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity getDefaultInstanceForType() { + return org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.getDefaultInstance(); } - public org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity build() { - org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity result = buildPartial(); + public org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity build() { + org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } - private org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity buildParsed() + private org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity result = buildPartial(); + org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); @@ -269,8 +269,8 @@ public final class PreKeyProtos { return result; } - public org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity buildPartial() { - org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity result = new org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity(this); + public org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity buildPartial() { + org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity result = new org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { @@ -287,16 +287,16 @@ public final class PreKeyProtos { } public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity) { - return mergeFrom((org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity)other); + if (other instanceof org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity) { + return mergeFrom((org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity)other); } else { super.mergeFrom(other); return this; } } - public Builder mergeFrom(org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity other) { - if (other == org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.getDefaultInstance()) return this; + public Builder mergeFrom(org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity other) { + if (other == org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.getDefaultInstance()) return this; if (other.hasId()) { setId(other.getId()); } @@ -421,9 +421,9 @@ public final class PreKeyProtos { static { java.lang.String[] descriptorData = { "\n\022PreKeyEntity.proto\022\ntextsecure\"\'\n\014PreK" + - "eyEntity\022\n\n\002id\030\001 \001(\004\022\013\n\003key\030\002 \001(\014B2\n\"org" + - ".thoughtcrime.securesms.encodedB\014PreKeyP" + - "rotos" + "eyEntity\022\n\n\002id\030\001 \001(\004\022\013\n\003key\030\002 \001(\014B5\n%org" + + ".whispersystems.textsecure.encodedB\014PreK" + + "eyProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -436,8 +436,8 @@ public final class PreKeyProtos { com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_textsecure_PreKeyEntity_descriptor, new java.lang.String[] { "Id", "Key", }, - org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.class, - org.thoughtcrime.securesms.encoded.PreKeyProtos.PreKeyEntity.Builder.class); + org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.class, + org.whispersystems.textsecure.encoded.PreKeyProtos.PreKeyEntity.Builder.class); return null; } }; diff --git a/src/org/thoughtcrime/securesms/protocol/Message.java b/library/src/org/whispersystems/textsecure/protocol/Message.java similarity index 95% rename from src/org/thoughtcrime/securesms/protocol/Message.java rename to library/src/org/whispersystems/textsecure/protocol/Message.java index d65ee815d2..cd5c8ea73e 100644 --- a/src/org/thoughtcrime/securesms/protocol/Message.java +++ b/library/src/org/whispersystems/textsecure/protocol/Message.java @@ -14,13 +14,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.protocol; +package org.whispersystems.textsecure.protocol; import android.util.Log; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.InvalidMessageException; -import org.thoughtcrime.securesms.crypto.PublicKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.PublicKey; import org.whispersystems.textsecure.util.Conversions; import java.nio.ByteBuffer; diff --git a/library/src/org/whispersystems/textsecure/storage/CanonicalRecipientAddress.java b/library/src/org/whispersystems/textsecure/storage/CanonicalRecipientAddress.java new file mode 100644 index 0000000000..7abb19ba4c --- /dev/null +++ b/library/src/org/whispersystems/textsecure/storage/CanonicalRecipientAddress.java @@ -0,0 +1,7 @@ +package org.whispersystems.textsecure.storage; + +import android.content.Context; + +public interface CanonicalRecipientAddress { + public long getCanonicalAddress(Context context); +} diff --git a/src/org/thoughtcrime/securesms/database/keys/InvalidKeyIdException.java b/library/src/org/whispersystems/textsecure/storage/InvalidKeyIdException.java similarity index 95% rename from src/org/thoughtcrime/securesms/database/keys/InvalidKeyIdException.java rename to library/src/org/whispersystems/textsecure/storage/InvalidKeyIdException.java index 053383b91d..920a633fa6 100644 --- a/src/org/thoughtcrime/securesms/database/keys/InvalidKeyIdException.java +++ b/library/src/org/whispersystems/textsecure/storage/InvalidKeyIdException.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; public class InvalidKeyIdException extends Exception { diff --git a/src/org/thoughtcrime/securesms/database/keys/LocalKeyRecord.java b/library/src/org/whispersystems/textsecure/storage/LocalKeyRecord.java similarity index 85% rename from src/org/thoughtcrime/securesms/database/keys/LocalKeyRecord.java rename to library/src/org/whispersystems/textsecure/storage/LocalKeyRecord.java index 536997be63..85f2637748 100644 --- a/src/org/thoughtcrime/securesms/database/keys/LocalKeyRecord.java +++ b/library/src/org/whispersystems/textsecure/storage/LocalKeyRecord.java @@ -14,18 +14,16 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.KeyPair; -import org.thoughtcrime.securesms.crypto.KeyUtil; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; -import org.thoughtcrime.securesms.recipients.Recipient; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.KeyPair; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -43,24 +41,24 @@ public class LocalKeyRecord extends Record { private final MasterCipher masterCipher; private final MasterSecret masterSecret; - public LocalKeyRecord(Context context, MasterSecret masterSecret, Recipient recipient) { + public LocalKeyRecord(Context context, MasterSecret masterSecret, CanonicalRecipientAddress recipient) { super(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); this.masterSecret = masterSecret; this.masterCipher = new MasterCipher(masterSecret); loadData(); } - public static boolean hasRecord(Context context, Recipient recipient) { + public static boolean hasRecord(Context context, CanonicalRecipientAddress recipient) { Log.w("LocalKeyRecord", "Checking: " + getFileNameForRecipient(context, recipient)); return Record.hasRecord(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); } - public static void delete(Context context, Recipient recipient) { + public static void delete(Context context, CanonicalRecipientAddress recipient) { Record.delete(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); } - private static String getFileNameForRecipient(Context context, Recipient recipient) { - return CanonicalAddressDatabase.getInstance(context).getCanonicalAddress(recipient.getNumber()) + "-local"; + private static String getFileNameForRecipient(Context context, CanonicalRecipientAddress recipient) { + return recipient.getCanonicalAddress(context) + "-local"; } public void advanceKeyIfNecessary(int keyId) { diff --git a/src/org/thoughtcrime/securesms/database/keys/PreKeyRecord.java b/library/src/org/whispersystems/textsecure/storage/PreKeyRecord.java similarity index 84% rename from src/org/thoughtcrime/securesms/database/keys/PreKeyRecord.java rename to library/src/org/whispersystems/textsecure/storage/PreKeyRecord.java index d98b07c411..f084c2dc59 100644 --- a/src/org/thoughtcrime/securesms/database/keys/PreKeyRecord.java +++ b/library/src/org/whispersystems/textsecure/storage/PreKeyRecord.java @@ -1,12 +1,11 @@ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.PreKeyPair; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PreKeyPair; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -19,7 +18,6 @@ public class PreKeyRecord extends Record { private static final Object FILE_LOCK = new Object(); private static final int CURRENT_VERSION_MARKER = 1; - private final MasterCipher masterCipher; private final MasterSecret masterSecret; private PreKeyPair keyPair; @@ -32,7 +30,6 @@ public class PreKeyRecord extends Record { this.id = id; this.masterSecret = masterSecret; - this.masterCipher = new MasterCipher(masterSecret); loadData(); } @@ -44,7 +41,6 @@ public class PreKeyRecord extends Record { this.id = id; this.keyPair = keyPair; this.masterSecret = masterSecret; - this.masterCipher = new MasterCipher(masterSecret); } public long getId() { @@ -95,7 +91,7 @@ public class PreKeyRecord extends Record { return; } - keyPair = readKeyPair(in, masterCipher); + keyPair = readKeyPair(in); in.close(); } catch (FileNotFoundException e) { Log.w("PreKeyRecord", e); @@ -115,7 +111,7 @@ public class PreKeyRecord extends Record { writeBlob(serialized, out); } - private PreKeyPair readKeyPair(FileInputStream in, MasterCipher masterCipher) + private PreKeyPair readKeyPair(FileInputStream in) throws IOException, InvalidKeyException { byte[] keyPairBytes = readBlob(in); diff --git a/src/org/thoughtcrime/securesms/database/keys/Record.java b/library/src/org/whispersystems/textsecure/storage/Record.java similarity index 93% rename from src/org/thoughtcrime/securesms/database/keys/Record.java rename to library/src/org/whispersystems/textsecure/storage/Record.java index fc8ba8d499..95cc66d64f 100644 --- a/src/org/thoughtcrime/securesms/database/keys/Record.java +++ b/library/src/org/whispersystems/textsecure/storage/Record.java @@ -14,13 +14,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; import android.content.Context; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.KeyPair; -import org.thoughtcrime.securesms.crypto.MasterCipher; import org.whispersystems.textsecure.util.Conversions; import java.io.File; diff --git a/src/org/thoughtcrime/securesms/database/keys/RemoteKeyRecord.java b/library/src/org/whispersystems/textsecure/storage/RemoteKeyRecord.java similarity index 80% rename from src/org/thoughtcrime/securesms/database/keys/RemoteKeyRecord.java rename to library/src/org/whispersystems/textsecure/storage/RemoteKeyRecord.java index bf8ede2bf7..3a3a2c89f7 100644 --- a/src/org/thoughtcrime/securesms/database/keys/RemoteKeyRecord.java +++ b/library/src/org/whispersystems/textsecure/storage/RemoteKeyRecord.java @@ -14,18 +14,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.PublicKey; -import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; -import org.thoughtcrime.securesms.database.keys.InvalidKeyIdException; -import org.thoughtcrime.securesms.database.keys.Record; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Hex; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.PublicKey; +import org.whispersystems.textsecure.util.Hex; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -46,22 +42,22 @@ public class RemoteKeyRecord extends Record { private PublicKey remoteKeyCurrent; private PublicKey remoteKeyLast; - public RemoteKeyRecord(Context context, Recipient recipient) { + public RemoteKeyRecord(Context context, CanonicalRecipientAddress recipient) { super(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); loadData(); } - public static void delete(Context context, Recipient recipient) { - Record.delete(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); + public static void delete(Context context, CanonicalRecipientAddress recipient) { + delete(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); } - public static boolean hasRecord(Context context, Recipient recipient) { + public static boolean hasRecord(Context context, CanonicalRecipientAddress recipient) { Log.w("LocalKeyRecord", "Checking: " + getFileNameForRecipient(context, recipient)); - return Record.hasRecord(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); + return hasRecord(context, SESSIONS_DIRECTORY, getFileNameForRecipient(context, recipient)); } - private static String getFileNameForRecipient(Context context, Recipient recipient) { - return CanonicalAddressDatabase.getInstance(context).getCanonicalAddress(recipient.getNumber()) + "-remote"; + private static String getFileNameForRecipient(Context context, CanonicalRecipientAddress recipient) { + return recipient.getCanonicalAddress(context) + "-remote"; } public void updateCurrentRemoteKey(PublicKey remoteKey) { diff --git a/src/org/thoughtcrime/securesms/database/keys/SessionKey.java b/library/src/org/whispersystems/textsecure/storage/SessionKey.java similarity index 91% rename from src/org/thoughtcrime/securesms/database/keys/SessionKey.java rename to library/src/org/whispersystems/textsecure/storage/SessionKey.java index 565718e796..3f0278bd74 100644 --- a/src/org/thoughtcrime/securesms/database/keys/SessionKey.java +++ b/library/src/org/whispersystems/textsecure/storage/SessionKey.java @@ -14,13 +14,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.SessionCipher; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.SessionCipher; import org.whispersystems.textsecure.util.Conversions; -import org.thoughtcrime.securesms.util.Util; +import org.whispersystems.textsecure.util.Util; import javax.crypto.spec.SecretKeySpec; diff --git a/src/org/thoughtcrime/securesms/database/keys/SessionRecord.java b/library/src/org/whispersystems/textsecure/storage/SessionRecord.java similarity index 87% rename from src/org/thoughtcrime/securesms/database/keys/SessionRecord.java rename to library/src/org/whispersystems/textsecure/storage/SessionRecord.java index 49a651fec9..566ea42cc6 100644 --- a/src/org/thoughtcrime/securesms/database/keys/SessionRecord.java +++ b/library/src/org/whispersystems/textsecure/storage/SessionRecord.java @@ -14,16 +14,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.database.keys; +package org.whispersystems.textsecure.storage; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.crypto.IdentityKey; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; -import org.thoughtcrime.securesms.recipients.Recipient; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.MasterSecret; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -53,7 +51,7 @@ public class SessionRecord extends Record { private final MasterSecret masterSecret; - public SessionRecord(Context context, MasterSecret masterSecret, Recipient recipient) { + public SessionRecord(Context context, MasterSecret masterSecret, CanonicalRecipientAddress recipient) { this(context, masterSecret, getRecipientId(context, recipient)); } @@ -64,17 +62,17 @@ public class SessionRecord extends Record { loadData(); } - public static void delete(Context context, Recipient recipient) { - Record.delete(context, SESSIONS_DIRECTORY, getRecipientId(context, recipient)+""); + public static void delete(Context context, CanonicalRecipientAddress recipient) { + delete(context, SESSIONS_DIRECTORY, getRecipientId(context, recipient)+""); } - public static boolean hasSession(Context context, Recipient recipient) { + public static boolean hasSession(Context context, CanonicalRecipientAddress recipient) { Log.w("LocalKeyRecord", "Checking: " + getRecipientId(context, recipient)); - return Record.hasRecord(context, SESSIONS_DIRECTORY, getRecipientId(context, recipient)+""); + return hasRecord(context, SESSIONS_DIRECTORY, getRecipientId(context, recipient)+""); } - private static long getRecipientId(Context context, Recipient recipient) { - return CanonicalAddressDatabase.getInstance(context).getCanonicalAddress(recipient.getNumber()); + private static long getRecipientId(Context context, CanonicalRecipientAddress recipient) { + return recipient.getCanonicalAddress(context); } public void setSessionKey(SessionKey sessionKeyRecord) { diff --git a/src/org/thoughtcrime/securesms/util/Hex.java b/library/src/org/whispersystems/textsecure/util/Hex.java similarity index 98% rename from src/org/thoughtcrime/securesms/util/Hex.java rename to library/src/org/whispersystems/textsecure/util/Hex.java index 0217343809..5db73998e5 100644 --- a/src/org/thoughtcrime/securesms/util/Hex.java +++ b/library/src/org/whispersystems/textsecure/util/Hex.java @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package org.thoughtcrime.securesms.util; +package org.whispersystems.textsecure.util; /** * Utility for generating hex dumps. diff --git a/library/src/org/whispersystems/textsecure/util/Util.java b/library/src/org/whispersystems/textsecure/util/Util.java index 6982a5461b..e7e678c1dc 100644 --- a/library/src/org/whispersystems/textsecure/util/Util.java +++ b/library/src/org/whispersystems/textsecure/util/Util.java @@ -16,6 +16,35 @@ import java.util.Collection; import java.util.List; public class Util { + + public static byte[] combine(byte[] one, byte[] two) { + byte[] combined = new byte[one.length + two.length]; + System.arraycopy(one, 0, combined, 0, one.length); + System.arraycopy(two, 0, combined, one.length, two.length); + + return combined; + } + + public static byte[] combine(byte[] one, byte[] two, byte[] three) { + byte[] combined = new byte[one.length + two.length + three.length]; + System.arraycopy(one, 0, combined, 0, one.length); + System.arraycopy(two, 0, combined, one.length, two.length); + System.arraycopy(three, 0, combined, one.length + two.length, three.length); + + return combined; + } + + public static byte[] combine(byte[] one, byte[] two, byte[] three, byte[] four) { + byte[] combined = new byte[one.length + two.length + three.length + four.length]; + System.arraycopy(one, 0, combined, 0, one.length); + System.arraycopy(two, 0, combined, one.length, two.length); + System.arraycopy(three, 0, combined, one.length + two.length, three.length); + System.arraycopy(four, 0, combined, one.length + two.length + three.length, four.length); + + return combined; + + } + public static boolean isEmpty(String value) { return value == null || value.trim().length() == 0; } diff --git a/src/org/bouncycastle/crypto/AsymmetricCipherKeyPair.java b/src/org/bouncycastle/crypto/AsymmetricCipherKeyPair.java deleted file mode 100644 index 85bec735b7..0000000000 --- a/src/org/bouncycastle/crypto/AsymmetricCipherKeyPair.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bouncycastle.crypto; - -/** - * a holding class for public/private parameter pairs. - */ -public class AsymmetricCipherKeyPair -{ - private CipherParameters publicParam; - private CipherParameters privateParam; - - /** - * basic constructor. - * - * @param publicParam a public key parameters object. - * @param privateParam the corresponding private key parameters. - */ - public AsymmetricCipherKeyPair( - CipherParameters publicParam, - CipherParameters privateParam) - { - this.publicParam = publicParam; - this.privateParam = privateParam; - } - - /** - * return the public key parameters. - * - * @return the public key parameters. - */ - public CipherParameters getPublic() - { - return publicParam; - } - - /** - * return the private key parameters. - * - * @return the private key parameters. - */ - public CipherParameters getPrivate() - { - return privateParam; - } -} diff --git a/src/org/bouncycastle/crypto/AsymmetricCipherKeyPairGenerator.java b/src/org/bouncycastle/crypto/AsymmetricCipherKeyPairGenerator.java deleted file mode 100644 index 919db199db..0000000000 --- a/src/org/bouncycastle/crypto/AsymmetricCipherKeyPairGenerator.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bouncycastle.crypto; - -/** - * interface that a public/private key pair generator should conform to. - */ -public interface AsymmetricCipherKeyPairGenerator -{ - /** - * intialise the key pair generator. - * - * @param param the parameters the key pair is to be initialised with. - */ - public void init(KeyGenerationParameters param); - - /** - * return an AsymmetricCipherKeyPair containing the generated keys. - * - * @return an AsymmetricCipherKeyPair containing the generated keys. - */ - public AsymmetricCipherKeyPair generateKeyPair(); -} - diff --git a/src/org/bouncycastle/crypto/BasicAgreement.java b/src/org/bouncycastle/crypto/BasicAgreement.java deleted file mode 100644 index 49074272c1..0000000000 --- a/src/org/bouncycastle/crypto/BasicAgreement.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bouncycastle.crypto; - -import java.math.BigInteger; - -/** - * The basic interface that basic Diffie-Hellman implementations - * conforms to. - */ -public interface BasicAgreement -{ - /** - * initialise the agreement engine. - */ - public void init(CipherParameters param); - - /** - * given a public key from a given party calculate the next - * message in the agreement sequence. - */ - public BigInteger calculateAgreement(CipherParameters pubKey); -} diff --git a/src/org/bouncycastle/crypto/CipherParameters.java b/src/org/bouncycastle/crypto/CipherParameters.java deleted file mode 100644 index 5be873047d..0000000000 --- a/src/org/bouncycastle/crypto/CipherParameters.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bouncycastle.crypto; - -/** - * all parameter classes implement this. - */ -public interface CipherParameters -{ -} diff --git a/src/org/bouncycastle/crypto/DSA.java b/src/org/bouncycastle/crypto/DSA.java deleted file mode 100644 index 1f5847626a..0000000000 --- a/src/org/bouncycastle/crypto/DSA.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bouncycastle.crypto; - -import java.math.BigInteger; - -/** - * interface for classes implementing algorithms modeled similar to the Digital Signature Alorithm. - */ -public interface DSA -{ - /** - * initialise the signer for signature generation or signature - * verification. - * - * @param forSigning true if we are generating a signature, false - * otherwise. - * @param param key parameters for signature generation. - */ - public void init(boolean forSigning, CipherParameters param); - - /** - * sign the passed in message (usually the output of a hash function). - * - * @param message the message to be signed. - * @return two big integers representing the r and s values respectively. - */ - public BigInteger[] generateSignature(byte[] message); - - /** - * verify the message message against the signature values r and s. - * - * @param message the message that was supposed to have been signed. - * @param r the r signature value. - * @param s the s signature value. - */ - public boolean verifySignature(byte[] message, BigInteger r, BigInteger s); -} diff --git a/src/org/bouncycastle/crypto/KeyGenerationParameters.java b/src/org/bouncycastle/crypto/KeyGenerationParameters.java deleted file mode 100644 index 9a63522fed..0000000000 --- a/src/org/bouncycastle/crypto/KeyGenerationParameters.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bouncycastle.crypto; - -import java.security.SecureRandom; - -/** - * The base class for parameters to key generators. - */ -public class KeyGenerationParameters -{ - private SecureRandom random; - private int strength; - - /** - * initialise the generator with a source of randomness - * and a strength (in bits). - * - * @param random the random byte source. - * @param strength the size, in bits, of the keys we want to produce. - */ - public KeyGenerationParameters( - SecureRandom random, - int strength) - { - this.random = random; - this.strength = strength; - } - - /** - * return the random source associated with this - * generator. - * - * @return the generators random source. - */ - public SecureRandom getRandom() - { - return random; - } - - /** - * return the bit strength for keys produced by this generator, - * - * @return the strength of the keys this generator produces (in bits). - */ - public int getStrength() - { - return strength; - } -} diff --git a/src/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java b/src/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java deleted file mode 100644 index 3ad3e1ca64..0000000000 --- a/src/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bouncycastle.crypto.agreement; - -import java.math.BigInteger; - -import org.bouncycastle.math.ec.ECPoint; - -import org.bouncycastle.crypto.BasicAgreement; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; - -/** - * P1363 7.2.1 ECSVDP-DH - * - * ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive, - * Diffie-Hellman version. It is based on the work of [DH76], [Mil86], - * and [Kob87]. This primitive derives a shared secret value from one - * party's private key and another party's public key, where both have - * the same set of EC domain parameters. If two parties correctly - * execute this primitive, they will produce the same output. This - * primitive can be invoked by a scheme to derive a shared secret key; - * specifically, it may be used with the schemes ECKAS-DH1 and - * DL/ECKAS-DH2. It assumes that the input keys are valid (see also - * Section 7.2.2). - */ -public class ECDHBasicAgreement - implements BasicAgreement -{ - private ECPrivateKeyParameters key; - - public void init( - CipherParameters key) - { - this.key = (ECPrivateKeyParameters)key; - } - - public BigInteger calculateAgreement( - CipherParameters pubKey) - { - ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey; - ECPoint P = pub.getQ().multiply(key.getD()); - - // if (p.isInfinity()) throw new RuntimeException("d*Q == infinity"); - - return P.getX().toBigInteger(); - } -} diff --git a/src/org/bouncycastle/crypto/generators/ECKeyPairGenerator.java b/src/org/bouncycastle/crypto/generators/ECKeyPairGenerator.java deleted file mode 100644 index d77bd747a9..0000000000 --- a/src/org/bouncycastle/crypto/generators/ECKeyPairGenerator.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bouncycastle.crypto.generators; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.KeyGenerationParameters; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyGenerationParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.math.ec.ECConstants; -import org.bouncycastle.math.ec.ECPoint; - -public class ECKeyPairGenerator - implements AsymmetricCipherKeyPairGenerator, ECConstants -{ - ECDomainParameters params; - SecureRandom random; - - public void init( - KeyGenerationParameters param) - { - ECKeyGenerationParameters ecP = (ECKeyGenerationParameters)param; - - this.random = ecP.getRandom(); - this.params = ecP.getDomainParameters(); - } - - /** - * Given the domain parameters this routine generates an EC key - * pair in accordance with X9.62 section 5.2.1 pages 26, 27. - */ - public AsymmetricCipherKeyPair generateKeyPair() - { - BigInteger n = params.getN(); - int nBitLength = n.bitLength(); - BigInteger d; - - do - { - d = new BigInteger(nBitLength, random); - } - while (d.equals(ZERO) || (d.compareTo(n) >= 0)); - - ECPoint Q = params.getG().multiply(d); - - return new AsymmetricCipherKeyPair( - new ECPublicKeyParameters(Q, params), - new ECPrivateKeyParameters(d, params)); - } -} diff --git a/src/org/bouncycastle/crypto/params/AsymmetricKeyParameter.java b/src/org/bouncycastle/crypto/params/AsymmetricKeyParameter.java deleted file mode 100644 index 03ba7253b5..0000000000 --- a/src/org/bouncycastle/crypto/params/AsymmetricKeyParameter.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bouncycastle.crypto.params; - -import org.bouncycastle.crypto.CipherParameters; - -public class AsymmetricKeyParameter - implements CipherParameters -{ - boolean privateKey; - - public AsymmetricKeyParameter( - boolean privateKey) - { - this.privateKey = privateKey; - } - - public boolean isPrivate() - { - return privateKey; - } -} diff --git a/src/org/bouncycastle/crypto/params/ECDomainParameters.java b/src/org/bouncycastle/crypto/params/ECDomainParameters.java deleted file mode 100644 index 95a3ec96c5..0000000000 --- a/src/org/bouncycastle/crypto/params/ECDomainParameters.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bouncycastle.crypto.params; - -import java.math.BigInteger; - -import org.bouncycastle.math.ec.ECConstants; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECPoint; - -public class ECDomainParameters - implements ECConstants -{ - ECCurve curve; - byte[] seed; - ECPoint G; - BigInteger n; - BigInteger h; - - public ECDomainParameters( - ECCurve curve, - ECPoint G, - BigInteger n) - { - this.curve = curve; - this.G = G; - this.n = n; - this.h = ONE; - this.seed = null; - } - - public ECDomainParameters( - ECCurve curve, - ECPoint G, - BigInteger n, - BigInteger h) - { - this.curve = curve; - this.G = G; - this.n = n; - this.h = h; - this.seed = null; - } - - public ECDomainParameters( - ECCurve curve, - ECPoint G, - BigInteger n, - BigInteger h, - byte[] seed) - { - this.curve = curve; - this.G = G; - this.n = n; - this.h = h; - this.seed = seed; - } - - public ECCurve getCurve() - { - return curve; - } - - public ECPoint getG() - { - return G; - } - - public BigInteger getN() - { - return n; - } - - public BigInteger getH() - { - return h; - } - - public byte[] getSeed() - { - return seed; - } -} diff --git a/src/org/bouncycastle/crypto/params/ECKeyGenerationParameters.java b/src/org/bouncycastle/crypto/params/ECKeyGenerationParameters.java deleted file mode 100644 index be3f20f5cd..0000000000 --- a/src/org/bouncycastle/crypto/params/ECKeyGenerationParameters.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bouncycastle.crypto.params; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.KeyGenerationParameters; - -public class ECKeyGenerationParameters - extends KeyGenerationParameters -{ - private ECDomainParameters domainParams; - - public ECKeyGenerationParameters( - ECDomainParameters domainParams, - SecureRandom random) - { - super(random, domainParams.getN().bitLength()); - - this.domainParams = domainParams; - } - - public ECDomainParameters getDomainParameters() - { - return domainParams; - } -} diff --git a/src/org/bouncycastle/crypto/params/ECKeyParameters.java b/src/org/bouncycastle/crypto/params/ECKeyParameters.java deleted file mode 100644 index 19825c5b45..0000000000 --- a/src/org/bouncycastle/crypto/params/ECKeyParameters.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bouncycastle.crypto.params; - -public class ECKeyParameters - extends AsymmetricKeyParameter -{ - ECDomainParameters params; - - protected ECKeyParameters( - boolean isPrivate, - ECDomainParameters params) - { - super(isPrivate); - - this.params = params; - } - - public ECDomainParameters getParameters() - { - return params; - } -} diff --git a/src/org/bouncycastle/crypto/params/ECPrivateKeyParameters.java b/src/org/bouncycastle/crypto/params/ECPrivateKeyParameters.java deleted file mode 100644 index 3e49983e9d..0000000000 --- a/src/org/bouncycastle/crypto/params/ECPrivateKeyParameters.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bouncycastle.crypto.params; - -import java.math.BigInteger; - -public class ECPrivateKeyParameters - extends ECKeyParameters -{ - BigInteger d; - - public ECPrivateKeyParameters( - BigInteger d, - ECDomainParameters params) - { - super(true, params); - this.d = d; - } - - public BigInteger getD() - { - return d; - } -} diff --git a/src/org/bouncycastle/crypto/params/ECPublicKeyParameters.java b/src/org/bouncycastle/crypto/params/ECPublicKeyParameters.java deleted file mode 100644 index 5fbea19ee3..0000000000 --- a/src/org/bouncycastle/crypto/params/ECPublicKeyParameters.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bouncycastle.crypto.params; - -import org.bouncycastle.math.ec.ECPoint; - -public class ECPublicKeyParameters - extends ECKeyParameters -{ - ECPoint Q; - - public ECPublicKeyParameters( - ECPoint Q, - ECDomainParameters params) - { - super(false, params); - this.Q = Q; - } - - public ECPoint getQ() - { - return Q; - } -} diff --git a/src/org/bouncycastle/crypto/params/ParametersWithRandom.java b/src/org/bouncycastle/crypto/params/ParametersWithRandom.java deleted file mode 100644 index a7b18e51f3..0000000000 --- a/src/org/bouncycastle/crypto/params/ParametersWithRandom.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bouncycastle.crypto.params; - -import org.bouncycastle.crypto.CipherParameters; - -import java.security.SecureRandom; - -public class ParametersWithRandom - implements CipherParameters -{ - private SecureRandom random; - private CipherParameters parameters; - - public ParametersWithRandom( - CipherParameters parameters, - SecureRandom random) - { - this.random = random; - this.parameters = parameters; - } - - public ParametersWithRandom( - CipherParameters parameters) - { - this(parameters, new SecureRandom()); - } - - public SecureRandom getRandom() - { - return random; - } - - public CipherParameters getParameters() - { - return parameters; - } -} diff --git a/src/org/bouncycastle/crypto/signers/ECDSASigner.java b/src/org/bouncycastle/crypto/signers/ECDSASigner.java deleted file mode 100644 index 0341227c38..0000000000 --- a/src/org/bouncycastle/crypto/signers/ECDSASigner.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.bouncycastle.crypto.signers; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.DSA; -import org.bouncycastle.crypto.params.ECKeyParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.math.ec.ECAlgorithms; -import org.bouncycastle.math.ec.ECConstants; -import org.bouncycastle.math.ec.ECPoint; - -import java.math.BigInteger; -import java.security.SecureRandom; - -/** - * EC-DSA as described in X9.62 - */ -public class ECDSASigner - implements ECConstants, DSA -{ - ECKeyParameters key; - - SecureRandom random; - - public void init( - boolean forSigning, - CipherParameters param) - { - if (forSigning) - { - if (param instanceof ParametersWithRandom) - { - ParametersWithRandom rParam = (ParametersWithRandom)param; - - this.random = rParam.getRandom(); - this.key = (ECPrivateKeyParameters)rParam.getParameters(); - } - else - { - this.random = new SecureRandom(); - this.key = (ECPrivateKeyParameters)param; - } - } - else - { - this.key = (ECPublicKeyParameters)param; - } - } - - // 5.3 pg 28 - /** - * generate a signature for the given message using the key we were - * initialised with. For conventional DSA the message should be a SHA-1 - * hash of the message of interest. - * - * @param message the message that will be verified later. - */ - public BigInteger[] generateSignature( - byte[] message) - { - BigInteger n = key.getParameters().getN(); - BigInteger e = calculateE(n, message); - BigInteger r = null; - BigInteger s = null; - - // 5.3.2 - do // generate s - { - BigInteger k = null; - int nBitLength = n.bitLength(); - - do // generate r - { - do - { - k = new BigInteger(nBitLength, random); - } - while (k.equals(ZERO)); - - ECPoint p = key.getParameters().getG().multiply(k); - - // 5.3.3 - BigInteger x = p.getX().toBigInteger(); - - r = x.mod(n); - } - while (r.equals(ZERO)); - - BigInteger d = ((ECPrivateKeyParameters)key).getD(); - - s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); - } - while (s.equals(ZERO)); - - BigInteger[] res = new BigInteger[2]; - - res[0] = r; - res[1] = s; - - return res; - } - - // 5.4 pg 29 - /** - * return true if the value r and s represent a DSA signature for - * the passed in message (for standard DSA the message should be - * a SHA-1 hash of the real message to be verified). - */ - public boolean verifySignature( - byte[] message, - BigInteger r, - BigInteger s) - { - BigInteger n = key.getParameters().getN(); - BigInteger e = calculateE(n, message); - - // r in the range [1,n-1] - if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) - { - return false; - } - - // s in the range [1,n-1] - if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) - { - return false; - } - - BigInteger c = s.modInverse(n); - - BigInteger u1 = e.multiply(c).mod(n); - BigInteger u2 = r.multiply(c).mod(n); - - ECPoint G = key.getParameters().getG(); - ECPoint Q = ((ECPublicKeyParameters)key).getQ(); - - ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2); - - BigInteger v = point.getX().toBigInteger().mod(n); - - return v.equals(r); - } - - private BigInteger calculateE(BigInteger n, byte[] message) - { - if (n.bitLength() > message.length * 8) - { - return new BigInteger(1, message); - } - else - { - int messageBitLength = message.length * 8; - BigInteger trunc = new BigInteger(1, message); - - if (messageBitLength - n.bitLength() > 0) - { - trunc = trunc.shiftRight(messageBitLength - n.bitLength()); - } - - return trunc; - } - } -} diff --git a/src/org/bouncycastle/math/ec/ECAlgorithms.java b/src/org/bouncycastle/math/ec/ECAlgorithms.java deleted file mode 100644 index a5b268e0f4..0000000000 --- a/src/org/bouncycastle/math/ec/ECAlgorithms.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -public class ECAlgorithms -{ - public static ECPoint sumOfTwoMultiplies(ECPoint P, BigInteger a, - ECPoint Q, BigInteger b) - { - ECCurve c = P.getCurve(); - if (!c.equals(Q.getCurve())) - { - throw new IllegalArgumentException("P and Q must be on same curve"); - } - - // TODO Add special case back in when WTNAF is enabled -// // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick -// if (c instanceof ECCurve.F2m) -// { -// ECCurve.F2m f2mCurve = (ECCurve.F2m) c; -// if (f2mCurve.isKoblitz()) -// { -// return P.multiply(a).add(Q.multiply(b)); -// } -// } - - return implShamirsTrick(P, a, Q, b); - } - - /* - * "Shamir's Trick", originally due to E. G. Straus - * (Addition chains of vectors. American Mathematical Monthly, - * 71(7):806-808, Aug./Sept. 1964) - *
-     * Input: The points P, Q, scalar k = (km?, ... , k1, k0)
-     * and scalar l = (lm?, ... , l1, l0).
-     * Output: R = k * P + l * Q.
-     * 1: Z <- P + Q
-     * 2: R <- O
-     * 3: for i from m-1 down to 0 do
-     * 4:        R <- R + R        {point doubling}
-     * 5:        if (ki = 1) and (li = 0) then R <- R + P end if
-     * 6:        if (ki = 0) and (li = 1) then R <- R + Q end if
-     * 7:        if (ki = 1) and (li = 1) then R <- R + Z end if
-     * 8: end for
-     * 9: return R
-     * 
- */ - public static ECPoint shamirsTrick(ECPoint P, BigInteger k, - ECPoint Q, BigInteger l) - { - if (!P.getCurve().equals(Q.getCurve())) - { - throw new IllegalArgumentException("P and Q must be on same curve"); - } - - return implShamirsTrick(P, k, Q, l); - } - - private static ECPoint implShamirsTrick(ECPoint P, BigInteger k, - ECPoint Q, BigInteger l) - { - int m = Math.max(k.bitLength(), l.bitLength()); - ECPoint Z = P.add(Q); - ECPoint R = P.getCurve().getInfinity(); - - for (int i = m - 1; i >= 0; --i) - { - R = R.twice(); - - if (k.testBit(i)) - { - if (l.testBit(i)) - { - R = R.add(Z); - } - else - { - R = R.add(P); - } - } - else - { - if (l.testBit(i)) - { - R = R.add(Q); - } - } - } - - return R; - } -} diff --git a/src/org/bouncycastle/math/ec/ECConstants.java b/src/org/bouncycastle/math/ec/ECConstants.java deleted file mode 100644 index 864f746da0..0000000000 --- a/src/org/bouncycastle/math/ec/ECConstants.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -public interface ECConstants -{ - public static final BigInteger ZERO = BigInteger.valueOf(0); - public static final BigInteger ONE = BigInteger.valueOf(1); - public static final BigInteger TWO = BigInteger.valueOf(2); - public static final BigInteger THREE = BigInteger.valueOf(3); - public static final BigInteger FOUR = BigInteger.valueOf(4); -} diff --git a/src/org/bouncycastle/math/ec/ECCurve.java b/src/org/bouncycastle/math/ec/ECCurve.java deleted file mode 100644 index 4db07d5036..0000000000 --- a/src/org/bouncycastle/math/ec/ECCurve.java +++ /dev/null @@ -1,660 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; -import java.util.Random; - -/** - * base class for an elliptic curve - */ -public abstract class ECCurve -{ - ECFieldElement a, b; - - public abstract int getFieldSize(); - - public abstract ECFieldElement fromBigInteger(BigInteger x); - - public abstract ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression); - - public abstract ECPoint decodePoint(byte[] encoded); - - public abstract ECPoint getInfinity(); - - public ECFieldElement getA() - { - return a; - } - - public ECFieldElement getB() - { - return b; - } - - /** - * Elliptic curve over Fp - */ - public static class Fp extends ECCurve - { - BigInteger q; - ECPoint.Fp infinity; - - public Fp(BigInteger q, BigInteger a, BigInteger b) - { - this.q = q; - this.a = fromBigInteger(a); - this.b = fromBigInteger(b); - this.infinity = new ECPoint.Fp(this, null, null); - } - - public BigInteger getQ() - { - return q; - } - - public int getFieldSize() - { - return q.bitLength(); - } - - public ECFieldElement fromBigInteger(BigInteger x) - { - return new ECFieldElement.Fp(this.q, x); - } - - public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression) - { - return new ECPoint.Fp(this, fromBigInteger(x), fromBigInteger(y), withCompression); - } - - /** - * Decode a point on this curve from its ASN.1 encoding. The different - * encodings are taken account of, including point compression for - * Fp (X9.62 s 4.2.1 pg 17). - * @return The decoded point. - */ - public ECPoint decodePoint(byte[] encoded) - { - ECPoint p = null; - - switch (encoded[0]) - { - // infinity - case 0x00: - p = getInfinity(); - break; - // compressed - case 0x02: - case 0x03: - int ytilde = encoded[0] & 1; - byte[] i = new byte[encoded.length - 1]; - - System.arraycopy(encoded, 1, i, 0, i.length); - - ECFieldElement x = new ECFieldElement.Fp(this.q, new BigInteger(1, i)); - ECFieldElement alpha = x.multiply(x.square().add(a)).add(b); - ECFieldElement beta = alpha.sqrt(); - - // - // if we can't find a sqrt we haven't got a point on the - // curve - run! - // - if (beta == null) - { - throw new RuntimeException("Invalid point compression"); - } - - int bit0 = (beta.toBigInteger().testBit(0) ? 1 : 0); - - if (bit0 == ytilde) - { - p = new ECPoint.Fp(this, x, beta, true); - } - else - { - p = new ECPoint.Fp(this, x, - new ECFieldElement.Fp(this.q, q.subtract(beta.toBigInteger())), true); - } - break; - // uncompressed - case 0x04: - // hybrid - case 0x06: - case 0x07: - byte[] xEnc = new byte[(encoded.length - 1) / 2]; - byte[] yEnc = new byte[(encoded.length - 1) / 2]; - - System.arraycopy(encoded, 1, xEnc, 0, xEnc.length); - System.arraycopy(encoded, xEnc.length + 1, yEnc, 0, yEnc.length); - - p = new ECPoint.Fp(this, - new ECFieldElement.Fp(this.q, new BigInteger(1, xEnc)), - new ECFieldElement.Fp(this.q, new BigInteger(1, yEnc))); - break; - default: - throw new RuntimeException("Invalid point encoding 0x" + Integer.toString(encoded[0], 16)); - } - - return p; - } - - public ECPoint getInfinity() - { - return infinity; - } - - public boolean equals( - Object anObject) - { - if (anObject == this) - { - return true; - } - - if (!(anObject instanceof ECCurve.Fp)) - { - return false; - } - - ECCurve.Fp other = (ECCurve.Fp) anObject; - - return this.q.equals(other.q) - && a.equals(other.a) && b.equals(other.b); - } - - public int hashCode() - { - return a.hashCode() ^ b.hashCode() ^ q.hashCode(); - } - } - - /** - * Elliptic curves over F2m. The Weierstrass equation is given by - * y2 + xy = x3 + ax2 + b. - */ - public static class F2m extends ECCurve - { - /** - * The exponent m of F2m. - */ - private int m; // can't be final - JDK 1.1 - - /** - * TPB: The integer k where xm + - * xk + 1 represents the reduction polynomial - * f(z).
- * PPB: The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k1; // can't be final - JDK 1.1 - - /** - * TPB: Always set to 0
- * PPB: The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k2; // can't be final - JDK 1.1 - - /** - * TPB: Always set to 0
- * PPB: The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k3; // can't be final - JDK 1.1 - - /** - * The order of the base point of the curve. - */ - private BigInteger n; // can't be final - JDK 1.1 - - /** - * The cofactor of the curve. - */ - private BigInteger h; // can't be final - JDK 1.1 - - /** - * The point at infinity on this curve. - */ - private ECPoint.F2m infinity; // can't be final - JDK 1.1 - - /** - * The parameter μ of the elliptic curve if this is - * a Koblitz curve. - */ - private byte mu = 0; - - /** - * The auxiliary values s0 and - * s1 used for partial modular reduction for - * Koblitz curves. - */ - private BigInteger[] si = null; - - /** - * Constructor for Trinomial Polynomial Basis (TPB). - * @param m The exponent m of - * F2m. - * @param k The integer k where xm + - * xk + 1 represents the reduction - * polynomial f(z). - * @param a The coefficient a in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param b The coefficient b in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - */ - public F2m( - int m, - int k, - BigInteger a, - BigInteger b) - { - this(m, k, 0, 0, a, b, null, null); - } - - /** - * Constructor for Trinomial Polynomial Basis (TPB). - * @param m The exponent m of - * F2m. - * @param k The integer k where xm + - * xk + 1 represents the reduction - * polynomial f(z). - * @param a The coefficient a in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param b The coefficient b in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param n The order of the main subgroup of the elliptic curve. - * @param h The cofactor of the elliptic curve, i.e. - * #Ea(F2m) = h * n. - */ - public F2m( - int m, - int k, - BigInteger a, - BigInteger b, - BigInteger n, - BigInteger h) - { - this(m, k, 0, 0, a, b, n, h); - } - - /** - * Constructor for Pentanomial Polynomial Basis (PPB). - * @param m The exponent m of - * F2m. - * @param k1 The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k2 The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k3 The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param a The coefficient a in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param b The coefficient b in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - */ - public F2m( - int m, - int k1, - int k2, - int k3, - BigInteger a, - BigInteger b) - { - this(m, k1, k2, k3, a, b, null, null); - } - - /** - * Constructor for Pentanomial Polynomial Basis (PPB). - * @param m The exponent m of - * F2m. - * @param k1 The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k2 The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k3 The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param a The coefficient a in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param b The coefficient b in the Weierstrass equation - * for non-supersingular elliptic curves over - * F2m. - * @param n The order of the main subgroup of the elliptic curve. - * @param h The cofactor of the elliptic curve, i.e. - * #Ea(F2m) = h * n. - */ - public F2m( - int m, - int k1, - int k2, - int k3, - BigInteger a, - BigInteger b, - BigInteger n, - BigInteger h) - { - this.m = m; - this.k1 = k1; - this.k2 = k2; - this.k3 = k3; - this.n = n; - this.h = h; - - if (k1 == 0) - { - throw new IllegalArgumentException("k1 must be > 0"); - } - - if (k2 == 0) - { - if (k3 != 0) - { - throw new IllegalArgumentException("k3 must be 0 if k2 == 0"); - } - } - else - { - if (k2 <= k1) - { - throw new IllegalArgumentException("k2 must be > k1"); - } - - if (k3 <= k2) - { - throw new IllegalArgumentException("k3 must be > k2"); - } - } - - this.a = fromBigInteger(a); - this.b = fromBigInteger(b); - this.infinity = new ECPoint.F2m(this, null, null); - } - - public int getFieldSize() - { - return m; - } - - public ECFieldElement fromBigInteger(BigInteger x) - { - return new ECFieldElement.F2m(this.m, this.k1, this.k2, this.k3, x); - } - - public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression) - { - return new ECPoint.F2m(this, fromBigInteger(x), fromBigInteger(y), withCompression); - } - - /* (non-Javadoc) - * @see org.bouncycastle.math.ec.ECCurve#decodePoint(byte[]) - */ - public ECPoint decodePoint(byte[] encoded) - { - ECPoint p = null; - - switch (encoded[0]) - { - // infinity - case 0x00: - p = getInfinity(); - break; - // compressed - case 0x02: - case 0x03: - byte[] enc = new byte[encoded.length - 1]; - System.arraycopy(encoded, 1, enc, 0, enc.length); - if (encoded[0] == 0x02) - { - p = decompressPoint(enc, 0); - } - else - { - p = decompressPoint(enc, 1); - } - break; - // uncompressed - case 0x04: - // hybrid - case 0x06: - case 0x07: - byte[] xEnc = new byte[(encoded.length - 1) / 2]; - byte[] yEnc = new byte[(encoded.length - 1) / 2]; - - System.arraycopy(encoded, 1, xEnc, 0, xEnc.length); - System.arraycopy(encoded, xEnc.length + 1, yEnc, 0, yEnc.length); - - p = new ECPoint.F2m(this, - new ECFieldElement.F2m(this.m, this.k1, this.k2, this.k3, - new BigInteger(1, xEnc)), - new ECFieldElement.F2m(this.m, this.k1, this.k2, this.k3, - new BigInteger(1, yEnc)), false); - break; - - default: - throw new RuntimeException("Invalid point encoding 0x" + Integer.toString(encoded[0], 16)); - } - - return p; - } - - public ECPoint getInfinity() - { - return infinity; - } - - /** - * Returns true if this is a Koblitz curve (ABC curve). - * @return true if this is a Koblitz curve (ABC curve), false otherwise - */ - public boolean isKoblitz() - { - return ((n != null) && (h != null) && - ((a.toBigInteger().equals(ECConstants.ZERO)) || - (a.toBigInteger().equals(ECConstants.ONE))) && - (b.toBigInteger().equals(ECConstants.ONE))); - } - - /** - * Returns the parameter μ of the elliptic curve. - * @return μ of the elliptic curve. - * @throws IllegalArgumentException if the given ECCurve is not a - * Koblitz curve. - */ - synchronized byte getMu() - { - if (mu == 0) - { - mu = Tnaf.getMu(this); - } - return mu; - } - - /** - * @return the auxiliary values s0 and - * s1 used for partial modular reduction for - * Koblitz curves. - */ - synchronized BigInteger[] getSi() - { - if (si == null) - { - si = Tnaf.getSi(this); - } - return si; - } - - /** - * Decompresses a compressed point P = (xp, yp) (X9.62 s 4.2.2). - * - * @param xEnc - * The encoding of field element xp. - * @param ypBit - * ~yp, an indication bit for the decompression of yp. - * @return the decompressed point. - */ - private ECPoint decompressPoint( - byte[] xEnc, - int ypBit) - { - ECFieldElement xp = new ECFieldElement.F2m( - this.m, this.k1, this.k2, this.k3, new BigInteger(1, xEnc)); - ECFieldElement yp = null; - if (xp.toBigInteger().equals(ECConstants.ZERO)) - { - yp = (ECFieldElement.F2m)b; - for (int i = 0; i < m - 1; i++) - { - yp = yp.square(); - } - } - else - { - ECFieldElement beta = xp.add(a).add( - b.multiply(xp.square().invert())); - ECFieldElement z = solveQuadradicEquation(beta); - if (z == null) - { - throw new RuntimeException("Invalid point compression"); - } - int zBit = 0; - if (z.toBigInteger().testBit(0)) - { - zBit = 1; - } - if (zBit != ypBit) - { - z = z.add(new ECFieldElement.F2m(this.m, this.k1, this.k2, - this.k3, ECConstants.ONE)); - } - yp = xp.multiply(z); - } - - return new ECPoint.F2m(this, xp, yp); - } - - /** - * Solves a quadratic equation z2 + z = beta(X9.62 - * D.1.6) The other solution is z + 1. - * - * @param beta - * The value to solve the qradratic equation for. - * @return the solution for z2 + z = beta or - * null if no solution exists. - */ - private ECFieldElement solveQuadradicEquation(ECFieldElement beta) - { - ECFieldElement zeroElement = new ECFieldElement.F2m( - this.m, this.k1, this.k2, this.k3, ECConstants.ZERO); - - if (beta.toBigInteger().equals(ECConstants.ZERO)) - { - return zeroElement; - } - - ECFieldElement z = null; - ECFieldElement gamma = zeroElement; - - Random rand = new Random(); - do - { - ECFieldElement t = new ECFieldElement.F2m(this.m, this.k1, - this.k2, this.k3, new BigInteger(m, rand)); - z = zeroElement; - ECFieldElement w = beta; - for (int i = 1; i <= m - 1; i++) - { - ECFieldElement w2 = w.square(); - z = z.square().add(w2.multiply(t)); - w = w2.add(beta); - } - if (!w.toBigInteger().equals(ECConstants.ZERO)) - { - return null; - } - gamma = z.square().add(z); - } - while (gamma.toBigInteger().equals(ECConstants.ZERO)); - - return z; - } - - public boolean equals( - Object anObject) - { - if (anObject == this) - { - return true; - } - - if (!(anObject instanceof ECCurve.F2m)) - { - return false; - } - - ECCurve.F2m other = (ECCurve.F2m)anObject; - - return (this.m == other.m) && (this.k1 == other.k1) - && (this.k2 == other.k2) && (this.k3 == other.k3) - && a.equals(other.a) && b.equals(other.b); - } - - public int hashCode() - { - return this.a.hashCode() ^ this.b.hashCode() ^ m ^ k1 ^ k2 ^ k3; - } - - public int getM() - { - return m; - } - - /** - * Return true if curve uses a Trinomial basis. - * - * @return true if curve Trinomial, false otherwise. - */ - public boolean isTrinomial() - { - return k2 == 0 && k3 == 0; - } - - public int getK1() - { - return k1; - } - - public int getK2() - { - return k2; - } - - public int getK3() - { - return k3; - } - - public BigInteger getN() - { - return n; - } - - public BigInteger getH() - { - return h; - } - } -} diff --git a/src/org/bouncycastle/math/ec/ECFieldElement.java b/src/org/bouncycastle/math/ec/ECFieldElement.java deleted file mode 100644 index b4b9b0af4e..0000000000 --- a/src/org/bouncycastle/math/ec/ECFieldElement.java +++ /dev/null @@ -1,1194 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; -import java.util.Random; - -public abstract class ECFieldElement - implements ECConstants -{ - - public abstract BigInteger toBigInteger(); - public abstract String getFieldName(); - public abstract int getFieldSize(); - public abstract ECFieldElement add(ECFieldElement b); - public abstract ECFieldElement subtract(ECFieldElement b); - public abstract ECFieldElement multiply(ECFieldElement b); - public abstract ECFieldElement divide(ECFieldElement b); - public abstract ECFieldElement negate(); - public abstract ECFieldElement square(); - public abstract ECFieldElement invert(); - public abstract ECFieldElement sqrt(); - - public String toString() - { - return this.toBigInteger().toString(2); - } - - public static class Fp extends ECFieldElement - { - BigInteger x; - - BigInteger q; - - public Fp(BigInteger q, BigInteger x) - { - this.x = x; - - if (x.compareTo(q) >= 0) - { - throw new IllegalArgumentException("x value too large in field element"); - } - - this.q = q; - } - - public BigInteger toBigInteger() - { - return x; - } - - /** - * return the field name for this field. - * - * @return the string "Fp". - */ - public String getFieldName() - { - return "Fp"; - } - - public int getFieldSize() - { - return q.bitLength(); - } - - public BigInteger getQ() - { - return q; - } - - public ECFieldElement add(ECFieldElement b) - { - return new Fp(q, x.add(b.toBigInteger()).mod(q)); - } - - public ECFieldElement subtract(ECFieldElement b) - { - return new Fp(q, x.subtract(b.toBigInteger()).mod(q)); - } - - public ECFieldElement multiply(ECFieldElement b) - { - return new Fp(q, x.multiply(b.toBigInteger()).mod(q)); - } - - public ECFieldElement divide(ECFieldElement b) - { - return new Fp(q, x.multiply(b.toBigInteger().modInverse(q)).mod(q)); - } - - public ECFieldElement negate() - { - return new Fp(q, x.negate().mod(q)); - } - - public ECFieldElement square() - { - return new Fp(q, x.multiply(x).mod(q)); - } - - public ECFieldElement invert() - { - return new Fp(q, x.modInverse(q)); - } - - // D.1.4 91 - /** - * return a sqrt root - the routine verifies that the calculation - * returns the right value - if none exists it returns null. - */ - public ECFieldElement sqrt() - { - if (!q.testBit(0)) - { - throw new RuntimeException("not done yet"); - } - - // p mod 4 == 3 - if (q.testBit(1)) - { - // z = g^(u+1) + p, p = 4u + 3 - ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q)); - - return z.square().equals(this) ? z : null; - } - - // p mod 4 == 1 - BigInteger qMinusOne = q.subtract(ECConstants.ONE); - - BigInteger legendreExponent = qMinusOne.shiftRight(1); - if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) - { - return null; - } - - BigInteger u = qMinusOne.shiftRight(2); - BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); - - BigInteger Q = this.x; - BigInteger fourQ = Q.shiftLeft(2).mod(q); - - BigInteger U, V; - Random rand = new Random(); - do - { - BigInteger P; - do - { - P = new BigInteger(q.bitLength(), rand); - } - while (P.compareTo(q) >= 0 - || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); - - BigInteger[] result = lucasSequence(q, P, Q, k); - U = result[0]; - V = result[1]; - - if (V.multiply(V).mod(q).equals(fourQ)) - { - // Integer division by 2, mod q - if (V.testBit(0)) - { - V = V.add(q); - } - - V = V.shiftRight(1); - - //assert V.multiply(V).mod(q).equals(x); - - return new ECFieldElement.Fp(q, V); - } - } - while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); - - return null; - -// BigInteger qMinusOne = q.subtract(ECConstants.ONE); -// BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); -// if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) -// { -// return null; -// } -// -// Random rand = new Random(); -// BigInteger fourX = x.shiftLeft(2); -// -// BigInteger r; -// do -// { -// r = new BigInteger(q.bitLength(), rand); -// } -// while (r.compareTo(q) >= 0 -// || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); -// -// BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); -// BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); -// -// BigInteger wOne = WOne(r, x, q); -// BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); -// BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); -// -// BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) -// .multiply(x).mod(q) -// .multiply(wSum).mod(q); -// -// return new Fp(q, root); - } - -// private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) -// { -// if (n.equals(ECConstants.ONE)) -// { -// return wOne; -// } -// boolean isEven = !n.testBit(0); -// n = n.shiftRight(1);//divide(ECConstants.TWO); -// if (isEven) -// { -// BigInteger w = W(n, wOne, p); -// return w.multiply(w).subtract(ECConstants.TWO).mod(p); -// } -// BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); -// BigInteger w2 = W(n, wOne, p); -// return w1.multiply(w2).subtract(wOne).mod(p); -// } -// -// private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) -// { -// return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); -// } - - private static BigInteger[] lucasSequence( - BigInteger p, - BigInteger P, - BigInteger Q, - BigInteger k) - { - int n = k.bitLength(); - int s = k.getLowestSetBit(); - - BigInteger Uh = ECConstants.ONE; - BigInteger Vl = ECConstants.TWO; - BigInteger Vh = P; - BigInteger Ql = ECConstants.ONE; - BigInteger Qh = ECConstants.ONE; - - for (int j = n - 1; j >= s + 1; --j) - { - Ql = Ql.multiply(Qh).mod(p); - - if (k.testBit(j)) - { - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vh).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); - } - else - { - Qh = Ql; - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - } - } - - Ql = Ql.multiply(Qh).mod(p); - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Ql = Ql.multiply(Qh).mod(p); - - for (int j = 1; j <= s; ++j) - { - Uh = Uh.multiply(Vl).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - Ql = Ql.multiply(Ql).mod(p); - } - - return new BigInteger[]{ Uh, Vl }; - } - - public boolean equals(Object other) - { - if (other == this) - { - return true; - } - - if (!(other instanceof ECFieldElement.Fp)) - { - return false; - } - - ECFieldElement.Fp o = (ECFieldElement.Fp)other; - return q.equals(o.q) && x.equals(o.x); - } - - public int hashCode() - { - return q.hashCode() ^ x.hashCode(); - } - } - -// /** -// * Class representing the Elements of the finite field -// * F2m in polynomial basis (PB) -// * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial -// * basis representations are supported. Gaussian normal basis (GNB) -// * representation is not supported. -// */ -// public static class F2m extends ECFieldElement -// { -// BigInteger x; -// -// /** -// * Indicates gaussian normal basis representation (GNB). Number chosen -// * according to X9.62. GNB is not implemented at present. -// */ -// public static final int GNB = 1; -// -// /** -// * Indicates trinomial basis representation (TPB). Number chosen -// * according to X9.62. -// */ -// public static final int TPB = 2; -// -// /** -// * Indicates pentanomial basis representation (PPB). Number chosen -// * according to X9.62. -// */ -// public static final int PPB = 3; -// -// /** -// * TPB or PPB. -// */ -// private int representation; -// -// /** -// * The exponent m of F2m. -// */ -// private int m; -// -// /** -// * TPB: The integer k where xm + -// * xk + 1 represents the reduction polynomial -// * f(z).
-// * PPB: The integer k1 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// private int k1; -// -// /** -// * TPB: Always set to 0
-// * PPB: The integer k2 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// private int k2; -// -// /** -// * TPB: Always set to 0
-// * PPB: The integer k3 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// private int k3; -// -// /** -// * Constructor for PPB. -// * @param m The exponent m of -// * F2m. -// * @param k1 The integer k1 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z). -// * @param k2 The integer k2 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z). -// * @param k3 The integer k3 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z). -// * @param x The BigInteger representing the value of the field element. -// */ -// public F2m( -// int m, -// int k1, -// int k2, -// int k3, -// BigInteger x) -// { -//// super(x); -// this.x = x; -// -// if ((k2 == 0) && (k3 == 0)) -// { -// this.representation = TPB; -// } -// else -// { -// if (k2 >= k3) -// { -// throw new IllegalArgumentException( -// "k2 must be smaller than k3"); -// } -// if (k2 <= 0) -// { -// throw new IllegalArgumentException( -// "k2 must be larger than 0"); -// } -// this.representation = PPB; -// } -// -// if (x.signum() < 0) -// { -// throw new IllegalArgumentException("x value cannot be negative"); -// } -// -// this.m = m; -// this.k1 = k1; -// this.k2 = k2; -// this.k3 = k3; -// } -// -// /** -// * Constructor for TPB. -// * @param m The exponent m of -// * F2m. -// * @param k The integer k where xm + -// * xk + 1 represents the reduction -// * polynomial f(z). -// * @param x The BigInteger representing the value of the field element. -// */ -// public F2m(int m, int k, BigInteger x) -// { -// // Set k1 to k, and set k2 and k3 to 0 -// this(m, k, 0, 0, x); -// } -// -// public BigInteger toBigInteger() -// { -// return x; -// } -// -// public String getFieldName() -// { -// return "F2m"; -// } -// -// public int getFieldSize() -// { -// return m; -// } -// -// /** -// * Checks, if the ECFieldElements a and b -// * are elements of the same field F2m -// * (having the same representation). -// * @param a field element. -// * @param b field element to be compared. -// * @throws IllegalArgumentException if a and b -// * are not elements of the same field -// * F2m (having the same -// * representation). -// */ -// public static void checkFieldElements( -// ECFieldElement a, -// ECFieldElement b) -// { -// if ((!(a instanceof F2m)) || (!(b instanceof F2m))) -// { -// throw new IllegalArgumentException("Field elements are not " -// + "both instances of ECFieldElement.F2m"); -// } -// -// if ((a.toBigInteger().signum() < 0) || (b.toBigInteger().signum() < 0)) -// { -// throw new IllegalArgumentException( -// "x value may not be negative"); -// } -// -// ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; -// ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; -// -// if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) -// || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) -// { -// throw new IllegalArgumentException("Field elements are not " -// + "elements of the same field F2m"); -// } -// -// if (aF2m.representation != bF2m.representation) -// { -// // Should never occur -// throw new IllegalArgumentException( -// "One of the field " -// + "elements are not elements has incorrect representation"); -// } -// } -// -// /** -// * Computes z * a(z) mod f(z), where f(z) is -// * the reduction polynomial of this. -// * @param a The polynomial a(z) to be multiplied by -// * z mod f(z). -// * @return z * a(z) mod f(z) -// */ -// private BigInteger multZModF(final BigInteger a) -// { -// // Left-shift of a(z) -// BigInteger az = a.shiftLeft(1); -// if (az.testBit(this.m)) -// { -// // If the coefficient of z^m in a(z) equals 1, reduction -// // modulo f(z) is performed: Add f(z) to to a(z): -// // Step 1: Unset mth coeffient of a(z) -// az = az.clearBit(this.m); -// -// // Step 2: Add r(z) to a(z), where r(z) is defined as -// // f(z) = z^m + r(z), and k1, k2, k3 are the positions of -// // the non-zero coefficients in r(z) -// az = az.flipBit(0); -// az = az.flipBit(this.k1); -// if (this.representation == PPB) -// { -// az = az.flipBit(this.k2); -// az = az.flipBit(this.k3); -// } -// } -// return az; -// } -// -// public ECFieldElement add(final ECFieldElement b) -// { -// // No check performed here for performance reasons. Instead the -// // elements involved are checked in ECPoint.F2m -// // checkFieldElements(this, b); -// if (b.toBigInteger().signum() == 0) -// { -// return this; -// } -// -// return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.toBigInteger())); -// } -// -// public ECFieldElement subtract(final ECFieldElement b) -// { -// // Addition and subtraction are the same in F2m -// return add(b); -// } -// -// -// public ECFieldElement multiply(final ECFieldElement b) -// { -// // Left-to-right shift-and-add field multiplication in F2m -// // Input: Binary polynomials a(z) and b(z) of degree at most m-1 -// // Output: c(z) = a(z) * b(z) mod f(z) -// -// // No check performed here for performance reasons. Instead the -// // elements involved are checked in ECPoint.F2m -// // checkFieldElements(this, b); -// final BigInteger az = this.x; -// BigInteger bz = b.toBigInteger(); -// BigInteger cz; -// -// // Compute c(z) = a(z) * b(z) mod f(z) -// if (az.testBit(0)) -// { -// cz = bz; -// } -// else -// { -// cz = ECConstants.ZERO; -// } -// -// for (int i = 1; i < this.m; i++) -// { -// // b(z) := z * b(z) mod f(z) -// bz = multZModF(bz); -// -// if (az.testBit(i)) -// { -// // If the coefficient of x^i in a(z) equals 1, b(z) is added -// // to c(z) -// cz = cz.xor(bz); -// } -// } -// return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); -// } -// -// -// public ECFieldElement divide(final ECFieldElement b) -// { -// // There may be more efficient implementations -// ECFieldElement bInv = b.invert(); -// return multiply(bInv); -// } -// -// public ECFieldElement negate() -// { -// // -x == x holds for all x in F2m -// return this; -// } -// -// public ECFieldElement square() -// { -// // Naive implementation, can probably be speeded up using modular -// // reduction -// return multiply(this); -// } -// -// public ECFieldElement invert() -// { -// // Inversion in F2m using the extended Euclidean algorithm -// // Input: A nonzero polynomial a(z) of degree at most m-1 -// // Output: a(z)^(-1) mod f(z) -// -// // u(z) := a(z) -// BigInteger uz = this.x; -// if (uz.signum() <= 0) -// { -// throw new ArithmeticException("x is zero or negative, " + -// "inversion is impossible"); -// } -// -// // v(z) := f(z) -// BigInteger vz = ECConstants.ZERO.setBit(m); -// vz = vz.setBit(0); -// vz = vz.setBit(this.k1); -// if (this.representation == PPB) -// { -// vz = vz.setBit(this.k2); -// vz = vz.setBit(this.k3); -// } -// -// // g1(z) := 1, g2(z) := 0 -// BigInteger g1z = ECConstants.ONE; -// BigInteger g2z = ECConstants.ZERO; -// -// // while u != 1 -// while (!(uz.equals(ECConstants.ZERO))) -// { -// // j := deg(u(z)) - deg(v(z)) -// int j = uz.bitLength() - vz.bitLength(); -// -// // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j -// if (j < 0) -// { -// final BigInteger uzCopy = uz; -// uz = vz; -// vz = uzCopy; -// -// final BigInteger g1zCopy = g1z; -// g1z = g2z; -// g2z = g1zCopy; -// -// j = -j; -// } -// -// // u(z) := u(z) + z^j * v(z) -// // Note, that no reduction modulo f(z) is required, because -// // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) -// // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) -// // = deg(u(z)) -// uz = uz.xor(vz.shiftLeft(j)); -// -// // g1(z) := g1(z) + z^j * g2(z) -// g1z = g1z.xor(g2z.shiftLeft(j)); -//// if (g1z.bitLength() > this.m) { -//// throw new ArithmeticException( -//// "deg(g1z) >= m, g1z = " + g1z.toString(2)); -//// } -// } -// return new ECFieldElement.F2m( -// this.m, this.k1, this.k2, this.k3, g2z); -// } -// -// public ECFieldElement sqrt() -// { -// throw new RuntimeException("Not implemented"); -// } -// -// /** -// * @return the representation of the field -// * F2m, either of -// * TPB (trinomial -// * basis representation) or -// * PPB (pentanomial -// * basis representation). -// */ -// public int getRepresentation() -// { -// return this.representation; -// } -// -// /** -// * @return the degree m of the reduction polynomial -// * f(z). -// */ -// public int getM() -// { -// return this.m; -// } -// -// /** -// * @return TPB: The integer k where xm + -// * xk + 1 represents the reduction polynomial -// * f(z).
-// * PPB: The integer k1 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// public int getK1() -// { -// return this.k1; -// } -// -// /** -// * @return TPB: Always returns 0
-// * PPB: The integer k2 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// public int getK2() -// { -// return this.k2; -// } -// -// /** -// * @return TPB: Always set to 0
-// * PPB: The integer k3 where xm + -// * xk3 + xk2 + xk1 + 1 -// * represents the reduction polynomial f(z).
-// */ -// public int getK3() -// { -// return this.k3; -// } -// -// public boolean equals(Object anObject) -// { -// if (anObject == this) -// { -// return true; -// } -// -// if (!(anObject instanceof ECFieldElement.F2m)) -// { -// return false; -// } -// -// ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; -// -// return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) -// && (this.k3 == b.k3) -// && (this.representation == b.representation) -// && (this.x.equals(b.x))); -// } -// -// public int hashCode() -// { -// return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; -// } -// } - - /** - * Class representing the Elements of the finite field - * F2m in polynomial basis (PB) - * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial - * basis representations are supported. Gaussian normal basis (GNB) - * representation is not supported. - */ - public static class F2m extends ECFieldElement - { - /** - * Indicates gaussian normal basis representation (GNB). Number chosen - * according to X9.62. GNB is not implemented at present. - */ - public static final int GNB = 1; - - /** - * Indicates trinomial basis representation (TPB). Number chosen - * according to X9.62. - */ - public static final int TPB = 2; - - /** - * Indicates pentanomial basis representation (PPB). Number chosen - * according to X9.62. - */ - public static final int PPB = 3; - - /** - * TPB or PPB. - */ - private int representation; - - /** - * The exponent m of F2m. - */ - private int m; - - /** - * TPB: The integer k where xm + - * xk + 1 represents the reduction polynomial - * f(z).
- * PPB: The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k1; - - /** - * TPB: Always set to 0
- * PPB: The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k2; - - /** - * TPB: Always set to 0
- * PPB: The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - private int k3; - - /** - * The IntArray holding the bits. - */ - private IntArray x; - - /** - * The number of ints required to hold m bits. - */ - private int t; - - /** - * Constructor for PPB. - * @param m The exponent m of - * F2m. - * @param k1 The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k2 The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param k3 The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z). - * @param x The BigInteger representing the value of the field element. - */ - public F2m( - int m, - int k1, - int k2, - int k3, - BigInteger x) - { - // t = m / 32 rounded up to the next integer - t = (m + 31) >> 5; - this.x = new IntArray(x, t); - - if ((k2 == 0) && (k3 == 0)) - { - this.representation = TPB; - } - else - { - if (k2 >= k3) - { - throw new IllegalArgumentException( - "k2 must be smaller than k3"); - } - if (k2 <= 0) - { - throw new IllegalArgumentException( - "k2 must be larger than 0"); - } - this.representation = PPB; - } - - if (x.signum() < 0) - { - throw new IllegalArgumentException("x value cannot be negative"); - } - - this.m = m; - this.k1 = k1; - this.k2 = k2; - this.k3 = k3; - } - - /** - * Constructor for TPB. - * @param m The exponent m of - * F2m. - * @param k The integer k where xm + - * xk + 1 represents the reduction - * polynomial f(z). - * @param x The BigInteger representing the value of the field element. - */ - public F2m(int m, int k, BigInteger x) - { - // Set k1 to k, and set k2 and k3 to 0 - this(m, k, 0, 0, x); - } - - private F2m(int m, int k1, int k2, int k3, IntArray x) - { - t = (m + 31) >> 5; - this.x = x; - this.m = m; - this.k1 = k1; - this.k2 = k2; - this.k3 = k3; - - if ((k2 == 0) && (k3 == 0)) - { - this.representation = TPB; - } - else - { - this.representation = PPB; - } - - } - - public BigInteger toBigInteger() - { - return x.toBigInteger(); - } - - public String getFieldName() - { - return "F2m"; - } - - public int getFieldSize() - { - return m; - } - - /** - * Checks, if the ECFieldElements a and b - * are elements of the same field F2m - * (having the same representation). - * @param a field element. - * @param b field element to be compared. - * @throws IllegalArgumentException if a and b - * are not elements of the same field - * F2m (having the same - * representation). - */ - public static void checkFieldElements( - ECFieldElement a, - ECFieldElement b) - { - if ((!(a instanceof F2m)) || (!(b instanceof F2m))) - { - throw new IllegalArgumentException("Field elements are not " - + "both instances of ECFieldElement.F2m"); - } - - ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; - ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; - - if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) - || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) - { - throw new IllegalArgumentException("Field elements are not " - + "elements of the same field F2m"); - } - - if (aF2m.representation != bF2m.representation) - { - // Should never occur - throw new IllegalArgumentException( - "One of the field " - + "elements are not elements has incorrect representation"); - } - } - - public ECFieldElement add(final ECFieldElement b) - { - // No check performed here for performance reasons. Instead the - // elements involved are checked in ECPoint.F2m - // checkFieldElements(this, b); - IntArray iarrClone = (IntArray)this.x.clone(); - F2m bF2m = (F2m)b; - iarrClone.addShifted(bF2m.x, 0); - return new F2m(m, k1, k2, k3, iarrClone); - } - - public ECFieldElement subtract(final ECFieldElement b) - { - // Addition and subtraction are the same in F2m - return add(b); - } - - public ECFieldElement multiply(final ECFieldElement b) - { - // Right-to-left comb multiplication in the IntArray - // Input: Binary polynomials a(z) and b(z) of degree at most m-1 - // Output: c(z) = a(z) * b(z) mod f(z) - - // No check performed here for performance reasons. Instead the - // elements involved are checked in ECPoint.F2m - // checkFieldElements(this, b); - F2m bF2m = (F2m)b; - IntArray mult = x.multiply(bF2m.x, m); - mult.reduce(m, new int[]{k1, k2, k3}); - return new F2m(m, k1, k2, k3, mult); - } - - public ECFieldElement divide(final ECFieldElement b) - { - // There may be more efficient implementations - ECFieldElement bInv = b.invert(); - return multiply(bInv); - } - - public ECFieldElement negate() - { - // -x == x holds for all x in F2m - return this; - } - - public ECFieldElement square() - { - IntArray squared = x.square(m); - squared.reduce(m, new int[]{k1, k2, k3}); - return new F2m(m, k1, k2, k3, squared); - } - - - public ECFieldElement invert() - { - // Inversion in F2m using the extended Euclidean algorithm - // Input: A nonzero polynomial a(z) of degree at most m-1 - // Output: a(z)^(-1) mod f(z) - - // u(z) := a(z) - IntArray uz = (IntArray)this.x.clone(); - - // v(z) := f(z) - IntArray vz = new IntArray(t); - vz.setBit(m); - vz.setBit(0); - vz.setBit(this.k1); - if (this.representation == PPB) - { - vz.setBit(this.k2); - vz.setBit(this.k3); - } - - // g1(z) := 1, g2(z) := 0 - IntArray g1z = new IntArray(t); - g1z.setBit(0); - IntArray g2z = new IntArray(t); - - // while u != 0 - while (!uz.isZero()) -// while (uz.getUsedLength() > 0) -// while (uz.bitLength() > 1) - { - // j := deg(u(z)) - deg(v(z)) - int j = uz.bitLength() - vz.bitLength(); - - // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j - if (j < 0) - { - final IntArray uzCopy = uz; - uz = vz; - vz = uzCopy; - - final IntArray g1zCopy = g1z; - g1z = g2z; - g2z = g1zCopy; - - j = -j; - } - - // u(z) := u(z) + z^j * v(z) - // Note, that no reduction modulo f(z) is required, because - // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) - // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) - // = deg(u(z)) - // uz = uz.xor(vz.shiftLeft(j)); - // jInt = n / 32 - int jInt = j >> 5; - // jInt = n % 32 - int jBit = j & 0x1F; - IntArray vzShift = vz.shiftLeft(jBit); - uz.addShifted(vzShift, jInt); - - // g1(z) := g1(z) + z^j * g2(z) -// g1z = g1z.xor(g2z.shiftLeft(j)); - IntArray g2zShift = g2z.shiftLeft(jBit); - g1z.addShifted(g2zShift, jInt); - - } - return new ECFieldElement.F2m( - this.m, this.k1, this.k2, this.k3, g2z); - } - - public ECFieldElement sqrt() - { - throw new RuntimeException("Not implemented"); - } - - /** - * @return the representation of the field - * F2m, either of - * TPB (trinomial - * basis representation) or - * PPB (pentanomial - * basis representation). - */ - public int getRepresentation() - { - return this.representation; - } - - /** - * @return the degree m of the reduction polynomial - * f(z). - */ - public int getM() - { - return this.m; - } - - /** - * @return TPB: The integer k where xm + - * xk + 1 represents the reduction polynomial - * f(z).
- * PPB: The integer k1 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - public int getK1() - { - return this.k1; - } - - /** - * @return TPB: Always returns 0
- * PPB: The integer k2 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - public int getK2() - { - return this.k2; - } - - /** - * @return TPB: Always set to 0
- * PPB: The integer k3 where xm + - * xk3 + xk2 + xk1 + 1 - * represents the reduction polynomial f(z).
- */ - public int getK3() - { - return this.k3; - } - - public boolean equals(Object anObject) - { - if (anObject == this) - { - return true; - } - - if (!(anObject instanceof ECFieldElement.F2m)) - { - return false; - } - - ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; - - return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) - && (this.k3 == b.k3) - && (this.representation == b.representation) - && (this.x.equals(b.x))); - } - - public int hashCode() - { - return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; - } - } -} diff --git a/src/org/bouncycastle/math/ec/ECMultiplier.java b/src/org/bouncycastle/math/ec/ECMultiplier.java deleted file mode 100644 index 4d72e33cf0..0000000000 --- a/src/org/bouncycastle/math/ec/ECMultiplier.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Interface for classes encapsulating a point multiplication algorithm - * for ECPoints. - */ -interface ECMultiplier -{ - /** - * Multiplies the ECPoint p by k, i.e. - * p is added k times to itself. - * @param p The ECPoint to be multiplied. - * @param k The factor by which p i multiplied. - * @return p multiplied by k. - */ - ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo); -} diff --git a/src/org/bouncycastle/math/ec/ECPoint.java b/src/org/bouncycastle/math/ec/ECPoint.java deleted file mode 100644 index 3cb27fa540..0000000000 --- a/src/org/bouncycastle/math/ec/ECPoint.java +++ /dev/null @@ -1,594 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -import org.thoughtcrime.bouncycastle.asn1.x9.X9IntegerConverter; - -/** - * base class for points on elliptic curves. - */ -public abstract class ECPoint -{ - ECCurve curve; - ECFieldElement x; - ECFieldElement y; - - protected boolean withCompression; - - protected ECMultiplier multiplier = null; - - protected PreCompInfo preCompInfo = null; - - private static X9IntegerConverter converter = new X9IntegerConverter(); - - protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) - { - this.curve = curve; - this.x = x; - this.y = y; - } - - public ECCurve getCurve() - { - return curve; - } - - public ECFieldElement getX() - { - return x; - } - - public ECFieldElement getY() - { - return y; - } - - public boolean isInfinity() - { - return x == null && y == null; - } - - public boolean isCompressed() - { - return withCompression; - } - - public boolean equals( - Object other) - { - if (other == this) - { - return true; - } - - if (!(other instanceof ECPoint)) - { - return false; - } - - ECPoint o = (ECPoint)other; - - if (this.isInfinity()) - { - return o.isInfinity(); - } - - return x.equals(o.x) && y.equals(o.y); - } - - public int hashCode() - { - if (this.isInfinity()) - { - return 0; - } - - return x.hashCode() ^ y.hashCode(); - } - -// /** -// * Mainly for testing. Explicitly set the ECMultiplier. -// * @param multiplier The ECMultiplier to be used to multiply -// * this ECPoint. -// */ -// public void setECMultiplier(ECMultiplier multiplier) -// { -// this.multiplier = multiplier; -// } - - /** - * Sets the PreCompInfo. Used by ECMultipliers - * to save the precomputation for this ECPoint to store the - * precomputation result for use by subsequent multiplication. - * @param preCompInfo The values precomputed by the - * ECMultiplier. - */ - void setPreCompInfo(PreCompInfo preCompInfo) - { - this.preCompInfo = preCompInfo; - } - - public abstract byte[] getEncoded(); - - public abstract ECPoint add(ECPoint b); - public abstract ECPoint subtract(ECPoint b); - public abstract ECPoint negate(); - public abstract ECPoint twice(); - - /** - * Sets the default ECMultiplier, unless already set. - */ - synchronized void assertECMultiplier() - { - if (this.multiplier == null) - { - this.multiplier = new FpNafMultiplier(); - } - } - - /** - * Multiplies this ECPoint by the given number. - * @param k The multiplicator. - * @return k * this. - */ - public ECPoint multiply(BigInteger k) - { - if (this.isInfinity()) - { - return this; - } - - if (k.signum() == 0) - { - return this.curve.getInfinity(); - } - - assertECMultiplier(); - return this.multiplier.multiply(this, k, preCompInfo); - } - - /** - * Elliptic curve points over Fp - */ - public static class Fp extends ECPoint - { - - /** - * Create a point which encodes with point compression. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - */ - public Fp(ECCurve curve, ECFieldElement x, ECFieldElement y) - { - this(curve, x, y, false); - } - - /** - * Create a point that encodes with or without point compresion. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - * @param withCompression if true encode with point compression - */ - public Fp(ECCurve curve, ECFieldElement x, ECFieldElement y, boolean withCompression) - { - super(curve, x, y); - - if ((x != null && y == null) || (x == null && y != null)) - { - throw new IllegalArgumentException("Exactly one of the field elements is null"); - } - - this.withCompression = withCompression; - } - - /** - * return the field element encoded with point compression. (S 4.3.6) - */ - public byte[] getEncoded() - { - if (this.isInfinity()) - { - return new byte[1]; - } - - int qLength = converter.getByteLength(x); - - if (withCompression) - { - byte PC; - - if (this.getY().toBigInteger().testBit(0)) - { - PC = 0x03; - } - else - { - PC = 0x02; - } - - byte[] X = converter.integerToBytes(this.getX().toBigInteger(), qLength); - byte[] PO = new byte[X.length + 1]; - - PO[0] = PC; - System.arraycopy(X, 0, PO, 1, X.length); - - return PO; - } - else - { - byte[] X = converter.integerToBytes(this.getX().toBigInteger(), qLength); - byte[] Y = converter.integerToBytes(this.getY().toBigInteger(), qLength); - byte[] PO = new byte[X.length + Y.length + 1]; - - PO[0] = 0x04; - System.arraycopy(X, 0, PO, 1, X.length); - System.arraycopy(Y, 0, PO, X.length + 1, Y.length); - - return PO; - } - } - - // B.3 pg 62 - public ECPoint add(ECPoint b) - { - if (this.isInfinity()) - { - return b; - } - - if (b.isInfinity()) - { - return this; - } - - // Check if b = this or b = -this - if (this.x.equals(b.x)) - { - if (this.y.equals(b.y)) - { - // this = b, i.e. this must be doubled - return this.twice(); - } - - // this = -b, i.e. the result is the point at infinity - return this.curve.getInfinity(); - } - - ECFieldElement gamma = b.y.subtract(this.y).divide(b.x.subtract(this.x)); - - ECFieldElement x3 = gamma.square().subtract(this.x).subtract(b.x); - ECFieldElement y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ECPoint.Fp(curve, x3, y3); - } - - // B.3 pg 62 - public ECPoint twice() - { - if (this.isInfinity()) - { - // Twice identity element (point at infinity) is identity - return this; - } - - if (this.y.toBigInteger().signum() == 0) - { - // if y1 == 0, then (x1, y1) == (x1, -y1) - // and hence this = -this and thus 2(x1, y1) == infinity - return this.curve.getInfinity(); - } - - ECFieldElement TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); - ECFieldElement THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); - ECFieldElement gamma = this.x.square().multiply(THREE).add(curve.a).divide(y.multiply(TWO)); - - ECFieldElement x3 = gamma.square().subtract(this.x.multiply(TWO)); - ECFieldElement y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ECPoint.Fp(curve, x3, y3, this.withCompression); - } - - // D.3.2 pg 102 (see Note:) - public ECPoint subtract(ECPoint b) - { - if (b.isInfinity()) - { - return this; - } - - // Add -b - return add(b.negate()); - } - - public ECPoint negate() - { - return new ECPoint.Fp(curve, this.x, this.y.negate(), this.withCompression); - } - - // TODO Uncomment this to enable WNAF algorithm for Fp point multiplication -// /** -// * Sets the default ECMultiplier, unless already set. -// */ -// synchronized void assertECMultiplier() -// { -// if (this.multiplier == null) -// { -// this.multiplier = new WNafMultiplier(); -// } -// } - } - - /** - * Elliptic curve points over F2m - */ - public static class F2m extends ECPoint - { - /** - * @param curve base curve - * @param x x point - * @param y y point - */ - public F2m(ECCurve curve, ECFieldElement x, ECFieldElement y) - { - this(curve, x, y, false); - } - - /** - * @param curve base curve - * @param x x point - * @param y y point - * @param withCompression true if encode with point compression. - */ - public F2m(ECCurve curve, ECFieldElement x, ECFieldElement y, boolean withCompression) - { - super(curve, x, y); - - if ((x != null && y == null) || (x == null && y != null)) - { - throw new IllegalArgumentException("Exactly one of the field elements is null"); - } - - if (x != null) - { - // Check if x and y are elements of the same field - ECFieldElement.F2m.checkFieldElements(this.x, this.y); - - // Check if x and a are elements of the same field - if (curve != null) - { - ECFieldElement.F2m.checkFieldElements(this.x, this.curve.getA()); - } - } - - this.withCompression = withCompression; - } - - /** - * @deprecated use ECCurve.getInfinity() - * Constructor for point at infinity - */ - public F2m(ECCurve curve) - { - super(curve, null, null); - } - - /* (non-Javadoc) - * @see org.bouncycastle.math.ec.ECPoint#getEncoded() - */ - public byte[] getEncoded() - { - if (this.isInfinity()) - { - return new byte[1]; - } - - int byteCount = converter.getByteLength(this.x); - byte[] X = converter.integerToBytes(this.getX().toBigInteger(), byteCount); - byte[] PO; - - if (withCompression) - { - // See X9.62 4.3.6 and 4.2.2 - PO = new byte[byteCount + 1]; - - PO[0] = 0x02; - // X9.62 4.2.2 and 4.3.6: - // if x = 0 then ypTilde := 0, else ypTilde is the rightmost - // bit of y * x^(-1) - // if ypTilde = 0, then PC := 02, else PC := 03 - // Note: PC === PO[0] - if (!(this.getX().toBigInteger().equals(ECConstants.ZERO))) - { - if (this.getY().multiply(this.getX().invert()) - .toBigInteger().testBit(0)) - { - // ypTilde = 1, hence PC = 03 - PO[0] = 0x03; - } - } - - System.arraycopy(X, 0, PO, 1, byteCount); - } - else - { - byte[] Y = converter.integerToBytes(this.getY().toBigInteger(), byteCount); - - PO = new byte[byteCount + byteCount + 1]; - - PO[0] = 0x04; - System.arraycopy(X, 0, PO, 1, byteCount); - System.arraycopy(Y, 0, PO, byteCount + 1, byteCount); - } - - return PO; - } - - /** - * Check, if two ECPoints can be added or subtracted. - * @param a The first ECPoint to check. - * @param b The second ECPoint to check. - * @throws IllegalArgumentException if a and b - * cannot be added. - */ - private static void checkPoints(ECPoint a, ECPoint b) - { - // Check, if points are on the same curve - if (!(a.curve.equals(b.curve))) - { - throw new IllegalArgumentException("Only points on the same " - + "curve can be added or subtracted"); - } - -// ECFieldElement.F2m.checkFieldElements(a.x, b.x); - } - - /* (non-Javadoc) - * @see org.bouncycastle.math.ec.ECPoint#add(org.bouncycastle.math.ec.ECPoint) - */ - public ECPoint add(ECPoint b) - { - checkPoints(this, b); - return addSimple((ECPoint.F2m)b); - } - - /** - * Adds another ECPoints.F2m to this without - * checking if both points are on the same curve. Used by multiplication - * algorithms, because there all points are a multiple of the same point - * and hence the checks can be omitted. - * @param b The other ECPoints.F2m to add to - * this. - * @return this + b - */ - public ECPoint.F2m addSimple(ECPoint.F2m b) - { - ECPoint.F2m other = b; - if (this.isInfinity()) - { - return other; - } - - if (other.isInfinity()) - { - return this; - } - - ECFieldElement.F2m x2 = (ECFieldElement.F2m)other.getX(); - ECFieldElement.F2m y2 = (ECFieldElement.F2m)other.getY(); - - // Check if other = this or other = -this - if (this.x.equals(x2)) - { - if (this.y.equals(y2)) - { - // this = other, i.e. this must be doubled - return (ECPoint.F2m)this.twice(); - } - - // this = -other, i.e. the result is the point at infinity - return (ECPoint.F2m)this.curve.getInfinity(); - } - - ECFieldElement.F2m lambda - = (ECFieldElement.F2m)(this.y.add(y2)).divide(this.x.add(x2)); - - ECFieldElement.F2m x3 - = (ECFieldElement.F2m)lambda.square().add(lambda).add(this.x).add(x2).add(this.curve.getA()); - - ECFieldElement.F2m y3 - = (ECFieldElement.F2m)lambda.multiply(this.x.add(x3)).add(x3).add(this.y); - - return new ECPoint.F2m(curve, x3, y3, withCompression); - } - - /* (non-Javadoc) - * @see org.bouncycastle.math.ec.ECPoint#subtract(org.bouncycastle.math.ec.ECPoint) - */ - public ECPoint subtract(ECPoint b) - { - checkPoints(this, b); - return subtractSimple((ECPoint.F2m)b); - } - - /** - * Subtracts another ECPoints.F2m from this - * without checking if both points are on the same curve. Used by - * multiplication algorithms, because there all points are a multiple - * of the same point and hence the checks can be omitted. - * @param b The other ECPoints.F2m to subtract from - * this. - * @return this - b - */ - public ECPoint.F2m subtractSimple(ECPoint.F2m b) - { - if (b.isInfinity()) - { - return this; - } - - // Add -b - return addSimple((ECPoint.F2m)b.negate()); - } - - /* (non-Javadoc) - * @see org.bouncycastle.math.ec.ECPoint#twice() - */ - public ECPoint twice() - { - if (this.isInfinity()) - { - // Twice identity element (point at infinity) is identity - return this; - } - - if (this.x.toBigInteger().signum() == 0) - { - // if x1 == 0, then (x1, y1) == (x1, x1 + y1) - // and hence this = -this and thus 2(x1, y1) == infinity - return this.curve.getInfinity(); - } - - ECFieldElement.F2m lambda - = (ECFieldElement.F2m)this.x.add(this.y.divide(this.x)); - - ECFieldElement.F2m x3 - = (ECFieldElement.F2m)lambda.square().add(lambda). - add(this.curve.getA()); - - ECFieldElement ONE = this.curve.fromBigInteger(ECConstants.ONE); - ECFieldElement.F2m y3 - = (ECFieldElement.F2m)this.x.square().add( - x3.multiply(lambda.add(ONE))); - - return new ECPoint.F2m(this.curve, x3, y3, withCompression); - } - - public ECPoint negate() - { - return new ECPoint.F2m(curve, this.getX(), this.getY().add(this.getX()), withCompression); - } - - // TODO Uncomment this to enable WNAF/WTNAF F2m point multiplication -// /** -// * Sets the appropriate ECMultiplier, unless already set. -// */ -// synchronized void assertECMultiplier() -// { -// if (this.multiplier == null) -// { -// if (((ECCurve.F2m)(this.curve)).isKoblitz()) -// { -// this.multiplier = new WTauNafMultiplier(); -// } -// else -// { -// this.multiplier = new WNafMultiplier(); -// } -// } -// } - } -} diff --git a/src/org/bouncycastle/math/ec/FpNafMultiplier.java b/src/org/bouncycastle/math/ec/FpNafMultiplier.java deleted file mode 100644 index 35e601d5a0..0000000000 --- a/src/org/bouncycastle/math/ec/FpNafMultiplier.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm. - */ -class FpNafMultiplier implements ECMultiplier -{ - /** - * D.3.2 pg 101 - * @see org.bouncycastle.math.ec.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger) - */ - public ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) - { - // TODO Probably should try to add this - // BigInteger e = k.mod(n); // n == order of p - BigInteger e = k; - BigInteger h = e.multiply(BigInteger.valueOf(3)); - - ECPoint neg = p.negate(); - ECPoint R = p; - - for (int i = h.bitLength() - 2; i > 0; --i) - { - R = R.twice(); - - boolean hBit = h.testBit(i); - boolean eBit = e.testBit(i); - - if (hBit != eBit) - { - R = R.add(hBit ? p : neg); - } - } - - return R; - } -} diff --git a/src/org/bouncycastle/math/ec/IntArray.java b/src/org/bouncycastle/math/ec/IntArray.java deleted file mode 100644 index ead38c4809..0000000000 --- a/src/org/bouncycastle/math/ec/IntArray.java +++ /dev/null @@ -1,518 +0,0 @@ -package org.bouncycastle.math.ec; - -import org.bouncycastle.util.Arrays; - -import java.math.BigInteger; - -class IntArray -{ - // TODO make m fixed for the IntArray, and hence compute T once and for all - - private int[] m_ints; - - public IntArray(int intLen) - { - m_ints = new int[intLen]; - } - - public IntArray(int[] ints) - { - m_ints = ints; - } - - public IntArray(BigInteger bigInt) - { - this(bigInt, 0); - } - - public IntArray(BigInteger bigInt, int minIntLen) - { - if (bigInt.signum() == -1) - { - throw new IllegalArgumentException("Only positive Integers allowed"); - } - if (bigInt.equals(ECConstants.ZERO)) - { - m_ints = new int[] { 0 }; - return; - } - - byte[] barr = bigInt.toByteArray(); - int barrLen = barr.length; - int barrStart = 0; - if (barr[0] == 0) - { - // First byte is 0 to enforce highest (=sign) bit is zero. - // In this case ignore barr[0]. - barrLen--; - barrStart = 1; - } - int intLen = (barrLen + 3) / 4; - if (intLen < minIntLen) - { - m_ints = new int[minIntLen]; - } - else - { - m_ints = new int[intLen]; - } - - int iarrJ = intLen - 1; - int rem = barrLen % 4 + barrStart; - int temp = 0; - int barrI = barrStart; - if (barrStart < rem) - { - for (; barrI < rem; barrI++) - { - temp <<= 8; - int barrBarrI = barr[barrI]; - if (barrBarrI < 0) - { - barrBarrI += 256; - } - temp |= barrBarrI; - } - m_ints[iarrJ--] = temp; - } - - for (; iarrJ >= 0; iarrJ--) - { - temp = 0; - for (int i = 0; i < 4; i++) - { - temp <<= 8; - int barrBarrI = barr[barrI++]; - if (barrBarrI < 0) - { - barrBarrI += 256; - } - temp |= barrBarrI; - } - m_ints[iarrJ] = temp; - } - } - - public boolean isZero() - { - return m_ints.length == 0 - || (m_ints[0] == 0 && getUsedLength() == 0); - } - - public int getUsedLength() - { - int highestIntPos = m_ints.length; - - if (highestIntPos < 1) - { - return 0; - } - - // Check if first element will act as sentinel - if (m_ints[0] != 0) - { - while (m_ints[--highestIntPos] == 0) - { - } - return highestIntPos + 1; - } - - do - { - if (m_ints[--highestIntPos] != 0) - { - return highestIntPos + 1; - } - } - while (highestIntPos > 0); - - return 0; - } - - public int bitLength() - { - // JDK 1.5: see Integer.numberOfLeadingZeros() - int intLen = getUsedLength(); - if (intLen == 0) - { - return 0; - } - - int last = intLen - 1; - int highest = m_ints[last]; - int bits = (last << 5) + 1; - - // A couple of binary search steps - if ((highest & 0xffff0000) != 0) - { - if ((highest & 0xff000000) != 0) - { - bits += 24; - highest >>>= 24; - } - else - { - bits += 16; - highest >>>= 16; - } - } - else if (highest > 0x000000ff) - { - bits += 8; - highest >>>= 8; - } - - while (highest != 1) - { - ++bits; - highest >>>= 1; - } - - return bits; - } - - private int[] resizedInts(int newLen) - { - int[] newInts = new int[newLen]; - int oldLen = m_ints.length; - int copyLen = oldLen < newLen ? oldLen : newLen; - System.arraycopy(m_ints, 0, newInts, 0, copyLen); - return newInts; - } - - public BigInteger toBigInteger() - { - int usedLen = getUsedLength(); - if (usedLen == 0) - { - return ECConstants.ZERO; - } - - int highestInt = m_ints[usedLen - 1]; - byte[] temp = new byte[4]; - int barrI = 0; - boolean trailingZeroBytesDone = false; - for (int j = 3; j >= 0; j--) - { - byte thisByte = (byte) (highestInt >>> (8 * j)); - if (trailingZeroBytesDone || (thisByte != 0)) - { - trailingZeroBytesDone = true; - temp[barrI++] = thisByte; - } - } - - int barrLen = 4 * (usedLen - 1) + barrI; - byte[] barr = new byte[barrLen]; - for (int j = 0; j < barrI; j++) - { - barr[j] = temp[j]; - } - // Highest value int is done now - - for (int iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--) - { - for (int j = 3; j >= 0; j--) - { - barr[barrI++] = (byte) (m_ints[iarrJ] >>> (8 * j)); - } - } - return new BigInteger(1, barr); - } - - public void shiftLeft() - { - int usedLen = getUsedLength(); - if (usedLen == 0) - { - return; - } - if (m_ints[usedLen - 1] < 0) - { - // highest bit of highest used byte is set, so shifting left will - // make the IntArray one byte longer - usedLen++; - if (usedLen > m_ints.length) - { - // make the m_ints one byte longer, because we need one more - // byte which is not available in m_ints - m_ints = resizedInts(m_ints.length + 1); - } - } - - boolean carry = false; - for (int i = 0; i < usedLen; i++) - { - // nextCarry is true if highest bit is set - boolean nextCarry = m_ints[i] < 0; - m_ints[i] <<= 1; - if (carry) - { - // set lowest bit - m_ints[i] |= 1; - } - carry = nextCarry; - } - } - - public IntArray shiftLeft(int n) - { - int usedLen = getUsedLength(); - if (usedLen == 0) - { - return this; - } - - if (n == 0) - { - return this; - } - - if (n > 31) - { - throw new IllegalArgumentException("shiftLeft() for max 31 bits " - + ", " + n + "bit shift is not possible"); - } - - int[] newInts = new int[usedLen + 1]; - - int nm32 = 32 - n; - newInts[0] = m_ints[0] << n; - for (int i = 1; i < usedLen; i++) - { - newInts[i] = (m_ints[i] << n) | (m_ints[i - 1] >>> nm32); - } - newInts[usedLen] = m_ints[usedLen - 1] >>> nm32; - - return new IntArray(newInts); - } - - public void addShifted(IntArray other, int shift) - { - int usedLenOther = other.getUsedLength(); - int newMinUsedLen = usedLenOther + shift; - if (newMinUsedLen > m_ints.length) - { - m_ints = resizedInts(newMinUsedLen); - //System.out.println("Resize required"); - } - - for (int i = 0; i < usedLenOther; i++) - { - m_ints[i + shift] ^= other.m_ints[i]; - } - } - - public int getLength() - { - return m_ints.length; - } - - public boolean testBit(int n) - { - // theInt = n / 32 - int theInt = n >> 5; - // theBit = n % 32 - int theBit = n & 0x1F; - int tester = 1 << theBit; - return ((m_ints[theInt] & tester) != 0); - } - - public void flipBit(int n) - { - // theInt = n / 32 - int theInt = n >> 5; - // theBit = n % 32 - int theBit = n & 0x1F; - int flipper = 1 << theBit; - m_ints[theInt] ^= flipper; - } - - public void setBit(int n) - { - // theInt = n / 32 - int theInt = n >> 5; - // theBit = n % 32 - int theBit = n & 0x1F; - int setter = 1 << theBit; - m_ints[theInt] |= setter; - } - - public IntArray multiply(IntArray other, int m) - { - // Lenght of c is 2m bits rounded up to the next int (32 bit) - int t = (m + 31) >> 5; - if (m_ints.length < t) - { - m_ints = resizedInts(t); - } - - IntArray b = new IntArray(other.resizedInts(other.getLength() + 1)); - IntArray c = new IntArray((m + m + 31) >> 5); - // IntArray c = new IntArray(t + t); - int testBit = 1; - for (int k = 0; k < 32; k++) - { - for (int j = 0; j < t; j++) - { - if ((m_ints[j] & testBit) != 0) - { - // The kth bit of m_ints[j] is set - c.addShifted(b, j); - } - } - testBit <<= 1; - b.shiftLeft(); - } - return c; - } - - // public IntArray multiplyLeftToRight(IntArray other, int m) { - // // Lenght of c is 2m bits rounded up to the next int (32 bit) - // int t = (m + 31) / 32; - // if (m_ints.length < t) { - // m_ints = resizedInts(t); - // } - // - // IntArray b = new IntArray(other.resizedInts(other.getLength() + 1)); - // IntArray c = new IntArray((m + m + 31) / 32); - // // IntArray c = new IntArray(t + t); - // int testBit = 1 << 31; - // for (int k = 31; k >= 0; k--) { - // for (int j = 0; j < t; j++) { - // if ((m_ints[j] & testBit) != 0) { - // // The kth bit of m_ints[j] is set - // c.addShifted(b, j); - // } - // } - // testBit >>>= 1; - // if (k > 0) { - // c.shiftLeft(); - // } - // } - // return c; - // } - - // TODO note, redPol.length must be 3 for TPB and 5 for PPB - public void reduce(int m, int[] redPol) - { - for (int i = m + m - 2; i >= m; i--) - { - if (testBit(i)) - { - int bit = i - m; - flipBit(bit); - flipBit(i); - int l = redPol.length; - while (--l >= 0) - { - flipBit(redPol[l] + bit); - } - } - } - m_ints = resizedInts((m + 31) >> 5); - } - - public IntArray square(int m) - { - // TODO make the table static final - final int[] table = { 0x0, 0x1, 0x4, 0x5, 0x10, 0x11, 0x14, 0x15, 0x40, - 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55 }; - - int t = (m + 31) >> 5; - if (m_ints.length < t) - { - m_ints = resizedInts(t); - } - - IntArray c = new IntArray(t + t); - - // TODO twice the same code, put in separate private method - for (int i = 0; i < t; i++) - { - int v0 = 0; - for (int j = 0; j < 4; j++) - { - v0 = v0 >>> 8; - int u = (m_ints[i] >>> (j * 4)) & 0xF; - int w = table[u] << 24; - v0 |= w; - } - c.m_ints[i + i] = v0; - - v0 = 0; - int upper = m_ints[i] >>> 16; - for (int j = 0; j < 4; j++) - { - v0 = v0 >>> 8; - int u = (upper >>> (j * 4)) & 0xF; - int w = table[u] << 24; - v0 |= w; - } - c.m_ints[i + i + 1] = v0; - } - return c; - } - - public boolean equals(Object o) - { - if (!(o instanceof IntArray)) - { - return false; - } - IntArray other = (IntArray) o; - int usedLen = getUsedLength(); - if (other.getUsedLength() != usedLen) - { - return false; - } - for (int i = 0; i < usedLen; i++) - { - if (m_ints[i] != other.m_ints[i]) - { - return false; - } - } - return true; - } - - public int hashCode() - { - int usedLen = getUsedLength(); - int hash = 1; - for (int i = 0; i < usedLen; i++) - { - hash = hash * 31 + m_ints[i]; - } - return hash; - } - - public Object clone() - { - return new IntArray(Arrays.clone(m_ints)); - } - - public String toString() - { - int usedLen = getUsedLength(); - if (usedLen == 0) - { - return "0"; - } - - StringBuffer sb = new StringBuffer(Integer - .toBinaryString(m_ints[usedLen - 1])); - for (int iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--) - { - String hexString = Integer.toBinaryString(m_ints[iarrJ]); - - // Add leading zeroes, except for highest significant int - for (int i = hexString.length(); i < 8; i++) - { - hexString = "0" + hexString; - } - sb.append(hexString); - } - return sb.toString(); - } -} diff --git a/src/org/bouncycastle/math/ec/PreCompInfo.java b/src/org/bouncycastle/math/ec/PreCompInfo.java deleted file mode 100644 index 804dcf749f..0000000000 --- a/src/org/bouncycastle/math/ec/PreCompInfo.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bouncycastle.math.ec; - -/** - * Interface for classes storing precomputation data for multiplication - * algorithms. Used as a Memento (see GOF patterns) for - * WNafMultiplier. - */ -interface PreCompInfo -{ -} diff --git a/src/org/bouncycastle/math/ec/ReferenceMultiplier.java b/src/org/bouncycastle/math/ec/ReferenceMultiplier.java deleted file mode 100644 index c1dd54831f..0000000000 --- a/src/org/bouncycastle/math/ec/ReferenceMultiplier.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -class ReferenceMultiplier implements ECMultiplier -{ - /** - * Simple shift-and-add multiplication. Serves as reference implementation - * to verify (possibly faster) implementations in - * {@link org.bouncycastle.math.ec.ECPoint ECPoint}. - * - * @param p The point to multiply. - * @param k The factor by which to multiply. - * @return The result of the point multiplication k * p. - */ - public ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) - { - ECPoint q = p.getCurve().getInfinity(); - int t = k.bitLength(); - for (int i = 0; i < t; i++) - { - if (k.testBit(i)) - { - q = q.add(p); - } - p = p.twice(); - } - return q; - } -} diff --git a/src/org/bouncycastle/math/ec/SimpleBigDecimal.java b/src/org/bouncycastle/math/ec/SimpleBigDecimal.java deleted file mode 100644 index 96e666d1b2..0000000000 --- a/src/org/bouncycastle/math/ec/SimpleBigDecimal.java +++ /dev/null @@ -1,253 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class representing a simple version of a big decimal. A - * SimpleBigDecimal is basically a - * {@link java.math.BigInteger BigInteger} with a few digits on the right of - * the decimal point. The number of (binary) digits on the right of the decimal - * point is called the scale of the SimpleBigDecimal. - * Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted - * automatically, but must be set manually. All SimpleBigDecimals - * taking part in the same arithmetic operation must have equal scale. The - * result of a multiplication of two SimpleBigDecimals returns a - * SimpleBigDecimal with double scale. - */ -class SimpleBigDecimal - //extends Number // not in J2ME - add compatibility class? -{ - private static final long serialVersionUID = 1L; - - private final BigInteger bigInt; - private final int scale; - - /** - * Returns a SimpleBigDecimal representing the same numerical - * value as value. - * @param value The value of the SimpleBigDecimal to be - * created. - * @param scale The scale of the SimpleBigDecimal to be - * created. - * @return The such created SimpleBigDecimal. - */ - public static SimpleBigDecimal getInstance(BigInteger value, int scale) - { - return new SimpleBigDecimal(value.shiftLeft(scale), scale); - } - - /** - * Constructor for SimpleBigDecimal. The value of the - * constructed SimpleBigDecimal equals bigInt / - * 2scale. - * @param bigInt The bigInt value parameter. - * @param scale The scale of the constructed SimpleBigDecimal. - */ - public SimpleBigDecimal(BigInteger bigInt, int scale) - { - if (scale < 0) - { - throw new IllegalArgumentException("scale may not be negative"); - } - - this.bigInt = bigInt; - this.scale = scale; - } - - private SimpleBigDecimal(SimpleBigDecimal limBigDec) - { - bigInt = limBigDec.bigInt; - scale = limBigDec.scale; - } - - private void checkScale(SimpleBigDecimal b) - { - if (scale != b.scale) - { - throw new IllegalArgumentException("Only SimpleBigDecimal of " + - "same scale allowed in arithmetic operations"); - } - } - - public SimpleBigDecimal adjustScale(int newScale) - { - if (newScale < 0) - { - throw new IllegalArgumentException("scale may not be negative"); - } - - if (newScale == scale) - { - return new SimpleBigDecimal(this); - } - - return new SimpleBigDecimal(bigInt.shiftLeft(newScale - scale), - newScale); - } - - public SimpleBigDecimal add(SimpleBigDecimal b) - { - checkScale(b); - return new SimpleBigDecimal(bigInt.add(b.bigInt), scale); - } - - public SimpleBigDecimal add(BigInteger b) - { - return new SimpleBigDecimal(bigInt.add(b.shiftLeft(scale)), scale); - } - - public SimpleBigDecimal negate() - { - return new SimpleBigDecimal(bigInt.negate(), scale); - } - - public SimpleBigDecimal subtract(SimpleBigDecimal b) - { - return add(b.negate()); - } - - public SimpleBigDecimal subtract(BigInteger b) - { - return new SimpleBigDecimal(bigInt.subtract(b.shiftLeft(scale)), - scale); - } - - public SimpleBigDecimal multiply(SimpleBigDecimal b) - { - checkScale(b); - return new SimpleBigDecimal(bigInt.multiply(b.bigInt), scale + scale); - } - - public SimpleBigDecimal multiply(BigInteger b) - { - return new SimpleBigDecimal(bigInt.multiply(b), scale); - } - - public SimpleBigDecimal divide(SimpleBigDecimal b) - { - checkScale(b); - BigInteger dividend = bigInt.shiftLeft(scale); - return new SimpleBigDecimal(dividend.divide(b.bigInt), scale); - } - - public SimpleBigDecimal divide(BigInteger b) - { - return new SimpleBigDecimal(bigInt.divide(b), scale); - } - - public SimpleBigDecimal shiftLeft(int n) - { - return new SimpleBigDecimal(bigInt.shiftLeft(n), scale); - } - - public int compareTo(SimpleBigDecimal val) - { - checkScale(val); - return bigInt.compareTo(val.bigInt); - } - - public int compareTo(BigInteger val) - { - return bigInt.compareTo(val.shiftLeft(scale)); - } - - public BigInteger floor() - { - return bigInt.shiftRight(scale); - } - - public BigInteger round() - { - SimpleBigDecimal oneHalf = new SimpleBigDecimal(ECConstants.ONE, 1); - return add(oneHalf.adjustScale(scale)).floor(); - } - - public int intValue() - { - return floor().intValue(); - } - - public long longValue() - { - return floor().longValue(); - } - /* NON-J2ME compliant. - public double doubleValue() - { - return Double.valueOf(toString()).doubleValue(); - } - - public float floatValue() - { - return Float.valueOf(toString()).floatValue(); - } - */ - public int getScale() - { - return scale; - } - - public String toString() - { - if (scale == 0) - { - return bigInt.toString(); - } - - BigInteger floorBigInt = floor(); - - BigInteger fract = bigInt.subtract(floorBigInt.shiftLeft(scale)); - if (bigInt.signum() == -1) - { - fract = ECConstants.ONE.shiftLeft(scale).subtract(fract); - } - - if ((floorBigInt.signum() == -1) && (!(fract.equals(ECConstants.ZERO)))) - { - floorBigInt = floorBigInt.add(ECConstants.ONE); - } - String leftOfPoint = floorBigInt.toString(); - - char[] fractCharArr = new char[scale]; - String fractStr = fract.toString(2); - int fractLen = fractStr.length(); - int zeroes = scale - fractLen; - for (int i = 0; i < zeroes; i++) - { - fractCharArr[i] = '0'; - } - for (int j = 0; j < fractLen; j++) - { - fractCharArr[zeroes + j] = fractStr.charAt(j); - } - String rightOfPoint = new String(fractCharArr); - - StringBuffer sb = new StringBuffer(leftOfPoint); - sb.append("."); - sb.append(rightOfPoint); - - return sb.toString(); - } - - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - - if (!(o instanceof SimpleBigDecimal)) - { - return false; - } - - SimpleBigDecimal other = (SimpleBigDecimal)o; - return ((bigInt.equals(other.bigInt)) && (scale == other.scale)); - } - - public int hashCode() - { - return bigInt.hashCode() ^ scale; - } - -} diff --git a/src/org/bouncycastle/math/ec/Tnaf.java b/src/org/bouncycastle/math/ec/Tnaf.java deleted file mode 100644 index af4355f3d6..0000000000 --- a/src/org/bouncycastle/math/ec/Tnaf.java +++ /dev/null @@ -1,844 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class holding methods for point multiplication based on the window - * τ-adic nonadjacent form (WTNAF). The algorithms are based on the - * paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves" - * by Jerome A. Solinas. The paper first appeared in the Proceedings of - * Crypto 1997. - */ -class Tnaf -{ - private static final BigInteger MINUS_ONE = ECConstants.ONE.negate(); - private static final BigInteger MINUS_TWO = ECConstants.TWO.negate(); - private static final BigInteger MINUS_THREE = ECConstants.THREE.negate(); - - /** - * The window width of WTNAF. The standard value of 4 is slightly less - * than optimal for running time, but keeps space requirements for - * precomputation low. For typical curves, a value of 5 or 6 results in - * a better running time. When changing this value, the - * αu's must be computed differently, see - * e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson, - * Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004, - * p. 121-122 - */ - public static final byte WIDTH = 4; - - /** - * 24 - */ - public static final byte POW_2_WIDTH = 16; - - /** - * The αu's for a=0 as an array - * of ZTauElements. - */ - public static final ZTauElement[] alpha0 = { - null, - new ZTauElement(ECConstants.ONE, ECConstants.ZERO), null, - new ZTauElement(MINUS_THREE, MINUS_ONE), null, - new ZTauElement(MINUS_ONE, MINUS_ONE), null, - new ZTauElement(ECConstants.ONE, MINUS_ONE), null - }; - - /** - * The αu's for a=0 as an array - * of TNAFs. - */ - public static final byte[][] alpha0Tnaf = { - null, {1}, null, {-1, 0, 1}, null, {1, 0, 1}, null, {-1, 0, 0, 1} - }; - - /** - * The αu's for a=1 as an array - * of ZTauElements. - */ - public static final ZTauElement[] alpha1 = {null, - new ZTauElement(ECConstants.ONE, ECConstants.ZERO), null, - new ZTauElement(MINUS_THREE, ECConstants.ONE), null, - new ZTauElement(MINUS_ONE, ECConstants.ONE), null, - new ZTauElement(ECConstants.ONE, ECConstants.ONE), null - }; - - /** - * The αu's for a=1 as an array - * of TNAFs. - */ - public static final byte[][] alpha1Tnaf = { - null, {1}, null, {-1, 0, 1}, null, {1, 0, 1}, null, {-1, 0, 0, -1} - }; - - /** - * Computes the norm of an element λ of - * Z[τ]. - * @param mu The parameter μ of the elliptic curve. - * @param lambda The element λ of - * Z[τ]. - * @return The norm of λ. - */ - public static BigInteger norm(final byte mu, ZTauElement lambda) - { - BigInteger norm; - - // s1 = u^2 - BigInteger s1 = lambda.u.multiply(lambda.u); - - // s2 = u * v - BigInteger s2 = lambda.u.multiply(lambda.v); - - // s3 = 2 * v^2 - BigInteger s3 = lambda.v.multiply(lambda.v).shiftLeft(1); - - if (mu == 1) - { - norm = s1.add(s2).add(s3); - } - else if (mu == -1) - { - norm = s1.subtract(s2).add(s3); - } - else - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - return norm; - } - - /** - * Computes the norm of an element λ of - * R[τ], where λ = u + vτ - * and u and u are real numbers (elements of - * R). - * @param mu The parameter μ of the elliptic curve. - * @param u The real part of the element λ of - * R[τ]. - * @param v The τ-adic part of the element - * λ of R[τ]. - * @return The norm of λ. - */ - public static SimpleBigDecimal norm(final byte mu, SimpleBigDecimal u, - SimpleBigDecimal v) - { - SimpleBigDecimal norm; - - // s1 = u^2 - SimpleBigDecimal s1 = u.multiply(u); - - // s2 = u * v - SimpleBigDecimal s2 = u.multiply(v); - - // s3 = 2 * v^2 - SimpleBigDecimal s3 = v.multiply(v).shiftLeft(1); - - if (mu == 1) - { - norm = s1.add(s2).add(s3); - } - else if (mu == -1) - { - norm = s1.subtract(s2).add(s3); - } - else - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - return norm; - } - - /** - * Rounds an element λ of R[τ] - * to an element of Z[τ], such that their difference - * has minimal norm. λ is given as - * λ = λ0 + λ1τ. - * @param lambda0 The component λ0. - * @param lambda1 The component λ1. - * @param mu The parameter μ of the elliptic curve. Must - * equal 1 or -1. - * @return The rounded element of Z[τ]. - * @throws IllegalArgumentException if lambda0 and - * lambda1 do not have same scale. - */ - public static ZTauElement round(SimpleBigDecimal lambda0, - SimpleBigDecimal lambda1, byte mu) - { - int scale = lambda0.getScale(); - if (lambda1.getScale() != scale) - { - throw new IllegalArgumentException("lambda0 and lambda1 do not " + - "have same scale"); - } - - if (!((mu == 1) || (mu == -1))) - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - BigInteger f0 = lambda0.round(); - BigInteger f1 = lambda1.round(); - - SimpleBigDecimal eta0 = lambda0.subtract(f0); - SimpleBigDecimal eta1 = lambda1.subtract(f1); - - // eta = 2*eta0 + mu*eta1 - SimpleBigDecimal eta = eta0.add(eta0); - if (mu == 1) - { - eta = eta.add(eta1); - } - else - { - // mu == -1 - eta = eta.subtract(eta1); - } - - // check1 = eta0 - 3*mu*eta1 - // check2 = eta0 + 4*mu*eta1 - SimpleBigDecimal threeEta1 = eta1.add(eta1).add(eta1); - SimpleBigDecimal fourEta1 = threeEta1.add(eta1); - SimpleBigDecimal check1; - SimpleBigDecimal check2; - if (mu == 1) - { - check1 = eta0.subtract(threeEta1); - check2 = eta0.add(fourEta1); - } - else - { - // mu == -1 - check1 = eta0.add(threeEta1); - check2 = eta0.subtract(fourEta1); - } - - byte h0 = 0; - byte h1 = 0; - - // if eta >= 1 - if (eta.compareTo(ECConstants.ONE) >= 0) - { - if (check1.compareTo(MINUS_ONE) < 0) - { - h1 = mu; - } - else - { - h0 = 1; - } - } - else - { - // eta < 1 - if (check2.compareTo(ECConstants.TWO) >= 0) - { - h1 = mu; - } - } - - // if eta < -1 - if (eta.compareTo(MINUS_ONE) < 0) - { - if (check1.compareTo(ECConstants.ONE) >= 0) - { - h1 = (byte)-mu; - } - else - { - h0 = -1; - } - } - else - { - // eta >= -1 - if (check2.compareTo(MINUS_TWO) < 0) - { - h1 = (byte)-mu; - } - } - - BigInteger q0 = f0.add(BigInteger.valueOf(h0)); - BigInteger q1 = f1.add(BigInteger.valueOf(h1)); - return new ZTauElement(q0, q1); - } - - /** - * Approximate division by n. For an integer - * k, the value λ = s k / n is - * computed to c bits of accuracy. - * @param k The parameter k. - * @param s The curve parameter s0 or - * s1. - * @param vm The Lucas Sequence element Vm. - * @param a The parameter a of the elliptic curve. - * @param m The bit length of the finite field - * Fm. - * @param c The number of bits of accuracy, i.e. the scale of the returned - * SimpleBigDecimal. - * @return The value λ = s k / n computed to - * c bits of accuracy. - */ - public static SimpleBigDecimal approximateDivisionByN(BigInteger k, - BigInteger s, BigInteger vm, byte a, int m, int c) - { - int _k = (m + 5)/2 + c; - BigInteger ns = k.shiftRight(m - _k - 2 + a); - - BigInteger gs = s.multiply(ns); - - BigInteger hs = gs.shiftRight(m); - - BigInteger js = vm.multiply(hs); - - BigInteger gsPlusJs = gs.add(js); - BigInteger ls = gsPlusJs.shiftRight(_k-c); - if (gsPlusJs.testBit(_k-c-1)) - { - // round up - ls = ls.add(ECConstants.ONE); - } - - return new SimpleBigDecimal(ls, c); - } - - /** - * Computes the τ-adic NAF (non-adjacent form) of an - * element λ of Z[τ]. - * @param mu The parameter μ of the elliptic curve. - * @param lambda The element λ of - * Z[τ]. - * @return The τ-adic NAF of λ. - */ - public static byte[] tauAdicNaf(byte mu, ZTauElement lambda) - { - if (!((mu == 1) || (mu == -1))) - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - BigInteger norm = norm(mu, lambda); - - // Ceiling of log2 of the norm - int log2Norm = norm.bitLength(); - - // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52 - int maxLength = log2Norm > 30 ? log2Norm + 4 : 34; - - // The array holding the TNAF - byte[] u = new byte[maxLength]; - int i = 0; - - // The actual length of the TNAF - int length = 0; - - BigInteger r0 = lambda.u; - BigInteger r1 = lambda.v; - - while(!((r0.equals(ECConstants.ZERO)) && (r1.equals(ECConstants.ZERO)))) - { - // If r0 is odd - if (r0.testBit(0)) - { - u[i] = (byte) ECConstants.TWO.subtract((r0.subtract(r1.shiftLeft(1))).mod(ECConstants.FOUR)).intValue(); - - // r0 = r0 - u[i] - if (u[i] == 1) - { - r0 = r0.clearBit(0); - } - else - { - // u[i] == -1 - r0 = r0.add(ECConstants.ONE); - } - length = i; - } - else - { - u[i] = 0; - } - - BigInteger t = r0; - BigInteger s = r0.shiftRight(1); - if (mu == 1) - { - r0 = r1.add(s); - } - else - { - // mu == -1 - r0 = r1.subtract(s); - } - - r1 = t.shiftRight(1).negate(); - i++; - } - - length++; - - // Reduce the TNAF array to its actual length - byte[] tnaf = new byte[length]; - System.arraycopy(u, 0, tnaf, 0, length); - return tnaf; - } - - /** - * Applies the operation τ() to an - * ECPoint.F2m. - * @param p The ECPoint.F2m to which τ() is applied. - * @return τ(p) - */ - public static ECPoint.F2m tau(ECPoint.F2m p) - { - if (p.isInfinity()) - { - return p; - } - - ECFieldElement x = p.getX(); - ECFieldElement y = p.getY(); - - return new ECPoint.F2m(p.getCurve(), x.square(), y.square(), p.isCompressed()); - } - - /** - * Returns the parameter μ of the elliptic curve. - * @param curve The elliptic curve from which to obtain μ. - * The curve must be a Koblitz curve, i.e. a equals - * 0 or 1 and b equals - * 1. - * @return μ of the elliptic curve. - * @throws IllegalArgumentException if the given ECCurve is not a Koblitz - * curve. - */ - public static byte getMu(ECCurve.F2m curve) - { - BigInteger a = curve.getA().toBigInteger(); - byte mu; - - if (a.equals(ECConstants.ZERO)) - { - mu = -1; - } - else if (a.equals(ECConstants.ONE)) - { - mu = 1; - } - else - { - throw new IllegalArgumentException("No Koblitz curve (ABC), " + - "TNAF multiplication not possible"); - } - return mu; - } - - /** - * Calculates the Lucas Sequence elements Uk-1 and - * Uk or Vk-1 and - * Vk. - * @param mu The parameter μ of the elliptic curve. - * @param k The index of the second element of the Lucas Sequence to be - * returned. - * @param doV If set to true, computes Vk-1 and - * Vk, otherwise Uk-1 and - * Uk. - * @return An array with 2 elements, containing Uk-1 - * and Uk or Vk-1 - * and Vk. - */ - public static BigInteger[] getLucas(byte mu, int k, boolean doV) - { - if (!((mu == 1) || (mu == -1))) - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - BigInteger u0; - BigInteger u1; - BigInteger u2; - - if (doV) - { - u0 = ECConstants.TWO; - u1 = BigInteger.valueOf(mu); - } - else - { - u0 = ECConstants.ZERO; - u1 = ECConstants.ONE; - } - - for (int i = 1; i < k; i++) - { - // u2 = mu*u1 - 2*u0; - BigInteger s = null; - if (mu == 1) - { - s = u1; - } - else - { - // mu == -1 - s = u1.negate(); - } - - u2 = s.subtract(u0.shiftLeft(1)); - u0 = u1; - u1 = u2; -// System.out.println(i + ": " + u2); -// System.out.println(); - } - - BigInteger[] retVal = {u0, u1}; - return retVal; - } - - /** - * Computes the auxiliary value tw. If the width is - * 4, then for mu = 1, tw = 6 and for - * mu = -1, tw = 10 - * @param mu The parameter μ of the elliptic curve. - * @param w The window width of the WTNAF. - * @return the auxiliary value tw - */ - public static BigInteger getTw(byte mu, int w) - { - if (w == 4) - { - if (mu == 1) - { - return BigInteger.valueOf(6); - } - else - { - // mu == -1 - return BigInteger.valueOf(10); - } - } - else - { - // For w <> 4, the values must be computed - BigInteger[] us = getLucas(mu, w, false); - BigInteger twoToW = ECConstants.ZERO.setBit(w); - BigInteger u1invert = us[1].modInverse(twoToW); - BigInteger tw; - tw = ECConstants.TWO.multiply(us[0]).multiply(u1invert).mod(twoToW); -// System.out.println("mu = " + mu); -// System.out.println("tw = " + tw); - return tw; - } - } - - /** - * Computes the auxiliary values s0 and - * s1 used for partial modular reduction. - * @param curve The elliptic curve for which to compute - * s0 and s1. - * @throws IllegalArgumentException if curve is not a - * Koblitz curve (Anomalous Binary Curve, ABC). - */ - public static BigInteger[] getSi(ECCurve.F2m curve) - { - if (!curve.isKoblitz()) - { - throw new IllegalArgumentException("si is defined for Koblitz curves only"); - } - - int m = curve.getM(); - int a = curve.getA().toBigInteger().intValue(); - byte mu = curve.getMu(); - int h = curve.getH().intValue(); - int index = m + 3 - a; - BigInteger[] ui = getLucas(mu, index, false); - - BigInteger dividend0; - BigInteger dividend1; - if (mu == 1) - { - dividend0 = ECConstants.ONE.subtract(ui[1]); - dividend1 = ECConstants.ONE.subtract(ui[0]); - } - else if (mu == -1) - { - dividend0 = ECConstants.ONE.add(ui[1]); - dividend1 = ECConstants.ONE.add(ui[0]); - } - else - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - BigInteger[] si = new BigInteger[2]; - - if (h == 2) - { - si[0] = dividend0.shiftRight(1); - si[1] = dividend1.shiftRight(1).negate(); - } - else if (h == 4) - { - si[0] = dividend0.shiftRight(2); - si[1] = dividend1.shiftRight(2).negate(); - } - else - { - throw new IllegalArgumentException("h (Cofactor) must be 2 or 4"); - } - - return si; - } - - /** - * Partial modular reduction modulo - * m - 1)/(τ - 1). - * @param k The integer to be reduced. - * @param m The bitlength of the underlying finite field. - * @param a The parameter a of the elliptic curve. - * @param s The auxiliary values s0 and - * s1. - * @param mu The parameter μ of the elliptic curve. - * @param c The precision (number of bits of accuracy) of the partial - * modular reduction. - * @return ρ := k partmod (τm - 1)/(τ - 1) - */ - public static ZTauElement partModReduction(BigInteger k, int m, byte a, - BigInteger[] s, byte mu, byte c) - { - // d0 = s[0] + mu*s[1]; mu is either 1 or -1 - BigInteger d0; - if (mu == 1) - { - d0 = s[0].add(s[1]); - } - else - { - d0 = s[0].subtract(s[1]); - } - - BigInteger[] v = getLucas(mu, m, true); - BigInteger vm = v[1]; - - SimpleBigDecimal lambda0 = approximateDivisionByN( - k, s[0], vm, a, m, c); - - SimpleBigDecimal lambda1 = approximateDivisionByN( - k, s[1], vm, a, m, c); - - ZTauElement q = round(lambda0, lambda1, mu); - - // r0 = n - d0*q0 - 2*s1*q1 - BigInteger r0 = k.subtract(d0.multiply(q.u)).subtract( - BigInteger.valueOf(2).multiply(s[1]).multiply(q.v)); - - // r1 = s1*q0 - s0*q1 - BigInteger r1 = s[1].multiply(q.u).subtract(s[0].multiply(q.v)); - - return new ZTauElement(r0, r1); - } - - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by a BigInteger using the reduced τ-adic - * NAF (RTNAF) method. - * @param p The ECPoint.F2m to multiply. - * @param k The BigInteger by which to multiply p. - * @return k * p - */ - public static ECPoint.F2m multiplyRTnaf(ECPoint.F2m p, BigInteger k) - { - ECCurve.F2m curve = (ECCurve.F2m) p.getCurve(); - int m = curve.getM(); - byte a = (byte) curve.getA().toBigInteger().intValue(); - byte mu = curve.getMu(); - BigInteger[] s = curve.getSi(); - ZTauElement rho = partModReduction(k, m, a, s, mu, (byte)10); - - return multiplyTnaf(p, rho); - } - - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by an element λ of Z[τ] - * using the τ-adic NAF (TNAF) method. - * @param p The ECPoint.F2m to multiply. - * @param lambda The element λ of - * Z[τ]. - * @return λ * p - */ - public static ECPoint.F2m multiplyTnaf(ECPoint.F2m p, ZTauElement lambda) - { - ECCurve.F2m curve = (ECCurve.F2m)p.getCurve(); - byte mu = curve.getMu(); - byte[] u = tauAdicNaf(mu, lambda); - - ECPoint.F2m q = multiplyFromTnaf(p, u); - - return q; - } - - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by an element λ of Z[τ] - * using the τ-adic NAF (TNAF) method, given the TNAF - * of λ. - * @param p The ECPoint.F2m to multiply. - * @param u The the TNAF of λ.. - * @return λ * p - */ - public static ECPoint.F2m multiplyFromTnaf(ECPoint.F2m p, byte[] u) - { - ECCurve.F2m curve = (ECCurve.F2m)p.getCurve(); - ECPoint.F2m q = (ECPoint.F2m) curve.getInfinity(); - for (int i = u.length - 1; i >= 0; i--) - { - q = tau(q); - if (u[i] == 1) - { - q = (ECPoint.F2m)q.addSimple(p); - } - else if (u[i] == -1) - { - q = (ECPoint.F2m)q.subtractSimple(p); - } - } - return q; - } - - /** - * Computes the [τ]-adic window NAF of an element - * λ of Z[τ]. - * @param mu The parameter μ of the elliptic curve. - * @param lambda The element λ of - * Z[τ] of which to compute the - * [τ]-adic NAF. - * @param width The window width of the resulting WNAF. - * @param pow2w 2width. - * @param tw The auxiliary value tw. - * @param alpha The αu's for the window width. - * @return The [τ]-adic window NAF of - * λ. - */ - public static byte[] tauAdicWNaf(byte mu, ZTauElement lambda, - byte width, BigInteger pow2w, BigInteger tw, ZTauElement[] alpha) - { - if (!((mu == 1) || (mu == -1))) - { - throw new IllegalArgumentException("mu must be 1 or -1"); - } - - BigInteger norm = norm(mu, lambda); - - // Ceiling of log2 of the norm - int log2Norm = norm.bitLength(); - - // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52 - int maxLength = log2Norm > 30 ? log2Norm + 4 + width : 34 + width; - - // The array holding the TNAF - byte[] u = new byte[maxLength]; - - // 2^(width - 1) - BigInteger pow2wMin1 = pow2w.shiftRight(1); - - // Split lambda into two BigIntegers to simplify calculations - BigInteger r0 = lambda.u; - BigInteger r1 = lambda.v; - int i = 0; - - // while lambda <> (0, 0) - while (!((r0.equals(ECConstants.ZERO))&&(r1.equals(ECConstants.ZERO)))) - { - // if r0 is odd - if (r0.testBit(0)) - { - // uUnMod = r0 + r1*tw mod 2^width - BigInteger uUnMod - = r0.add(r1.multiply(tw)).mod(pow2w); - - byte uLocal; - // if uUnMod >= 2^(width - 1) - if (uUnMod.compareTo(pow2wMin1) >= 0) - { - uLocal = (byte) uUnMod.subtract(pow2w).intValue(); - } - else - { - uLocal = (byte) uUnMod.intValue(); - } - // uLocal is now in [-2^(width-1), 2^(width-1)-1] - - u[i] = uLocal; - boolean s = true; - if (uLocal < 0) - { - s = false; - uLocal = (byte)-uLocal; - } - // uLocal is now >= 0 - - if (s) - { - r0 = r0.subtract(alpha[uLocal].u); - r1 = r1.subtract(alpha[uLocal].v); - } - else - { - r0 = r0.add(alpha[uLocal].u); - r1 = r1.add(alpha[uLocal].v); - } - } - else - { - u[i] = 0; - } - - BigInteger t = r0; - - if (mu == 1) - { - r0 = r1.add(r0.shiftRight(1)); - } - else - { - // mu == -1 - r0 = r1.subtract(r0.shiftRight(1)); - } - r1 = t.shiftRight(1).negate(); - i++; - } - return u; - } - - /** - * Does the precomputation for WTNAF multiplication. - * @param p The ECPoint for which to do the precomputation. - * @param a The parameter a of the elliptic curve. - * @return The precomputation array for p. - */ - public static ECPoint.F2m[] getPreComp(ECPoint.F2m p, byte a) - { - ECPoint.F2m[] pu; - pu = new ECPoint.F2m[16]; - pu[1] = p; - byte[][] alphaTnaf; - if (a == 0) - { - alphaTnaf = Tnaf.alpha0Tnaf; - } - else - { - // a == 1 - alphaTnaf = Tnaf.alpha1Tnaf; - } - - int precompLen = alphaTnaf.length; - for (int i = 3; i < precompLen; i = i + 2) - { - pu[i] = Tnaf.multiplyFromTnaf(p, alphaTnaf[i]); - } - - return pu; - } -} diff --git a/src/org/bouncycastle/math/ec/WNafMultiplier.java b/src/org/bouncycastle/math/ec/WNafMultiplier.java deleted file mode 100644 index 10c8ed24fb..0000000000 --- a/src/org/bouncycastle/math/ec/WNafMultiplier.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class implementing the WNAF (Window Non-Adjacent Form) multiplication - * algorithm. - */ -class WNafMultiplier implements ECMultiplier -{ - /** - * Computes the Window NAF (non-adjacent Form) of an integer. - * @param width The width w of the Window NAF. The width is - * defined as the minimal number w, such that for any - * w consecutive digits in the resulting representation, at - * most one is non-zero. - * @param k The integer of which the Window NAF is computed. - * @return The Window NAF of the given width, such that the following holds: - * k = ∑i=0l-1 ki2i - * , where the ki denote the elements of the - * returned byte[]. - */ - public byte[] windowNaf(byte width, BigInteger k) - { - // The window NAF is at most 1 element longer than the binary - // representation of the integer k. byte can be used instead of short or - // int unless the window width is larger than 8. For larger width use - // short or int. However, a width of more than 8 is not efficient for - // m = log2(q) smaller than 2305 Bits. Note: Values for m larger than - // 1000 Bits are currently not used in practice. - byte[] wnaf = new byte[k.bitLength() + 1]; - - // 2^width as short and BigInteger - short pow2wB = (short)(1 << width); - BigInteger pow2wBI = BigInteger.valueOf(pow2wB); - - int i = 0; - - // The actual length of the WNAF - int length = 0; - - // while k >= 1 - while (k.signum() > 0) - { - // if k is odd - if (k.testBit(0)) - { - // k mod 2^width - BigInteger remainder = k.mod(pow2wBI); - - // if remainder > 2^(width - 1) - 1 - if (remainder.testBit(width - 1)) - { - wnaf[i] = (byte)(remainder.intValue() - pow2wB); - } - else - { - wnaf[i] = (byte)remainder.intValue(); - } - // wnaf[i] is now in [-2^(width-1), 2^(width-1)-1] - - k = k.subtract(BigInteger.valueOf(wnaf[i])); - length = i; - } - else - { - wnaf[i] = 0; - } - - // k = k/2 - k = k.shiftRight(1); - i++; - } - - length++; - - // Reduce the WNAF array to its actual length - byte[] wnafShort = new byte[length]; - System.arraycopy(wnaf, 0, wnafShort, 0, length); - return wnafShort; - } - - /** - * Multiplies this by an integer k using the - * Window NAF method. - * @param k The integer by which this is multiplied. - * @return A new ECPoint which equals this - * multiplied by k. - */ - public ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) - { - WNafPreCompInfo wnafPreCompInfo; - - if ((preCompInfo != null) && (preCompInfo instanceof WNafPreCompInfo)) - { - wnafPreCompInfo = (WNafPreCompInfo)preCompInfo; - } - else - { - // Ignore empty PreCompInfo or PreCompInfo of incorrect type - wnafPreCompInfo = new WNafPreCompInfo(); - } - - // floor(log2(k)) - int m = k.bitLength(); - - // width of the Window NAF - byte width; - - // Required length of precomputation array - int reqPreCompLen; - - // Determine optimal width and corresponding length of precomputation - // array based on literature values - if (m < 13) - { - width = 2; - reqPreCompLen = 1; - } - else - { - if (m < 41) - { - width = 3; - reqPreCompLen = 2; - } - else - { - if (m < 121) - { - width = 4; - reqPreCompLen = 4; - } - else - { - if (m < 337) - { - width = 5; - reqPreCompLen = 8; - } - else - { - if (m < 897) - { - width = 6; - reqPreCompLen = 16; - } - else - { - if (m < 2305) - { - width = 7; - reqPreCompLen = 32; - } - else - { - width = 8; - reqPreCompLen = 127; - } - } - } - } - } - } - - // The length of the precomputation array - int preCompLen = 1; - - ECPoint[] preComp = wnafPreCompInfo.getPreComp(); - ECPoint twiceP = wnafPreCompInfo.getTwiceP(); - - // Check if the precomputed ECPoints already exist - if (preComp == null) - { - // Precomputation must be performed from scratch, create an empty - // precomputation array of desired length - preComp = new ECPoint[]{ p }; - } - else - { - // Take the already precomputed ECPoints to start with - preCompLen = preComp.length; - } - - if (twiceP == null) - { - // Compute twice(p) - twiceP = p.twice(); - } - - if (preCompLen < reqPreCompLen) - { - // Precomputation array must be made bigger, copy existing preComp - // array into the larger new preComp array - ECPoint[] oldPreComp = preComp; - preComp = new ECPoint[reqPreCompLen]; - System.arraycopy(oldPreComp, 0, preComp, 0, preCompLen); - - for (int i = preCompLen; i < reqPreCompLen; i++) - { - // Compute the new ECPoints for the precomputation array. - // The values 1, 3, 5, ..., 2^(width-1)-1 times p are - // computed - preComp[i] = twiceP.add(preComp[i - 1]); - } - } - - // Compute the Window NAF of the desired width - byte[] wnaf = windowNaf(width, k); - int l = wnaf.length; - - // Apply the Window NAF to p using the precomputed ECPoint values. - ECPoint q = p.getCurve().getInfinity(); - for (int i = l - 1; i >= 0; i--) - { - q = q.twice(); - - if (wnaf[i] != 0) - { - if (wnaf[i] > 0) - { - q = q.add(preComp[(wnaf[i] - 1)/2]); - } - else - { - // wnaf[i] < 0 - q = q.subtract(preComp[(-wnaf[i] - 1)/2]); - } - } - } - - // Set PreCompInfo in ECPoint, such that it is available for next - // multiplication. - wnafPreCompInfo.setPreComp(preComp); - wnafPreCompInfo.setTwiceP(twiceP); - p.setPreCompInfo(wnafPreCompInfo); - return q; - } - -} diff --git a/src/org/bouncycastle/math/ec/WNafPreCompInfo.java b/src/org/bouncycastle/math/ec/WNafPreCompInfo.java deleted file mode 100644 index fc0d5fe916..0000000000 --- a/src/org/bouncycastle/math/ec/WNafPreCompInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bouncycastle.math.ec; - -/** - * Class holding precomputation data for the WNAF (Window Non-Adjacent Form) - * algorithm. - */ -class WNafPreCompInfo implements PreCompInfo -{ - /** - * Array holding the precomputed ECPoints used for the Window - * NAF multiplication in - * {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply() - * WNafMultiplier.multiply()}. - */ - private ECPoint[] preComp = null; - - /** - * Holds an ECPoint representing twice(this). Used for the - * Window NAF multiplication in - * {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply() - * WNafMultiplier.multiply()}. - */ - private ECPoint twiceP = null; - - protected ECPoint[] getPreComp() - { - return preComp; - } - - protected void setPreComp(ECPoint[] preComp) - { - this.preComp = preComp; - } - - protected ECPoint getTwiceP() - { - return twiceP; - } - - protected void setTwiceP(ECPoint twiceThis) - { - this.twiceP = twiceThis; - } -} diff --git a/src/org/bouncycastle/math/ec/WTauNafMultiplier.java b/src/org/bouncycastle/math/ec/WTauNafMultiplier.java deleted file mode 100644 index 2353979eb8..0000000000 --- a/src/org/bouncycastle/math/ec/WTauNafMultiplier.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class implementing the WTNAF (Window - * τ-adic Non-Adjacent Form) algorithm. - */ -class WTauNafMultiplier implements ECMultiplier -{ - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by k using the reduced τ-adic NAF (RTNAF) - * method. - * @param p The ECPoint.F2m to multiply. - * @param k The integer by which to multiply k. - * @return p multiplied by k. - */ - public ECPoint multiply(ECPoint point, BigInteger k, PreCompInfo preCompInfo) - { - if (!(point instanceof ECPoint.F2m)) - { - throw new IllegalArgumentException("Only ECPoint.F2m can be " + - "used in WTauNafMultiplier"); - } - - ECPoint.F2m p = (ECPoint.F2m)point; - - ECCurve.F2m curve = (ECCurve.F2m) p.getCurve(); - int m = curve.getM(); - byte a = curve.getA().toBigInteger().byteValue(); - byte mu = curve.getMu(); - BigInteger[] s = curve.getSi(); - - ZTauElement rho = Tnaf.partModReduction(k, m, a, s, mu, (byte)10); - - return multiplyWTnaf(p, rho, preCompInfo, a, mu); - } - - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by an element λ of Z[τ] using - * the τ-adic NAF (TNAF) method. - * @param p The ECPoint.F2m to multiply. - * @param lambda The element λ of - * Z[τ] of which to compute the - * [τ]-adic NAF. - * @return p multiplied by λ. - */ - private ECPoint.F2m multiplyWTnaf(ECPoint.F2m p, ZTauElement lambda, - PreCompInfo preCompInfo, byte a, byte mu) - { - ZTauElement[] alpha; - if (a == 0) - { - alpha = Tnaf.alpha0; - } - else - { - // a == 1 - alpha = Tnaf.alpha1; - } - - BigInteger tw = Tnaf.getTw(mu, Tnaf.WIDTH); - - byte[]u = Tnaf.tauAdicWNaf(mu, lambda, Tnaf.WIDTH, - BigInteger.valueOf(Tnaf.POW_2_WIDTH), tw, alpha); - - return multiplyFromWTnaf(p, u, preCompInfo); - } - - /** - * Multiplies a {@link org.bouncycastle.math.ec.ECPoint.F2m ECPoint.F2m} - * by an element λ of Z[τ] - * using the window τ-adic NAF (TNAF) method, given the - * WTNAF of λ. - * @param p The ECPoint.F2m to multiply. - * @param u The the WTNAF of λ.. - * @return λ * p - */ - private static ECPoint.F2m multiplyFromWTnaf(ECPoint.F2m p, byte[] u, - PreCompInfo preCompInfo) - { - ECCurve.F2m curve = (ECCurve.F2m)p.getCurve(); - byte a = curve.getA().toBigInteger().byteValue(); - - ECPoint.F2m[] pu; - if ((preCompInfo == null) || !(preCompInfo instanceof WTauNafPreCompInfo)) - { - pu = Tnaf.getPreComp(p, a); - p.setPreCompInfo(new WTauNafPreCompInfo(pu)); - } - else - { - pu = ((WTauNafPreCompInfo)preCompInfo).getPreComp(); - } - - // q = infinity - ECPoint.F2m q = (ECPoint.F2m) p.getCurve().getInfinity(); - for (int i = u.length - 1; i >= 0; i--) - { - q = Tnaf.tau(q); - if (u[i] != 0) - { - if (u[i] > 0) - { - q = q.addSimple(pu[u[i]]); - } - else - { - // u[i] < 0 - q = q.subtractSimple(pu[-u[i]]); - } - } - } - - return q; - } -} diff --git a/src/org/bouncycastle/math/ec/WTauNafPreCompInfo.java b/src/org/bouncycastle/math/ec/WTauNafPreCompInfo.java deleted file mode 100644 index d7c583f1de..0000000000 --- a/src/org/bouncycastle/math/ec/WTauNafPreCompInfo.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bouncycastle.math.ec; - -/** - * Class holding precomputation data for the WTNAF (Window - * τ-adic Non-Adjacent Form) algorithm. - */ -class WTauNafPreCompInfo implements PreCompInfo -{ - /** - * Array holding the precomputed ECPoint.F2ms used for the - * WTNAF multiplication in - * {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() - * WTauNafMultiplier.multiply()}. - */ - private ECPoint.F2m[] preComp = null; - - /** - * Constructor for WTauNafPreCompInfo - * @param preComp Array holding the precomputed ECPoint.F2ms - * used for the WTNAF multiplication in - * {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() - * WTauNafMultiplier.multiply()}. - */ - WTauNafPreCompInfo(ECPoint.F2m[] preComp) - { - this.preComp = preComp; - } - - /** - * @return the array holding the precomputed ECPoint.F2ms - * used for the WTNAF multiplication in - * {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() - * WTauNafMultiplier.multiply()}. - */ - protected ECPoint.F2m[] getPreComp() - { - return preComp; - } -} diff --git a/src/org/bouncycastle/math/ec/ZTauElement.java b/src/org/bouncycastle/math/ec/ZTauElement.java deleted file mode 100644 index 7402f222f9..0000000000 --- a/src/org/bouncycastle/math/ec/ZTauElement.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bouncycastle.math.ec; - -import java.math.BigInteger; - -/** - * Class representing an element of Z[τ]. Let - * λ be an element of Z[τ]. Then - * λ is given as λ = u + vτ. The - * components u and v may be used directly, there - * are no accessor methods. - * Immutable class. - */ -class ZTauElement -{ - /** - * The "real" part of λ. - */ - public final BigInteger u; - - /** - * The "τ-adic" part of λ. - */ - public final BigInteger v; - - /** - * Constructor for an element λ of - * Z[τ]. - * @param u The "real" part of λ. - * @param v The "τ-adic" part of - * λ. - */ - public ZTauElement(BigInteger u, BigInteger v) - { - this.u = u; - this.v = v; - } -} diff --git a/src/org/bouncycastle/math/ec/package.html b/src/org/bouncycastle/math/ec/package.html deleted file mode 100644 index a02605ba3c..0000000000 --- a/src/org/bouncycastle/math/ec/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -Math support for Elliptic Curve. - - diff --git a/src/org/bouncycastle/util/Arrays.java b/src/org/bouncycastle/util/Arrays.java deleted file mode 100644 index 07ae4e3b30..0000000000 --- a/src/org/bouncycastle/util/Arrays.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.bouncycastle.util; - -/** - * General array utilities. - */ -public final class Arrays -{ - private Arrays() - { - // static class, hide constructor - } - - public static boolean areEqual( - boolean[] a, - boolean[] b) - { - if (a == b) - { - return true; - } - - if (a == null || b == null) - { - return false; - } - - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - public static boolean areEqual( - byte[] a, - byte[] b) - { - if (a == b) - { - return true; - } - - if (a == null || b == null) - { - return false; - } - - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - public static boolean areEqual( - int[] a, - int[] b) - { - if (a == b) - { - return true; - } - - if (a == null || b == null) - { - return false; - } - - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - public static void fill( - byte[] array, - byte value) - { - for (int i = 0; i < array.length; i++) - { - array[i] = value; - } - } - - public static void fill( - long[] array, - long value) - { - for (int i = 0; i < array.length; i++) - { - array[i] = value; - } - } - - public static void fill( - short[] array, - short value) - { - for (int i = 0; i < array.length; i++) - { - array[i] = value; - } - } - - public static int hashCode(byte[] data) - { - if (data == null) - { - return 0; - } - - int i = data.length; - int hc = i + 1; - - while (--i >= 0) - { - hc *= 257; - hc ^= data[i]; - } - - return hc; - } - - public static byte[] clone(byte[] data) - { - if (data == null) - { - return null; - } - byte[] copy = new byte[data.length]; - - System.arraycopy(data, 0, copy, 0, data.length); - - return copy; - } - - public static int[] clone(int[] data) - { - if (data == null) - { - return null; - } - int[] copy = new int[data.length]; - - System.arraycopy(data, 0, copy, 0, data.length); - - return copy; - } -} diff --git a/src/org/bouncycastle/util/Strings.java b/src/org/bouncycastle/util/Strings.java deleted file mode 100644 index e69eade27a..0000000000 --- a/src/org/bouncycastle/util/Strings.java +++ /dev/null @@ -1,246 +0,0 @@ -package org.bouncycastle.util; - -import java.io.ByteArrayOutputStream; -import java.util.Vector; - -public final class Strings -{ - public static String fromUTF8ByteArray(byte[] bytes) - { - int i = 0; - int length = 0; - - while (i < bytes.length) - { - length++; - if ((bytes[i] & 0xf0) == 0xf0) - { - // surrogate pair - length++; - i += 4; - } - else if ((bytes[i] & 0xe0) == 0xe0) - { - i += 3; - } - else if ((bytes[i] & 0xc0) == 0xc0) - { - i += 2; - } - else - { - i += 1; - } - } - - char[] cs = new char[length]; - - i = 0; - length = 0; - - while (i < bytes.length) - { - char ch; - - if ((bytes[i] & 0xf0) == 0xf0) - { - int codePoint = ((bytes[i] & 0x03) << 18) | ((bytes[i+1] & 0x3F) << 12) | ((bytes[i+2] & 0x3F) << 6) | (bytes[i+3] & 0x3F); - int U = codePoint - 0x10000; - char W1 = (char)(0xD800 | (U >> 10)); - char W2 = (char)(0xDC00 | (U & 0x3FF)); - cs[length++] = W1; - ch = W2; - i += 4; - } - else if ((bytes[i] & 0xe0) == 0xe0) - { - ch = (char)(((bytes[i] & 0x0f) << 12) - | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)); - i += 3; - } - else if ((bytes[i] & 0xd0) == 0xd0) - { - ch = (char)(((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f)); - i += 2; - } - else if ((bytes[i] & 0xc0) == 0xc0) - { - ch = (char)(((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f)); - i += 2; - } - else - { - ch = (char)(bytes[i] & 0xff); - i += 1; - } - - cs[length++] = ch; - } - - return new String(cs); - } - - public static byte[] toUTF8ByteArray(String string) - { - return toUTF8ByteArray(string.toCharArray()); - } - - public static byte[] toUTF8ByteArray(char[] string) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - char[] c = string; - int i = 0; - - while (i < c.length) - { - char ch = c[i]; - - if (ch < 0x0080) - { - bOut.write(ch); - } - else if (ch < 0x0800) - { - bOut.write(0xc0 | (ch >> 6)); - bOut.write(0x80 | (ch & 0x3f)); - } - // surrogate pair - else if (ch >= 0xD800 && ch <= 0xDFFF) - { - // in error - can only happen, if the Java String class has a - // bug. - if (i + 1 >= c.length) - { - throw new IllegalStateException("invalid UTF-16 codepoint"); - } - char W1 = ch; - ch = c[++i]; - char W2 = ch; - // in error - can only happen, if the Java String class has a - // bug. - if (W1 > 0xDBFF) - { - throw new IllegalStateException("invalid UTF-16 codepoint"); - } - int codePoint = (((W1 & 0x03FF) << 10) | (W2 & 0x03FF)) + 0x10000; - bOut.write(0xf0 | (codePoint >> 18)); - bOut.write(0x80 | ((codePoint >> 12) & 0x3F)); - bOut.write(0x80 | ((codePoint >> 6) & 0x3F)); - bOut.write(0x80 | (codePoint & 0x3F)); - } - else - { - bOut.write(0xe0 | (ch >> 12)); - bOut.write(0x80 | ((ch >> 6) & 0x3F)); - bOut.write(0x80 | (ch & 0x3F)); - } - - i++; - } - - return bOut.toByteArray(); - } - - /** - * A locale independent version of toUpperCase. - * - * @param string input to be converted - * @return a US Ascii uppercase version - */ - public static String toUpperCase(String string) - { - boolean changed = false; - char[] chars = string.toCharArray(); - - for (int i = 0; i != chars.length; i++) - { - char ch = chars[i]; - if ('a' <= ch && 'z' >= ch) - { - changed = true; - chars[i] = (char)(ch - 'a' + 'A'); - } - } - - if (changed) - { - return new String(chars); - } - - return string; - } - - /** - * A locale independent version of toLowerCase. - * - * @param string input to be converted - * @return a US ASCII lowercase version - */ - public static String toLowerCase(String string) - { - boolean changed = false; - char[] chars = string.toCharArray(); - - for (int i = 0; i != chars.length; i++) - { - char ch = chars[i]; - if ('A' <= ch && 'Z' >= ch) - { - changed = true; - chars[i] = (char)(ch - 'A' + 'a'); - } - } - - if (changed) - { - return new String(chars); - } - - return string; - } - - public static byte[] toByteArray(String string) - { - byte[] bytes = new byte[string.length()]; - - for (int i = 0; i != bytes.length; i++) - { - char ch = string.charAt(i); - - bytes[i] = (byte)ch; - } - - return bytes; - } - - public static String[] split(String input, char delimiter) - { - Vector v = new Vector(); - boolean moreTokens = true; - String subString; - - while (moreTokens) - { - int tokenLocation = input.indexOf(delimiter); - if (tokenLocation > 0) - { - subString = input.substring(0, tokenLocation); - v.addElement(subString); - input = input.substring(tokenLocation + 1); - } - else - { - moreTokens = false; - v.addElement(input); - } - } - - String[] res = new String[v.size()]; - - for (int i = 0; i != res.length; i++) - { - res[i] = (String)v.elementAt(i); - } - return res; - } -} diff --git a/src/org/bouncycastle/util/encoders/Encoder.java b/src/org/bouncycastle/util/encoders/Encoder.java deleted file mode 100644 index b066121053..0000000000 --- a/src/org/bouncycastle/util/encoders/Encoder.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bouncycastle.util.encoders; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Encode and decode byte arrays (typically from binary to 7-bit ASCII - * encodings). - */ -public interface Encoder -{ - int encode(byte[] data, int off, int length, OutputStream out) throws IOException; - - int decode(byte[] data, int off, int length, OutputStream out) throws IOException; - - int decode(String data, OutputStream out) throws IOException; -} diff --git a/src/org/bouncycastle/util/encoders/Hex.java b/src/org/bouncycastle/util/encoders/Hex.java deleted file mode 100644 index d69f7739f1..0000000000 --- a/src/org/bouncycastle/util/encoders/Hex.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bouncycastle.util.encoders; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class Hex -{ - private static final Encoder encoder = new HexEncoder(); - - /** - * encode the input data producing a Hex encoded byte array. - * - * @return a byte array containing the Hex encoded data. - */ - public static byte[] encode( - byte[] data) - { - return encode(data, 0, data.length); - } - - /** - * encode the input data producing a Hex encoded byte array. - * - * @return a byte array containing the Hex encoded data. - */ - public static byte[] encode( - byte[] data, - int off, - int length) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - try - { - encoder.encode(data, off, length, bOut); - } - catch (IOException e) - { - throw new RuntimeException("exception encoding Hex string: " + e); - } - - return bOut.toByteArray(); - } - - /** - * Hex encode the byte data writing it to the given output stream. - * - * @return the number of bytes produced. - */ - public static int encode( - byte[] data, - OutputStream out) - throws IOException - { - return encoder.encode(data, 0, data.length, out); - } - - /** - * Hex encode the byte data writing it to the given output stream. - * - * @return the number of bytes produced. - */ - public static int encode( - byte[] data, - int off, - int length, - OutputStream out) - throws IOException - { - return encoder.encode(data, off, length, out); - } - - /** - * decode the Hex encoded input data. It is assumed the input data is valid. - * - * @return a byte array representing the decoded data. - */ - public static byte[] decode( - byte[] data) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - try - { - encoder.decode(data, 0, data.length, bOut); - } - catch (IOException e) - { - throw new RuntimeException("exception decoding Hex string: " + e); - } - - return bOut.toByteArray(); - } - - /** - * decode the Hex encoded String data - whitespace will be ignored. - * - * @return a byte array representing the decoded data. - */ - public static byte[] decode( - String data) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - try - { - encoder.decode(data, bOut); - } - catch (IOException e) - { - throw new RuntimeException("exception decoding Hex string: " + e); - } - - return bOut.toByteArray(); - } - - /** - * decode the Hex encoded String data writing it to the given output stream, - * whitespace characters will be ignored. - * - * @return the number of bytes produced. - */ - public static int decode( - String data, - OutputStream out) - throws IOException - { - return encoder.decode(data, out); - } -} diff --git a/src/org/bouncycastle/util/encoders/HexEncoder.java b/src/org/bouncycastle/util/encoders/HexEncoder.java deleted file mode 100644 index 0dcae29172..0000000000 --- a/src/org/bouncycastle/util/encoders/HexEncoder.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.bouncycastle.util.encoders; - -import java.io.IOException; -import java.io.OutputStream; - -public class HexEncoder - implements Encoder -{ - protected final byte[] encodingTable = - { - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', - (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' - }; - - /* - * set up the decoding table. - */ - protected final byte[] decodingTable = new byte[128]; - - protected void initialiseDecodingTable() - { - for (int i = 0; i < encodingTable.length; i++) - { - decodingTable[encodingTable[i]] = (byte)i; - } - - decodingTable['A'] = decodingTable['a']; - decodingTable['B'] = decodingTable['b']; - decodingTable['C'] = decodingTable['c']; - decodingTable['D'] = decodingTable['d']; - decodingTable['E'] = decodingTable['e']; - decodingTable['F'] = decodingTable['f']; - } - - public HexEncoder() - { - initialiseDecodingTable(); - } - - /** - * encode the input data producing a Hex output stream. - * - * @return the number of bytes produced. - */ - public int encode( - byte[] data, - int off, - int length, - OutputStream out) - throws IOException - { - for (int i = off; i < (off + length); i++) - { - int v = data[i] & 0xff; - - out.write(encodingTable[(v >>> 4)]); - out.write(encodingTable[v & 0xf]); - } - - return length * 2; - } - - private boolean ignore( - char c) - { - return (c == '\n' || c =='\r' || c == '\t' || c == ' '); - } - - /** - * decode the Hex encoded byte data writing it to the given output stream, - * whitespace characters will be ignored. - * - * @return the number of bytes produced. - */ - public int decode( - byte[] data, - int off, - int length, - OutputStream out) - throws IOException - { - byte b1, b2; - int outLen = 0; - - int end = off + length; - - while (end > off) - { - if (!ignore((char)data[end - 1])) - { - break; - } - - end--; - } - - int i = off; - while (i < end) - { - while (i < end && ignore((char)data[i])) - { - i++; - } - - b1 = decodingTable[data[i++]]; - - while (i < end && ignore((char)data[i])) - { - i++; - } - - b2 = decodingTable[data[i++]]; - - out.write((b1 << 4) | b2); - - outLen++; - } - - return outLen; - } - - /** - * decode the Hex encoded String data writing it to the given output stream, - * whitespace characters will be ignored. - * - * @return the number of bytes produced. - */ - public int decode( - String data, - OutputStream out) - throws IOException - { - byte b1, b2; - int length = 0; - - int end = data.length(); - - while (end > 0) - { - if (!ignore(data.charAt(end - 1))) - { - break; - } - - end--; - } - - int i = 0; - while (i < end) - { - while (i < end && ignore(data.charAt(i))) - { - i++; - } - - b1 = decodingTable[data.charAt(i++)]; - - while (i < end && ignore(data.charAt(i))) - { - i++; - } - - b2 = decodingTable[data.charAt(i++)]; - - out.write((b1 << 4) | b2); - - length++; - } - - return length; - } -} diff --git a/src/org/bouncycastle/util/io/StreamOverflowException.java b/src/org/bouncycastle/util/io/StreamOverflowException.java deleted file mode 100644 index 01af8da90b..0000000000 --- a/src/org/bouncycastle/util/io/StreamOverflowException.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bouncycastle.util.io; - -import java.io.IOException; - -public class StreamOverflowException - extends IOException -{ - public StreamOverflowException(String msg) - { - super(msg); - } -} diff --git a/src/org/bouncycastle/util/io/Streams.java b/src/org/bouncycastle/util/io/Streams.java deleted file mode 100644 index 9ceabfb5d3..0000000000 --- a/src/org/bouncycastle/util/io/Streams.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bouncycastle.util.io; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -public final class Streams -{ - private static int BUFFER_SIZE = 512; - - public static void drain(InputStream inStr) - throws IOException - { - byte[] bs = new byte[BUFFER_SIZE]; - while (inStr.read(bs, 0, bs.length) >= 0) - { - } - } - - public static byte[] readAll(InputStream inStr) - throws IOException - { - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - pipeAll(inStr, buf); - return buf.toByteArray(); - } - - public static byte[] readAllLimited(InputStream inStr, int limit) - throws IOException - { - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - pipeAllLimited(inStr, limit, buf); - return buf.toByteArray(); - } - - public static int readFully(InputStream inStr, byte[] buf) - throws IOException - { - return readFully(inStr, buf, 0, buf.length); - } - - public static int readFully(InputStream inStr, byte[] buf, int off, int len) - throws IOException - { - int totalRead = 0; - while (totalRead < len) - { - int numRead = inStr.read(buf, off + totalRead, len - totalRead); - if (numRead < 0) - { - break; - } - totalRead += numRead; - } - return totalRead; - } - - public static void pipeAll(InputStream inStr, OutputStream outStr) - throws IOException - { - byte[] bs = new byte[BUFFER_SIZE]; - int numRead; - while ((numRead = inStr.read(bs, 0, bs.length)) >= 0) - { - outStr.write(bs, 0, numRead); - } - } - - public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr) - throws IOException - { - long total = 0; - byte[] bs = new byte[BUFFER_SIZE]; - int numRead; - while ((numRead = inStr.read(bs, 0, bs.length)) >= 0) - { - total += numRead; - if (total > limit) - throw new StreamOverflowException("Data Overflow"); - outStr.write(bs, 0, numRead); - } - return total; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1ApplicationSpecificParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1ApplicationSpecificParser.java deleted file mode 100644 index bcd8a1d8ee..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1ApplicationSpecificParser.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public interface ASN1ApplicationSpecificParser - extends DEREncodable -{ - DEREncodable readObject() - throws IOException; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Choice.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Choice.java deleted file mode 100644 index c3abdc5509..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Choice.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -/** - * Marker interface for CHOICE objects - if you implement this in a role your - * own object any attempt to tag the object implicitly will convert the tag to - * an explicit one as the encoding rules require. - *

- * If you use this interface your class should also implement the getInstance - * pattern which takes a tag object and the tagging mode used. - */ -public interface ASN1Choice -{ - // marker interface -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Encodable.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Encodable.java deleted file mode 100644 index cb755691f8..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Encodable.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * Base class for objects which can be written directly to ASN.1 output streams. - */ -public abstract class ASN1Encodable - implements DEREncodable -{ - public static final String DER = "DER"; - public static final String BER = "BER"; - - /** - * Return the default BER or DER encoding for this object. - * - * @return BER/DER byte encoded object. - * @throws IOException on encoding error. - */ - public byte[] getEncoded() - throws IOException - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(this); - - return bOut.toByteArray(); - } - - /** - * Return either the default for "BER" or a DER encoding if "DER" is specified. - * - * @param encoding name of encoding to use. - * @return byte encoded object. - * @throws IOException on encoding error. - */ - public byte[] getEncoded( - String encoding) - throws IOException - { - if (encoding.equals(DER)) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - dOut.writeObject(this); - - return bOut.toByteArray(); - } - - return this.getEncoded(); - } - - /** - * Return the DER encoding of the object, null if the DER encoding can not be made. - * - * @return a DER byte array, null otherwise. - */ - public byte[] getDEREncoded() - { - try - { - return this.getEncoded(DER); - } - catch (IOException e) - { - return null; - } - } - - public int hashCode() - { - return this.toASN1Object().hashCode(); - } - - public boolean equals( - Object o) - { - if (this == o) - { - return true; - } - - if (!(o instanceof DEREncodable)) - { - return false; - } - - DEREncodable other = (DEREncodable)o; - - return this.toASN1Object().equals(other.getDERObject()); - } - - public DERObject getDERObject() - { - return this.toASN1Object(); - } - - public abstract DERObject toASN1Object(); -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1EncodableVector.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1EncodableVector.java deleted file mode 100644 index 5b5271339a..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1EncodableVector.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -/** - * the parent class for this will eventually disappear. Use this one! - */ -public class ASN1EncodableVector - extends DEREncodableVector -{ - // migrating from DEREncodeableVector - public ASN1EncodableVector() - { - - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1InputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1InputStream.java deleted file mode 100644 index 91d8b9d439..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1InputStream.java +++ /dev/null @@ -1,382 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.bouncycastle.util.io.Streams; - -/** - * a general purpose ASN.1 decoder - note: this class differs from the - * others in that it returns null after it has read the last object in - * the stream. If an ASN.1 NULL is encountered a DER/BER Null object is - * returned. - */ -public class ASN1InputStream - extends FilterInputStream - implements DERTags -{ - private final int limit; - private final boolean lazyEvaluate; - - public ASN1InputStream( - InputStream is) - { - this(is, Integer.MAX_VALUE); - } - - /** - * Create an ASN1InputStream based on the input byte array. The length of DER objects in - * the stream is automatically limited to the length of the input array. - * - * @param input array containing ASN.1 encoded data. - */ - public ASN1InputStream( - byte[] input) - { - this(new ByteArrayInputStream(input), input.length); - } - - /** - * Create an ASN1InputStream based on the input byte array. The length of DER objects in - * the stream is automatically limited to the length of the input array. - * - * @param input array containing ASN.1 encoded data. - * @param lazyEvaluate true if parsing inside constructed objects can be delayed. - */ - public ASN1InputStream( - byte[] input, - boolean lazyEvaluate) - { - this(new ByteArrayInputStream(input), input.length, lazyEvaluate); - } - - /** - * Create an ASN1InputStream where no DER object will be longer than limit. - * - * @param input stream containing ASN.1 encoded data. - * @param limit maximum size of a DER encoded object. - */ - public ASN1InputStream( - InputStream input, - int limit) - { - this(input, limit, false); - } - - /** - * Create an ASN1InputStream where no DER object will be longer than limit, and constructed - * objects such as sequences will be parsed lazily. - * - * @param input stream containing ASN.1 encoded data. - * @param limit maximum size of a DER encoded object. - * @param lazyEvaluate true if parsing inside constructed objects can be delayed. - */ - public ASN1InputStream( - InputStream input, - int limit, - boolean lazyEvaluate) - { - super(input); - this.limit = limit; - this.lazyEvaluate = lazyEvaluate; - } - - protected int readLength() - throws IOException - { - return readLength(this, limit); - } - - protected void readFully( - byte[] bytes) - throws IOException - { - if (Streams.readFully(this, bytes) != bytes.length) - { - throw new EOFException("EOF encountered in middle of object"); - } - } - - /** - * build an object given its tag and the number of bytes to construct it from. - */ - protected DERObject buildObject( - int tag, - int tagNo, - int length) - throws IOException - { - boolean isConstructed = (tag & CONSTRUCTED) != 0; - - DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length); - - if ((tag & APPLICATION) != 0) - { - return new DERApplicationSpecific(isConstructed, tagNo, defIn.toByteArray()); - } - - if ((tag & TAGGED) != 0) - { - return new BERTaggedObjectParser(tag, tagNo, defIn).getDERObject(); - } - - if (isConstructed) - { - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case OCTET_STRING: - // - // yes, people actually do this... - // - return new BERConstructedOctetString(buildDEREncodableVector(defIn).v); - case SEQUENCE: - if (lazyEvaluate) - { - return new LazyDERSequence(defIn.toByteArray()); - } - else - { - return DERFactory.createSequence(buildDEREncodableVector(defIn)); - } - case SET: - return DERFactory.createSet(buildDEREncodableVector(defIn), false); - default: - return new DERUnknownTag(true, tagNo, defIn.toByteArray()); - } - } - - return createPrimitiveDERObject(tagNo, defIn.toByteArray()); - } - - ASN1EncodableVector buildEncodableVector() - throws IOException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - DERObject o; - - while ((o = readObject()) != null) - { - v.add(o); - } - - return v; - } - - ASN1EncodableVector buildDEREncodableVector( - DefiniteLengthInputStream dIn) throws IOException - { - return new ASN1InputStream(dIn).buildEncodableVector(); - } - - public DERObject readObject() - throws IOException - { - int tag = read(); - if (tag <= 0) - { - if (tag == 0) - { - throw new IOException("unexpected end-of-contents marker"); - } - - return null; - } - - // - // calculate tag number - // - int tagNo = readTagNumber(this, tag); - - boolean isConstructed = (tag & CONSTRUCTED) != 0; - - // - // calculate length - // - int length = readLength(); - - if (length < 0) // indefinite length method - { - if (!isConstructed) - { - throw new IOException("indefinite length primitive encoding encountered"); - } - - IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this); - - if ((tag & APPLICATION) != 0) - { - ASN1StreamParser sp = new ASN1StreamParser(indIn); - - return new BERApplicationSpecificParser(tagNo, sp).getDERObject(); - } - if ((tag & TAGGED) != 0) - { - return new BERTaggedObjectParser(tag, tagNo, indIn).getDERObject(); - } - - ASN1StreamParser sp = new ASN1StreamParser(indIn); - - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case OCTET_STRING: - return new BEROctetStringParser(sp).getDERObject(); - case SEQUENCE: - return new BERSequenceParser(sp).getDERObject(); - case SET: - return new BERSetParser(sp).getDERObject(); - default: - throw new IOException("unknown BER object encountered"); - } - } - else - { - return buildObject(tag, tagNo, length); - } - } - - static int readTagNumber(InputStream s, int tag) - throws IOException - { - int tagNo = tag & 0x1f; - - // - // with tagged object tag number is bottom 5 bits, or stored at the start of the content - // - if (tagNo == 0x1f) - { - tagNo = 0; - - int b = s.read(); - - // X.690-0207 8.1.2.4.2 - // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) // Note: -1 will pass - { - throw new IOException("corrupted stream - invalid high tag number found"); - } - - while ((b >= 0) && ((b & 0x80) != 0)) - { - tagNo |= (b & 0x7f); - tagNo <<= 7; - b = s.read(); - } - - if (b < 0) - { - throw new EOFException("EOF found inside tag value."); - } - - tagNo |= (b & 0x7f); - } - - return tagNo; - } - - static int readLength(InputStream s, int limit) - throws IOException - { - int length = s.read(); - if (length < 0) - { - throw new EOFException("EOF found when length expected"); - } - - if (length == 0x80) - { - return -1; // indefinite-length encoding - } - - if (length > 127) - { - int size = length & 0x7f; - - if (size > 4) - { - throw new IOException("DER length more than 4 bytes"); - } - - length = 0; - for (int i = 0; i < size; i++) - { - int next = s.read(); - - if (next < 0) - { - throw new EOFException("EOF found reading length"); - } - - length = (length << 8) + next; - } - - if (length < 0) - { - throw new IOException("corrupted stream - negative length found"); - } - - if (length >= limit) // after all we must have read at least 1 byte - { - throw new IOException("corrupted stream - out of bounds length found"); - } - } - - return length; - } - - static DERObject createPrimitiveDERObject( - int tagNo, - byte[] bytes) - { - switch (tagNo) - { - case BIT_STRING: - { - int padBits = bytes[0]; - byte[] data = new byte[bytes.length - 1]; - System.arraycopy(bytes, 1, data, 0, bytes.length - 1); - return new DERBitString(data, padBits); - } - case BMP_STRING: - return new DERBMPString(bytes); - case BOOLEAN: - return new DERBoolean(bytes); - case ENUMERATED: - return new DEREnumerated(bytes); - case GENERALIZED_TIME: - return new DERGeneralizedTime(bytes); - case GENERAL_STRING: - return new DERGeneralString(bytes); - case IA5_STRING: - return new DERIA5String(bytes); - case INTEGER: - return new DERInteger(bytes); - case NULL: - return DERNull.INSTANCE; // actual content is ignored (enforce 0 length?) - case NUMERIC_STRING: - return new DERNumericString(bytes); - case OBJECT_IDENTIFIER: - return new DERObjectIdentifier(bytes); - case OCTET_STRING: - return new DEROctetString(bytes); - case PRINTABLE_STRING: - return new DERPrintableString(bytes); - case T61_STRING: - return new DERT61String(bytes); - case UNIVERSAL_STRING: - return new DERUniversalString(bytes); - case UTC_TIME: - return new DERUTCTime(bytes); - case UTF8_STRING: - return new DERUTF8String(bytes); - case VISIBLE_STRING: - return new DERVisibleString(bytes); - default: - return new DERUnknownTag(false, tagNo, bytes); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Null.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Null.java deleted file mode 100644 index 6027db614a..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Null.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * A NULL object. - */ -public abstract class ASN1Null - extends ASN1Object -{ - public ASN1Null() - { - } - - public int hashCode() - { - return -1; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof ASN1Null)) - { - return false; - } - - return true; - } - - abstract void encode(DEROutputStream out) - throws IOException; - - public String toString() - { - return "NULL"; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Object.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Object.java deleted file mode 100644 index b0fd8f1e30..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Object.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public abstract class ASN1Object - extends DERObject -{ - /** - * Create a base ASN.1 object from a byte stream. - * - * @param data the byte stream to parse. - * @return the base ASN.1 object represented by the byte stream. - * @exception IOException if there is a problem parsing the data. - */ - public static ASN1Object fromByteArray(byte[] data) - throws IOException - { - ASN1InputStream aIn = new ASN1InputStream(data); - - return (ASN1Object)aIn.readObject(); - } - - public final boolean equals(Object o) - { - if (this == o) - { - return true; - } - - return (o instanceof DEREncodable) && asn1Equals(((DEREncodable)o).getDERObject()); - } - - public abstract int hashCode(); - - abstract void encode(DEROutputStream out) throws IOException; - - abstract boolean asn1Equals(DERObject o); -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1ObjectParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1ObjectParser.java deleted file mode 100644 index 551180549d..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1ObjectParser.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.InputStream; - -/** - * @deprecated will be removed - */ -public class ASN1ObjectParser -{ - ASN1StreamParser _aIn; - - protected ASN1ObjectParser( - int baseTag, - int tagNumber, - InputStream contentStream) - { - _aIn = new ASN1StreamParser(contentStream); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetString.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetString.java deleted file mode 100644 index a4c905a7a9..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetString.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.Arrays; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Vector; - -public abstract class ASN1OctetString - extends ASN1Object - implements ASN1OctetStringParser -{ - byte[] string; - - /** - * return an Octet String from a tagged object. - * - * @param obj the tagged object holding the object we want. - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static ASN1OctetString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * return an Octet String from the given object. - * - * @param obj the object we want converted. - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static ASN1OctetString getInstance( - Object obj) - { - if (obj == null || obj instanceof ASN1OctetString) - { - return (ASN1OctetString)obj; - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - if (obj instanceof ASN1Sequence) - { - Vector v = new Vector(); - Enumeration e = ((ASN1Sequence)obj).getObjects(); - - while (e.hasMoreElements()) - { - v.addElement(e.nextElement()); - } - - return new BERConstructedOctetString(v); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * @param string the octets making up the octet string. - */ - public ASN1OctetString( - byte[] string) - { - if (string == null) - { - throw new NullPointerException("string cannot be null"); - } - this.string = string; - } - - public ASN1OctetString( - DEREncodable obj) - { - try - { - this.string = obj.getDERObject().getEncoded(ASN1Encodable.DER); - } - catch (IOException e) - { - throw new IllegalArgumentException("Error processing object : " + e.toString()); - } - } - - public InputStream getOctetStream() - { - return new ByteArrayInputStream(string); - } - - public ASN1OctetStringParser parser() - { - return this; - } - - public byte[] getOctets() - { - return string; - } - - public int hashCode() - { - return Arrays.hashCode(this.getOctets()); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof ASN1OctetString)) - { - return false; - } - - ASN1OctetString other = (ASN1OctetString)o; - - return Arrays.areEqual(string, other.string); - } - - abstract void encode(DEROutputStream out) - throws IOException; - - public String toString() - { - return "#"+new String(Hex.encode(string)); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetStringParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetStringParser.java deleted file mode 100644 index dbf3d73fb5..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OctetStringParser.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.InputStream; - -public interface ASN1OctetStringParser - extends DEREncodable -{ - public InputStream getOctetStream(); -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OutputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1OutputStream.java deleted file mode 100644 index 17f524dd64..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1OutputStream.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.io.OutputStream; - -public class ASN1OutputStream - extends DEROutputStream -{ - public ASN1OutputStream( - OutputStream os) - { - super(os); - } - - public void writeObject( - Object obj) - throws IOException - { - if (obj == null) - { - writeNull(); - } - else if (obj instanceof DERObject) - { - ((DERObject)obj).encode(this); - } - else if (obj instanceof DEREncodable) - { - ((DEREncodable)obj).getDERObject().encode(this); - } - else - { - throw new IOException("object not ASN1Encodable"); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Sequence.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Sequence.java deleted file mode 100644 index 4c6e845417..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Sequence.java +++ /dev/null @@ -1,217 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Vector; - -public abstract class ASN1Sequence - extends ASN1Object -{ - private Vector seq = new Vector(); - - /** - * return an ASN1Sequence from the given object. - * - * @param obj the object we want converted. - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static ASN1Sequence getInstance( - Object obj) - { - if (obj == null || obj instanceof ASN1Sequence) - { - return (ASN1Sequence)obj; - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - /** - * Return an ASN1 sequence from a tagged object. There is a special - * case here, if an object appears to have been explicitly tagged on - * reading but we were expecting it to be implicitly tagged in the - * normal course of events it indicates that we lost the surrounding - * sequence - so we need to add it back (this will happen if the tagged - * object is a sequence that contains other sequences). If you are - * dealing with implicitly tagged sequences you really should - * be using this method. - * - * @param obj the tagged object. - * @param explicit true if the object is meant to be explicitly tagged, - * false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static ASN1Sequence getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - if (explicit) - { - if (!obj.isExplicit()) - { - throw new IllegalArgumentException("object implicit - explicit expected."); - } - - return (ASN1Sequence)obj.getObject(); - } - else - { - // - // constructed object which appears to be explicitly tagged - // when it should be implicit means we have to add the - // surrounding sequence. - // - if (obj.isExplicit()) - { - if (obj instanceof BERTaggedObject) - { - return new BERSequence(obj.getObject()); - } - else - { - return new DERSequence(obj.getObject()); - } - } - else - { - if (obj.getObject() instanceof ASN1Sequence) - { - return (ASN1Sequence)obj.getObject(); - } - } - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - public Enumeration getObjects() - { - return seq.elements(); - } - - public ASN1SequenceParser parser() - { - final ASN1Sequence outer = this; - - return new ASN1SequenceParser() - { - private final int max = size(); - - private int index; - - public DEREncodable readObject() throws IOException - { - if (index == max) - { - return null; - } - - DEREncodable obj = getObjectAt(index++); - if (obj instanceof ASN1Sequence) - { - return ((ASN1Sequence)obj).parser(); - } - if (obj instanceof ASN1Set) - { - return ((ASN1Set)obj).parser(); - } - - return obj; - } - - public DERObject getDERObject() - { - return outer; - } - }; - } - - /** - * return the object at the sequence position indicated by index. - * - * @param index the sequence number (starting at zero) of the object - * @return the object at the sequence position indicated by index. - */ - public DEREncodable getObjectAt( - int index) - { - return (DEREncodable)seq.elementAt(index); - } - - /** - * return the number of objects in this sequence. - * - * @return the number of objects in this sequence. - */ - public int size() - { - return seq.size(); - } - - public int hashCode() - { - Enumeration e = this.getObjects(); - int hashCode = size(); - - while (e.hasMoreElements()) - { - Object o = e.nextElement(); - hashCode *= 17; - if (o != null) - { - hashCode ^= o.hashCode(); - } - } - - return hashCode; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof ASN1Sequence)) - { - return false; - } - - ASN1Sequence other = (ASN1Sequence)o; - - if (this.size() != other.size()) - { - return false; - } - - Enumeration s1 = this.getObjects(); - Enumeration s2 = other.getObjects(); - - while (s1.hasMoreElements()) - { - DERObject o1 = ((DEREncodable)s1.nextElement()).getDERObject(); - DERObject o2 = ((DEREncodable)s2.nextElement()).getDERObject(); - - if (o1 == o2 || (o1 != null && o1.equals(o2))) - { - continue; - } - - return false; - } - - return true; - } - - protected void addObject( - DEREncodable obj) - { - seq.addElement(obj); - } - - abstract void encode(DEROutputStream out) - throws IOException; - - public String toString() - { - return seq.toString(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1SequenceParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1SequenceParser.java deleted file mode 100644 index d56b39e04e..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1SequenceParser.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public interface ASN1SequenceParser - extends DEREncodable -{ - DEREncodable readObject() - throws IOException; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Set.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1Set.java deleted file mode 100644 index da1ff327f7..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1Set.java +++ /dev/null @@ -1,343 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Vector; - -abstract public class ASN1Set - extends ASN1Object -{ - protected Vector set = new Vector(); - - /** - * return an ASN1Set from the given object. - * - * @param obj the object we want converted. - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static ASN1Set getInstance( - Object obj) - { - if (obj == null || obj instanceof ASN1Set) - { - return (ASN1Set)obj; - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - /** - * Return an ASN1 set from a tagged object. There is a special - * case here, if an object appears to have been explicitly tagged on - * reading but we were expecting it to be implicitly tagged in the - * normal course of events it indicates that we lost the surrounding - * set - so we need to add it back (this will happen if the tagged - * object is a sequence that contains other sequences). If you are - * dealing with implicitly tagged sets you really should - * be using this method. - * - * @param obj the tagged object. - * @param explicit true if the object is meant to be explicitly tagged - * false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static ASN1Set getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - if (explicit) - { - if (!obj.isExplicit()) - { - throw new IllegalArgumentException("object implicit - explicit expected."); - } - - return (ASN1Set)obj.getObject(); - } - else - { - // - // constructed object which appears to be explicitly tagged - // and it's really implicit means we have to add the - // surrounding sequence. - // - if (obj.isExplicit()) - { - ASN1Set set = new DERSet(obj.getObject()); - - return set; - } - else - { - if (obj.getObject() instanceof ASN1Set) - { - return (ASN1Set)obj.getObject(); - } - - // - // in this case the parser returns a sequence, convert it - // into a set. - // - ASN1EncodableVector v = new ASN1EncodableVector(); - - if (obj.getObject() instanceof ASN1Sequence) - { - ASN1Sequence s = (ASN1Sequence)obj.getObject(); - Enumeration e = s.getObjects(); - - while (e.hasMoreElements()) - { - v.add((DEREncodable)e.nextElement()); - } - - return new DERSet(v, false); - } - } - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - public ASN1Set() - { - } - - public Enumeration getObjects() - { - return set.elements(); - } - - /** - * return the object at the set position indicated by index. - * - * @param index the set number (starting at zero) of the object - * @return the object at the set position indicated by index. - */ - public DEREncodable getObjectAt( - int index) - { - return (DEREncodable)set.elementAt(index); - } - - /** - * return the number of objects in this set. - * - * @return the number of objects in this set. - */ - public int size() - { - return set.size(); - } - - public ASN1SetParser parser() - { - final ASN1Set outer = this; - - return new ASN1SetParser() - { - private final int max = size(); - - private int index; - - public DEREncodable readObject() throws IOException - { - if (index == max) - { - return null; - } - - DEREncodable obj = getObjectAt(index++); - if (obj instanceof ASN1Sequence) - { - return ((ASN1Sequence)obj).parser(); - } - if (obj instanceof ASN1Set) - { - return ((ASN1Set)obj).parser(); - } - - return obj; - } - - public DERObject getDERObject() - { - return outer; - } - }; - } - - public int hashCode() - { - Enumeration e = this.getObjects(); - int hashCode = size(); - - while (e.hasMoreElements()) - { - Object o = e.nextElement(); - hashCode *= 17; - if (o != null) - { - hashCode ^= o.hashCode(); - } - } - - return hashCode; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof ASN1Set)) - { - return false; - } - - ASN1Set other = (ASN1Set)o; - - if (this.size() != other.size()) - { - return false; - } - - Enumeration s1 = this.getObjects(); - Enumeration s2 = other.getObjects(); - - while (s1.hasMoreElements()) - { - DERObject o1 = ((DEREncodable)s1.nextElement()).getDERObject(); - DERObject o2 = ((DEREncodable)s2.nextElement()).getDERObject(); - - if (o1 == o2 || (o1 != null && o1.equals(o2))) - { - continue; - } - - return false; - } - - return true; - } - - /** - * return true if a <= b (arrays are assumed padded with zeros). - */ - private boolean lessThanOrEqual( - byte[] a, - byte[] b) - { - if (a.length <= b.length) - { - for (int i = 0; i != a.length; i++) - { - int l = a[i] & 0xff; - int r = b[i] & 0xff; - - if (r > l) - { - return true; - } - else if (l > r) - { - return false; - } - } - - return true; - } - else - { - for (int i = 0; i != b.length; i++) - { - int l = a[i] & 0xff; - int r = b[i] & 0xff; - - if (r > l) - { - return true; - } - else if (l > r) - { - return false; - } - } - - return false; - } - } - - private byte[] getEncoded( - DEREncodable obj) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - try - { - aOut.writeObject(obj); - } - catch (IOException e) - { - throw new IllegalArgumentException("cannot encode object added to SET"); - } - - return bOut.toByteArray(); - } - - protected void sort() - { - if (set.size() > 1) - { - boolean swapped = true; - int lastSwap = set.size() - 1; - - while (swapped) - { - int index = 0; - int swapIndex = 0; - byte[] a = getEncoded((DEREncodable)set.elementAt(0)); - - swapped = false; - - while (index != lastSwap) - { - byte[] b = getEncoded((DEREncodable)set.elementAt(index + 1)); - - if (lessThanOrEqual(a, b)) - { - a = b; - } - else - { - Object o = set.elementAt(index); - - set.setElementAt(set.elementAt(index + 1), index); - set.setElementAt(o, index + 1); - - swapped = true; - swapIndex = index; - } - - index++; - } - - lastSwap = swapIndex; - } - } - } - - protected void addObject( - DEREncodable obj) - { - set.addElement(obj); - } - - abstract void encode(DEROutputStream out) - throws IOException; - - public String toString() - { - return set.toString(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1SetParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1SetParser.java deleted file mode 100644 index 2c3a1a0c4f..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1SetParser.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public interface ASN1SetParser - extends DEREncodable -{ - public DEREncodable readObject() - throws IOException; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1StreamParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1StreamParser.java deleted file mode 100644 index 6271c96afb..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1StreamParser.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class ASN1StreamParser -{ - private final InputStream _in; - private final int _limit; - - public ASN1StreamParser( - InputStream in) - { - this(in, Integer.MAX_VALUE); - } - - public ASN1StreamParser( - InputStream in, - int limit) - { - this._in = in; - this._limit = limit; - } - - public ASN1StreamParser( - byte[] encoding) - { - this(new ByteArrayInputStream(encoding), encoding.length); - } - - public DEREncodable readObject() - throws IOException - { - int tag = _in.read(); - if (tag == -1) - { - return null; - } - - // - // turn of looking for "00" while we resolve the tag - // - set00Check(false); - - // - // calculate tag number - // - int tagNo = ASN1InputStream.readTagNumber(_in, tag); - - boolean isConstructed = (tag & DERTags.CONSTRUCTED) != 0; - - // - // calculate length - // - int length = ASN1InputStream.readLength(_in, _limit); - - if (length < 0) // indefinite length method - { - if (!isConstructed) - { - throw new IOException("indefinite length primitive encoding encountered"); - } - - IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in); - - if ((tag & DERTags.APPLICATION) != 0) - { - ASN1StreamParser sp = new ASN1StreamParser(indIn); - - return new BERApplicationSpecificParser(tagNo, sp); - } - - if ((tag & DERTags.TAGGED) != 0) - { - return new BERTaggedObjectParser(tag, tagNo, indIn); - } - - ASN1StreamParser sp = new ASN1StreamParser(indIn); - - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case DERTags.OCTET_STRING: - return new BEROctetStringParser(sp); - case DERTags.SEQUENCE: - return new BERSequenceParser(sp); - case DERTags.SET: - return new BERSetParser(sp); - default: - throw new IOException("unknown BER object encountered"); - } - } - else - { - DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length); - - if ((tag & DERTags.APPLICATION) != 0) - { - return new DERApplicationSpecific(isConstructed, tagNo, defIn.toByteArray()); - } - - if ((tag & DERTags.TAGGED) != 0) - { - return new BERTaggedObjectParser(tag, tagNo, defIn); - } - - if (isConstructed) - { - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case DERTags.OCTET_STRING: - // - // yes, people actually do this... - // - return new BEROctetStringParser(new ASN1StreamParser(defIn)); - case DERTags.SEQUENCE: - return new DERSequenceParser(new ASN1StreamParser(defIn)); - case DERTags.SET: - return new DERSetParser(new ASN1StreamParser(defIn)); - default: - // TODO Add DERUnknownTagParser class? - return new DERUnknownTag(true, tagNo, defIn.toByteArray()); - } - } - - // Some primitive encodings can be handled by parsers too... - switch (tagNo) - { - case DERTags.OCTET_STRING: - return new DEROctetStringParser(defIn); - } - - return ASN1InputStream.createPrimitiveDERObject(tagNo, defIn.toByteArray()); - } - } - - private void set00Check(boolean enabled) - { - if (_in instanceof IndefiniteLengthInputStream) - { - ((IndefiniteLengthInputStream)_in).setEofOn00(enabled); - } - } - - ASN1EncodableVector readVector() throws IOException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - DEREncodable obj; - while ((obj = readObject()) != null) - { - v.add(obj.getDERObject()); - } - - return v; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObject.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObject.java deleted file mode 100644 index e1b0eef89d..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObject.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by - * a [n] where n is some number - these are assumed to follow the construction - * rules (as with sequences). - */ -public abstract class ASN1TaggedObject - extends ASN1Object - implements ASN1TaggedObjectParser -{ - int tagNo; - boolean empty = false; - boolean explicit = true; - DEREncodable obj = null; - - static public ASN1TaggedObject getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - if (explicit) - { - return (ASN1TaggedObject)obj.getObject(); - } - - throw new IllegalArgumentException("implicitly tagged tagged object"); - } - - static public ASN1TaggedObject getInstance( - Object obj) - { - if (obj == null || obj instanceof ASN1TaggedObject) - { - return (ASN1TaggedObject)obj; - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - /** - * Create a tagged object in the explicit style. - * - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public ASN1TaggedObject( - int tagNo, - DEREncodable obj) - { - this.explicit = true; - this.tagNo = tagNo; - this.obj = obj; - } - - /** - * Create a tagged object with the style given by the value of explicit. - *

- * If the object implements ASN1Choice the tag style will always be changed - * to explicit in accordance with the ASN.1 encoding rules. - *

- * @param explicit true if the object is explicitly tagged. - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public ASN1TaggedObject( - boolean explicit, - int tagNo, - DEREncodable obj) - { - if (obj instanceof ASN1Choice) - { - this.explicit = true; - } - else - { - this.explicit = explicit; - } - - this.tagNo = tagNo; - this.obj = obj; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof ASN1TaggedObject)) - { - return false; - } - - ASN1TaggedObject other = (ASN1TaggedObject)o; - - if (tagNo != other.tagNo || empty != other.empty || explicit != other.explicit) - { - return false; - } - - if(obj == null) - { - if (other.obj != null) - { - return false; - } - } - else - { - if (!(obj.getDERObject().equals(other.obj.getDERObject()))) - { - return false; - } - } - - return true; - } - - public int hashCode() - { - int code = tagNo; - - // TODO: actually this is wrong - the problem is that a re-encoded - // object may end up with a different hashCode due to implicit - // tagging. As implicit tagging is ambiguous if a sequence is involved - // it seems the only correct method for both equals and hashCode is to - // compare the encodings... - if (obj != null) - { - code ^= obj.hashCode(); - } - - return code; - } - - public int getTagNo() - { - return tagNo; - } - - /** - * return whether or not the object may be explicitly tagged. - *

- * Note: if the object has been read from an input stream, the only - * time you can be sure if isExplicit is returning the true state of - * affairs is if it returns false. An implicitly tagged object may appear - * to be explicitly tagged, so you need to understand the context under - * which the reading was done as well, see getObject below. - */ - public boolean isExplicit() - { - return explicit; - } - - public boolean isEmpty() - { - return empty; - } - - /** - * return whatever was following the tag. - *

- * Note: tagged objects are generally context dependent if you're - * trying to extract a tagged object you should be going via the - * appropriate getInstance method. - */ - public DERObject getObject() - { - if (obj != null) - { - return obj.getDERObject(); - } - - return null; - } - - /** - * Return the object held in this tagged object as a parser assuming it has - * the type of the passed in tag. If the object doesn't have a parser - * associated with it, the base object is returned. - */ - public DEREncodable getObjectParser( - int tag, - boolean isExplicit) - { - switch (tag) - { - case DERTags.SET: - return ASN1Set.getInstance(this, isExplicit).parser(); - case DERTags.SEQUENCE: - return ASN1Sequence.getInstance(this, isExplicit).parser(); - case DERTags.OCTET_STRING: - return ASN1OctetString.getInstance(this, isExplicit).parser(); - } - - if (isExplicit) - { - return getObject(); - } - - throw new RuntimeException("implicit tagging not implemented for tag: " + tag); - } - - abstract void encode(DEROutputStream out) - throws IOException; - - public String toString() - { - return "[" + tagNo + "]" + obj; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObjectParser.java b/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObjectParser.java deleted file mode 100644 index a45877ef08..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ASN1TaggedObjectParser.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public interface ASN1TaggedObjectParser - extends DEREncodable -{ - public int getTagNo(); - - public DEREncodable getObjectParser(int tag, boolean isExplicit) - throws IOException; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecific.java b/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecific.java deleted file mode 100644 index 0dd5fa31a6..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecific.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -public class BERApplicationSpecific - extends DERApplicationSpecific -{ - public BERApplicationSpecific(int tagNo, ASN1EncodableVector vec) - { - super(tagNo, vec); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecificParser.java b/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecificParser.java deleted file mode 100644 index 719e927150..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERApplicationSpecificParser.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class BERApplicationSpecificParser - implements ASN1ApplicationSpecificParser -{ - private final int tag; - private final ASN1StreamParser parser; - - BERApplicationSpecificParser(int tag, ASN1StreamParser parser) - { - this.tag = tag; - this.parser = parser; - } - - public DEREncodable readObject() - throws IOException - { - return parser.readObject(); - } - - public DERObject getDERObject() - { - try - { - return new BERApplicationSpecific(tag, parser.readVector()); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} \ No newline at end of file diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERConstructedOctetString.java b/src/org/thoughtcrime/bouncycastle/asn1/BERConstructedOctetString.java deleted file mode 100644 index 4056cc4c0c..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERConstructedOctetString.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Vector; - -public class BERConstructedOctetString - extends DEROctetString -{ - private static final int MAX_LENGTH = 1000; - - /** - * convert a vector of octet strings into a single byte string - */ - static private byte[] toBytes( - Vector octs) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - for (int i = 0; i != octs.size(); i++) - { - try - { - DEROctetString o = (DEROctetString)octs.elementAt(i); - - bOut.write(o.getOctets()); - } - catch (ClassCastException e) - { - throw new IllegalArgumentException(octs.elementAt(i).getClass().getName() + " found in input should only contain DEROctetString"); - } - catch (IOException e) - { - throw new IllegalArgumentException("exception converting octets " + e.toString()); - } - } - - return bOut.toByteArray(); - } - - private Vector octs; - - /** - * @param string the octets making up the octet string. - */ - public BERConstructedOctetString( - byte[] string) - { - super(string); - } - - public BERConstructedOctetString( - Vector octs) - { - super(toBytes(octs)); - - this.octs = octs; - } - - public BERConstructedOctetString( - DERObject obj) - { - super(obj); - } - - public BERConstructedOctetString( - DEREncodable obj) - { - super(obj.getDERObject()); - } - - public byte[] getOctets() - { - return string; - } - - /** - * return the DER octets that make up this string. - */ - public Enumeration getObjects() - { - if (octs == null) - { - return generateOcts().elements(); - } - - return octs.elements(); - } - - private Vector generateOcts() - { - Vector vec = new Vector(); - for (int i = 0; i < string.length; i += MAX_LENGTH) - { - int end; - - if (i + MAX_LENGTH > string.length) - { - end = string.length; - } - else - { - end = i + MAX_LENGTH; - } - - byte[] nStr = new byte[end - i]; - - System.arraycopy(string, i, nStr, 0, nStr.length); - - vec.addElement(new DEROctetString(nStr)); - } - - return vec; - } - - public void encode( - DEROutputStream out) - throws IOException - { - if (out instanceof ASN1OutputStream || out instanceof BEROutputStream) - { - out.write(CONSTRUCTED | OCTET_STRING); - - out.write(0x80); - - // - // write out the octet array - // - Enumeration e = getObjects(); - while (e.hasMoreElements()) - { - out.writeObject(e.nextElement()); - } - - out.write(0x00); - out.write(0x00); - } - else - { - super.encode(out); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERFactory.java b/src/org/thoughtcrime/bouncycastle/asn1/BERFactory.java deleted file mode 100644 index d59e3f900c..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -class BERFactory -{ - static final BERSequence EMPTY_SEQUENCE = new BERSequence(); - static final BERSet EMPTY_SET = new BERSet(); - - static BERSequence createSequence(ASN1EncodableVector v) - { - return v.size() < 1 ? EMPTY_SEQUENCE : new BERSequence(v); - } - - static BERSet createSet(ASN1EncodableVector v) - { - return v.size() < 1 ? EMPTY_SET : new BERSet(v); - } - - static BERSet createSet(ASN1EncodableVector v, boolean needsSorting) - { - return v.size() < 1 ? EMPTY_SET : new BERSet(v, needsSorting); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BEROctetStringParser.java b/src/org/thoughtcrime/bouncycastle/asn1/BEROctetStringParser.java deleted file mode 100644 index 1c0975cbfe..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BEROctetStringParser.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.io.Streams; - -import java.io.InputStream; -import java.io.IOException; - -public class BEROctetStringParser - implements ASN1OctetStringParser -{ - private ASN1StreamParser _parser; - - BEROctetStringParser( - ASN1StreamParser parser) - { - _parser = parser; - } - - /** - * @deprecated will be removed - */ - protected BEROctetStringParser( - ASN1ObjectParser parser) - { - _parser = parser._aIn; - } - - public InputStream getOctetStream() - { - return new ConstructedOctetStream(_parser); - } - - public DERObject getDERObject() - { - try - { - return new BERConstructedOctetString(Streams.readAll(getOctetStream())); - } - catch (IOException e) - { - throw new IllegalStateException("IOException converting stream to byte array: " + e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BEROutputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/BEROutputStream.java deleted file mode 100644 index 361eae3a18..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BEROutputStream.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.io.OutputStream; - -public class BEROutputStream - extends DEROutputStream -{ - public BEROutputStream( - OutputStream os) - { - super(os); - } - - public void writeObject( - Object obj) - throws IOException - { - if (obj == null) - { - writeNull(); - } - else if (obj instanceof DERObject) - { - ((DERObject)obj).encode(this); - } - else if (obj instanceof DEREncodable) - { - ((DEREncodable)obj).getDERObject().encode(this); - } - else - { - throw new IOException("object not BEREncodable"); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERSequence.java b/src/org/thoughtcrime/bouncycastle/asn1/BERSequence.java deleted file mode 100644 index 9dd1c0e7e2..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERSequence.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.util.Enumeration; - -public class BERSequence - extends DERSequence -{ - /** - * create an empty sequence - */ - public BERSequence() - { - } - - /** - * create a sequence containing one object - */ - public BERSequence( - DEREncodable obj) - { - super(obj); - } - - /** - * create a sequence containing a vector of objects. - */ - public BERSequence( - DEREncodableVector v) - { - super(v); - } - - /* - */ - void encode( - DEROutputStream out) - throws IOException - { - if (out instanceof ASN1OutputStream || out instanceof BEROutputStream) - { - out.write(SEQUENCE | CONSTRUCTED); - out.write(0x80); - - Enumeration e = getObjects(); - while (e.hasMoreElements()) - { - out.writeObject(e.nextElement()); - } - - out.write(0x00); - out.write(0x00); - } - else - { - super.encode(out); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERSequenceParser.java b/src/org/thoughtcrime/bouncycastle/asn1/BERSequenceParser.java deleted file mode 100644 index 91f671f1a9..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERSequenceParser.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class BERSequenceParser - implements ASN1SequenceParser -{ - private ASN1StreamParser _parser; - - BERSequenceParser(ASN1StreamParser parser) - { - this._parser = parser; - } - - public DEREncodable readObject() - throws IOException - { - return _parser.readObject(); - } - - public DERObject getDERObject() - { - try - { - return new BERSequence(_parser.readVector()); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERSet.java b/src/org/thoughtcrime/bouncycastle/asn1/BERSet.java deleted file mode 100644 index 5ad981ea62..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERSet.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.util.Enumeration; - -public class BERSet - extends DERSet -{ - /** - * create an empty sequence - */ - public BERSet() - { - } - - /** - * create a set containing one object - */ - public BERSet( - DEREncodable obj) - { - super(obj); - } - - /** - * @param v - a vector of objects making up the set. - */ - public BERSet( - DEREncodableVector v) - { - super(v, false); - } - - /** - * @param v - a vector of objects making up the set. - */ - BERSet( - DEREncodableVector v, - boolean needsSorting) - { - super(v, needsSorting); - } - - /* - */ - void encode( - DEROutputStream out) - throws IOException - { - if (out instanceof ASN1OutputStream || out instanceof BEROutputStream) - { - out.write(SET | CONSTRUCTED); - out.write(0x80); - - Enumeration e = getObjects(); - while (e.hasMoreElements()) - { - out.writeObject(e.nextElement()); - } - - out.write(0x00); - out.write(0x00); - } - else - { - super.encode(out); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERSetParser.java b/src/org/thoughtcrime/bouncycastle/asn1/BERSetParser.java deleted file mode 100644 index 6d3fce077c..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERSetParser.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class BERSetParser - implements ASN1SetParser -{ - private ASN1StreamParser _parser; - - BERSetParser(ASN1StreamParser parser) - { - this._parser = parser; - } - - public DEREncodable readObject() - throws IOException - { - return _parser.readObject(); - } - - public DERObject getDERObject() - { - try - { - return new BERSet(_parser.readVector(), false); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObject.java b/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObject.java deleted file mode 100644 index 25cb2c1725..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObject.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.util.Enumeration; - -/** - * BER TaggedObject - in ASN.1 notation this is any object preceded by - * a [n] where n is some number - these are assumed to follow the construction - * rules (as with sequences). - */ -public class BERTaggedObject - extends DERTaggedObject -{ - /** - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public BERTaggedObject( - int tagNo, - DEREncodable obj) - { - super(tagNo, obj); - } - - /** - * @param explicit true if an explicitly tagged object. - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public BERTaggedObject( - boolean explicit, - int tagNo, - DEREncodable obj) - { - super(explicit, tagNo, obj); - } - - /** - * create an implicitly tagged object that contains a zero - * length sequence. - */ - public BERTaggedObject( - int tagNo) - { - super(false, tagNo, new BERSequence()); - } - - void encode( - DEROutputStream out) - throws IOException - { - if (out instanceof ASN1OutputStream || out instanceof BEROutputStream) - { - out.writeTag(CONSTRUCTED | TAGGED, tagNo); - out.write(0x80); - - if (!empty) - { - if (!explicit) - { - Enumeration e; - if (obj instanceof ASN1OctetString) - { - if (obj instanceof BERConstructedOctetString) - { - e = ((BERConstructedOctetString)obj).getObjects(); - } - else - { - ASN1OctetString octs = (ASN1OctetString)obj; - BERConstructedOctetString berO = new BERConstructedOctetString(octs.getOctets()); - e = berO.getObjects(); - } - } - else if (obj instanceof ASN1Sequence) - { - e = ((ASN1Sequence)obj).getObjects(); - } - else if (obj instanceof ASN1Set) - { - e = ((ASN1Set)obj).getObjects(); - } - else - { - throw new RuntimeException("not implemented: " + obj.getClass().getName()); - } - - while (e.hasMoreElements()) - { - out.writeObject(e.nextElement()); - } - } - else - { - out.writeObject(obj); - } - } - - out.write(0x00); - out.write(0x00); - } - else - { - super.encode(out); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObjectParser.java b/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObjectParser.java deleted file mode 100644 index 462190a738..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/BERTaggedObjectParser.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.io.InputStream; - -public class BERTaggedObjectParser - implements ASN1TaggedObjectParser -{ - private int _baseTag; - private int _tagNumber; - private InputStream _contentStream; - - private boolean _indefiniteLength; - - protected BERTaggedObjectParser( - int baseTag, - int tagNumber, - InputStream contentStream) - { - _baseTag = baseTag; - _tagNumber = tagNumber; - _contentStream = contentStream; - _indefiniteLength = contentStream instanceof IndefiniteLengthInputStream; - } - - public boolean isConstructed() - { - return (_baseTag & DERTags.CONSTRUCTED) != 0; - } - - public int getTagNo() - { - return _tagNumber; - } - - public DEREncodable getObjectParser( - int tag, - boolean isExplicit) - throws IOException - { - if (isExplicit) - { - return new ASN1StreamParser(_contentStream).readObject(); - } - - switch (tag) - { - case DERTags.SET: - if (_indefiniteLength) - { - return new BERSetParser(new ASN1StreamParser(_contentStream)); - } - else - { - return new DERSetParser(new ASN1StreamParser(_contentStream)); - } - case DERTags.SEQUENCE: - if (_indefiniteLength) - { - return new BERSequenceParser(new ASN1StreamParser(_contentStream)); - } - else - { - return new DERSequenceParser(new ASN1StreamParser(_contentStream)); - } - case DERTags.OCTET_STRING: - // TODO Is the handling of definite length constructed encodings correct? - if (_indefiniteLength || this.isConstructed()) - { - return new BEROctetStringParser(new ASN1StreamParser(_contentStream)); - } - else - { - return new DEROctetStringParser((DefiniteLengthInputStream)_contentStream); - } - } - - throw new RuntimeException("implicit tagging not implemented"); - } - - private ASN1EncodableVector rLoadVector(InputStream in) - { - try - { - return new ASN1StreamParser(in).readVector(); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } - - public DERObject getDERObject() - { - if (_indefiniteLength) - { - ASN1EncodableVector v = rLoadVector(_contentStream); - - return v.size() == 1 - ? new BERTaggedObject(true, _tagNumber, v.get(0)) - : new BERTaggedObject(false, _tagNumber, BERFactory.createSequence(v)); - } - - if (this.isConstructed()) - { - ASN1EncodableVector v = rLoadVector(_contentStream); - - return v.size() == 1 - ? new DERTaggedObject(true, _tagNumber, v.get(0)) - : new DERTaggedObject(false, _tagNumber, DERFactory.createSequence(v)); - } - - try - { - DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_contentStream; - return new DERTaggedObject(false, _tagNumber, new DEROctetString(defIn.toByteArray())); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/ConstructedOctetStream.java b/src/org/thoughtcrime/bouncycastle/asn1/ConstructedOctetStream.java deleted file mode 100644 index 77901f72cb..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/ConstructedOctetStream.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.InputStream; -import java.io.IOException; - -class ConstructedOctetStream - extends InputStream -{ - private final ASN1StreamParser _parser; - - private boolean _first = true; - private InputStream _currentStream; - - ConstructedOctetStream( - ASN1StreamParser parser) - { - _parser = parser; - } - - public int read(byte[] b, int off, int len) throws IOException - { - if (_currentStream == null) - { - if (!_first) - { - return -1; - } - - ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); - - if (s == null) - { - return -1; - } - - _first = false; - _currentStream = s.getOctetStream(); - } - - int totalRead = 0; - - for (;;) - { - int numRead = _currentStream.read(b, off + totalRead, len - totalRead); - - if (numRead >= 0) - { - totalRead += numRead; - - if (totalRead == len) - { - return totalRead; - } - } - else - { - ASN1OctetStringParser aos = (ASN1OctetStringParser)_parser.readObject(); - - if (aos == null) - { - _currentStream = null; - return totalRead < 1 ? -1 : totalRead; - } - - _currentStream = aos.getOctetStream(); - } - } - } - - public int read() - throws IOException - { - if (_currentStream == null) - { - if (!_first) - { - return -1; - } - - ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); - - if (s == null) - { - return -1; - } - - _first = false; - _currentStream = s.getOctetStream(); - } - - for (;;) - { - int b = _currentStream.read(); - - if (b >= 0) - { - return b; - } - - ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); - - if (s == null) - { - _currentStream = null; - return -1; - } - - _currentStream = s.getOctetStream(); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERApplicationSpecific.java b/src/org/thoughtcrime/bouncycastle/asn1/DERApplicationSpecific.java deleted file mode 100644 index a7594f04d0..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERApplicationSpecific.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.bouncycastle.util.Arrays; - -/** - * Base class for an application specific object - */ -public class DERApplicationSpecific - extends ASN1Object -{ - private final boolean isConstructed; - private final int tag; - private final byte[] octets; - - DERApplicationSpecific( - boolean isConstructed, - int tag, - byte[] octets) - { - this.isConstructed = isConstructed; - this.tag = tag; - this.octets = octets; - } - - public DERApplicationSpecific( - int tag, - byte[] octets) - { - this(false, tag, octets); - } - - public DERApplicationSpecific( - int tag, - DEREncodable object) - throws IOException - { - this(true, tag, object); - } - - public DERApplicationSpecific( - boolean explicit, - int tag, - DEREncodable object) - throws IOException - { - byte[] data = object.getDERObject().getDEREncoded(); - - this.isConstructed = explicit; - this.tag = tag; - - if (explicit) - { - this.octets = data; - } - else - { - int lenBytes = getLengthOfLength(data); - byte[] tmp = new byte[data.length - lenBytes]; - System.arraycopy(data, lenBytes, tmp, 0, tmp.length); - this.octets = tmp; - } - } - - public DERApplicationSpecific(int tagNo, ASN1EncodableVector vec) - { - this.tag = tagNo; - this.isConstructed = true; - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - for (int i = 0; i != vec.size(); i++) - { - try - { - bOut.write(((ASN1Encodable)vec.get(i)).getEncoded()); - } - catch (IOException e) - { - throw new IllegalStateException("malformed object: " + e); - } - } - this.octets = bOut.toByteArray(); - } - - private int getLengthOfLength(byte[] data) - { - int count = 2; // TODO: assumes only a 1 byte tag number - - while((data[count - 1] & 0x80) != 0) - { - count++; - } - - return count; - } - - public boolean isConstructed() - { - return isConstructed; - } - - public byte[] getContents() - { - return octets; - } - - public int getApplicationTag() - { - return tag; - } - - /** - * Return the enclosed object assuming explicit tagging. - * - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public DERObject getObject() - throws IOException - { - return new ASN1InputStream(getContents()).readObject(); - } - - /** - * Return the enclosed object assuming implicit tagging. - * - * @param derTagNo the type tag that should be applied to the object's contents. - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public DERObject getObject(int derTagNo) - throws IOException - { - if (derTagNo >= 0x1f) - { - throw new IOException("unsupported tag number"); - } - - byte[] orig = this.getEncoded(); - byte[] tmp = replaceTagNumber(derTagNo, orig); - - if ((orig[0] & DERTags.CONSTRUCTED) != 0) - { - tmp[0] |= DERTags.CONSTRUCTED; - } - - return new ASN1InputStream(tmp).readObject(); - } - - /* (non-Javadoc) - * @see org.bouncycastle.asn1.DERObject#encode(org.bouncycastle.asn1.DEROutputStream) - */ - void encode(DEROutputStream out) throws IOException - { - int classBits = DERTags.APPLICATION; - if (isConstructed) - { - classBits |= DERTags.CONSTRUCTED; - } - - out.writeEncoded(classBits, tag, octets); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERApplicationSpecific)) - { - return false; - } - - DERApplicationSpecific other = (DERApplicationSpecific)o; - - return isConstructed == other.isConstructed - && tag == other.tag - && Arrays.areEqual(octets, other.octets); - } - - public int hashCode() - { - return (isConstructed ? 1 : 0) ^ tag ^ Arrays.hashCode(octets); - } - - private byte[] replaceTagNumber(int newTag, byte[] input) - throws IOException - { - int tagNo = input[0] & 0x1f; - int index = 1; - // - // with tagged object tag number is bottom 5 bits, or stored at the start of the content - // - if (tagNo == 0x1f) - { - tagNo = 0; - - int b = input[index++] & 0xff; - - // X.690-0207 8.1.2.4.2 - // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) // Note: -1 will pass - { - throw new IllegalStateException("corrupted stream - invalid high tag number found"); - } - - while ((b >= 0) && ((b & 0x80) != 0)) - { - tagNo |= (b & 0x7f); - tagNo <<= 7; - b = input[index++] & 0xff; - } - - tagNo |= (b & 0x7f); - } - - byte[] tmp = new byte[input.length - index + 1]; - - System.arraycopy(input, index, tmp, 1, tmp.length - 1); - - tmp[0] = (byte)newTag; - - return tmp; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERBMPString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERBMPString.java deleted file mode 100644 index b7eb2f25c3..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERBMPString.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER BMPString object. - */ -public class DERBMPString - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a BMP String from the given object. - * - * @param obj the object we want converted. - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERBMPString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERBMPString) - { - return (DERBMPString)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERBMPString(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a BMP String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERBMPString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - - /** - * basic constructor - byte encoded string. - */ - public DERBMPString( - byte[] string) - { - char[] cs = new char[string.length / 2]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)((string[2 * i] << 8) | (string[2 * i + 1] & 0xff)); - } - - this.string = new String(cs); - } - - /** - * basic constructor - */ - public DERBMPString( - String string) - { - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - protected boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERBMPString)) - { - return false; - } - - DERBMPString s = (DERBMPString)o; - - return this.getString().equals(s.getString()); - } - - void encode( - DEROutputStream out) - throws IOException - { - char[] c = string.toCharArray(); - byte[] b = new byte[c.length * 2]; - - for (int i = 0; i != c.length; i++) - { - b[2 * i] = (byte)(c[i] >> 8); - b[2 * i + 1] = (byte)c[i]; - } - - out.writeEncoded(BMP_STRING, b); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERBitString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERBitString.java deleted file mode 100644 index 6804dcb494..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERBitString.java +++ /dev/null @@ -1,266 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.Arrays; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -public class DERBitString - extends ASN1Object - implements DERString -{ - private static final char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - protected byte[] data; - protected int padBits; - - /** - * return the correct number of pad bits for a bit string defined in - * a 32 bit constant - */ - static protected int getPadBits( - int bitString) - { - int val = 0; - for (int i = 3; i >= 0; i--) - { - // - // this may look a little odd, but if it isn't done like this pre jdk1.2 - // JVM's break! - // - if (i != 0) - { - if ((bitString >> (i * 8)) != 0) - { - val = (bitString >> (i * 8)) & 0xFF; - break; - } - } - else - { - if (bitString != 0) - { - val = bitString & 0xFF; - break; - } - } - } - - if (val == 0) - { - return 7; - } - - - int bits = 1; - - while (((val <<= 1) & 0xFF) != 0) - { - bits++; - } - - return 8 - bits; - } - - /** - * return the correct number of bytes for a bit string defined in - * a 32 bit constant - */ - static protected byte[] getBytes(int bitString) - { - int bytes = 4; - for (int i = 3; i >= 1; i--) - { - if ((bitString & (0xFF << (i * 8))) != 0) - { - break; - } - bytes--; - } - - byte[] result = new byte[bytes]; - for (int i = 0; i < bytes; i++) - { - result[i] = (byte) ((bitString >> (i * 8)) & 0xFF); - } - - return result; - } - - /** - * return a Bit String from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERBitString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERBitString) - { - return (DERBitString)obj; - } - - if (obj instanceof ASN1OctetString) - { - byte[] bytes = ((ASN1OctetString)obj).getOctets(); - int padBits = bytes[0]; - byte[] data = new byte[bytes.length - 1]; - - System.arraycopy(bytes, 1, data, 0, bytes.length - 1); - - return new DERBitString(data, padBits); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a Bit String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERBitString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - protected DERBitString( - byte data, - int padBits) - { - this.data = new byte[1]; - this.data[0] = data; - this.padBits = padBits; - } - - /** - * @param data the octets making up the bit string. - * @param padBits the number of extra bits at the end of the string. - */ - public DERBitString( - byte[] data, - int padBits) - { - this.data = data; - this.padBits = padBits; - } - - public DERBitString( - byte[] data) - { - this(data, 0); - } - - public DERBitString( - DEREncodable obj) - { - try - { - this.data = obj.getDERObject().getEncoded(ASN1Encodable.DER); - this.padBits = 0; - } - catch (IOException e) - { - throw new IllegalArgumentException("Error processing object : " + e.toString()); - } - } - - public byte[] getBytes() - { - return data; - } - - public int getPadBits() - { - return padBits; - } - - - /** - * @return the value of the bit string as an int (truncating if necessary) - */ - public int intValue() - { - int value = 0; - - for (int i = 0; i != data.length && i != 4; i++) - { - value |= (data[i] & 0xff) << (8 * i); - } - - return value; - } - - void encode( - DEROutputStream out) - throws IOException - { - byte[] bytes = new byte[getBytes().length + 1]; - - bytes[0] = (byte)getPadBits(); - System.arraycopy(getBytes(), 0, bytes, 1, bytes.length - 1); - - out.writeEncoded(BIT_STRING, bytes); - } - - public int hashCode() - { - return padBits ^ Arrays.hashCode(data); - } - - protected boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERBitString)) - { - return false; - } - - DERBitString other = (DERBitString)o; - - return this.padBits == other.padBits - && Arrays.areEqual(this.data, other.data); - } - - public String getString() - { - StringBuffer buf = new StringBuffer("#"); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - try - { - aOut.writeObject(this); - } - catch (IOException e) - { - throw new RuntimeException("internal error encoding BitString"); - } - - byte[] string = bOut.toByteArray(); - - for (int i = 0; i != string.length; i++) - { - buf.append(table[(string[i] >>> 4) & 0xf]); - buf.append(table[string[i] & 0xf]); - } - - return buf.toString(); - } - - public String toString() - { - return getString(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERBoolean.java b/src/org/thoughtcrime/bouncycastle/asn1/DERBoolean.java deleted file mode 100644 index 9d90f3af69..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERBoolean.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class DERBoolean - extends ASN1Object -{ - byte value; - - public static final DERBoolean FALSE = new DERBoolean(false); - public static final DERBoolean TRUE = new DERBoolean(true); - - /** - * return a boolean from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERBoolean getInstance( - Object obj) - { - if (obj == null || obj instanceof DERBoolean) - { - return (DERBoolean)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERBoolean(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a DERBoolean from the passed in boolean. - */ - public static DERBoolean getInstance( - boolean value) - { - return (value ? TRUE : FALSE); - } - - /** - * return a Boolean from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERBoolean getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - public DERBoolean( - byte[] value) - { - this.value = value[0]; - } - - public DERBoolean( - boolean value) - { - this.value = (value) ? (byte)0xff : (byte)0; - } - - public boolean isTrue() - { - return (value != 0); - } - - void encode( - DEROutputStream out) - throws IOException - { - byte[] bytes = new byte[1]; - - bytes[0] = value; - - out.writeEncoded(BOOLEAN, bytes); - } - - protected boolean asn1Equals( - DERObject o) - { - if ((o == null) || !(o instanceof DERBoolean)) - { - return false; - } - - return (value == ((DERBoolean)o).value); - } - - public int hashCode() - { - return value; - } - - - public String toString() - { - return (value != 0) ? "TRUE" : "FALSE"; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEREncodable.java b/src/org/thoughtcrime/bouncycastle/asn1/DEREncodable.java deleted file mode 100644 index b496ed3b36..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEREncodable.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -public interface DEREncodable -{ - public DERObject getDERObject(); -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEREncodableVector.java b/src/org/thoughtcrime/bouncycastle/asn1/DEREncodableVector.java deleted file mode 100644 index b2eba1ed2f..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEREncodableVector.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.util.Vector; - -/** - * a general class for building up a vector of DER encodable objects - - * this will eventually be superceded by ASN1EncodableVector so you should - * use that class in preference. - */ -public class DEREncodableVector -{ - Vector v = new Vector(); - - /** - * @deprecated use ASN1EncodableVector instead. - */ - public DEREncodableVector() - { - - } - - public void add( - DEREncodable obj) - { - v.addElement(obj); - } - - public DEREncodable get( - int i) - { - return (DEREncodable)v.elementAt(i); - } - - public int size() - { - return v.size(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEREnumerated.java b/src/org/thoughtcrime/bouncycastle/asn1/DEREnumerated.java deleted file mode 100644 index 6dd0f2c128..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEREnumerated.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.Arrays; - -import java.io.IOException; -import java.math.BigInteger; - -public class DEREnumerated - extends ASN1Object -{ - byte[] bytes; - - /** - * return an integer from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DEREnumerated getInstance( - Object obj) - { - if (obj == null || obj instanceof DEREnumerated) - { - return (DEREnumerated)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DEREnumerated(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an Enumerated from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DEREnumerated getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - public DEREnumerated( - int value) - { - bytes = BigInteger.valueOf(value).toByteArray(); - } - - public DEREnumerated( - BigInteger value) - { - bytes = value.toByteArray(); - } - - public DEREnumerated( - byte[] bytes) - { - this.bytes = bytes; - } - - public BigInteger getValue() - { - return new BigInteger(bytes); - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(ENUMERATED, bytes); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DEREnumerated)) - { - return false; - } - - DEREnumerated other = (DEREnumerated)o; - - return Arrays.areEqual(this.bytes, other.bytes); - } - - public int hashCode() - { - return Arrays.hashCode(bytes); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERFactory.java b/src/org/thoughtcrime/bouncycastle/asn1/DERFactory.java deleted file mode 100644 index 393cb80c08..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -class DERFactory -{ - static final DERSequence EMPTY_SEQUENCE = new DERSequence(); - static final DERSet EMPTY_SET = new DERSet(); - - static DERSequence createSequence(ASN1EncodableVector v) - { - return v.size() < 1 ? EMPTY_SEQUENCE : new DERSequence(v); - } - - static DERSet createSet(ASN1EncodableVector v) - { - return v.size() < 1 ? EMPTY_SET : new DERSet(v); - } - - static DERSet createSet(ASN1EncodableVector v, boolean needsSorting) - { - return v.size() < 1 ? EMPTY_SET : new DERSet(v, needsSorting); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralString.java deleted file mode 100644 index a3ee83a7c2..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralString.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class DERGeneralString - extends ASN1Object implements DERString -{ - private String string; - - public static DERGeneralString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERGeneralString) - { - return (DERGeneralString) obj; - } - if (obj instanceof ASN1OctetString) - { - return new DERGeneralString(((ASN1OctetString) obj).getOctets()); - } - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject) obj).getObject()); - } - throw new IllegalArgumentException("illegal object in getInstance: " - + obj.getClass().getName()); - } - - public static DERGeneralString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - public DERGeneralString(byte[] string) - { - char[] cs = new char[string.length]; - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - this.string = new String(cs); - } - - public DERGeneralString(String string) - { - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte) cs[i]; - } - return bs; - } - - void encode(DEROutputStream out) - throws IOException - { - out.writeEncoded(GENERAL_STRING, this.getOctets()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - boolean asn1Equals(DERObject o) - { - if (!(o instanceof DERGeneralString)) - { - return false; - } - DERGeneralString s = (DERGeneralString) o; - return this.getString().equals(s.getString()); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralizedTime.java b/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralizedTime.java deleted file mode 100644 index 1ba15c3fa6..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERGeneralizedTime.java +++ /dev/null @@ -1,314 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.SimpleTimeZone; -import java.util.TimeZone; - -/** - * Generalized time object. - */ -public class DERGeneralizedTime - extends ASN1Object -{ - String time; - - /** - * return a generalized time from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERGeneralizedTime getInstance( - Object obj) - { - if (obj == null || obj instanceof DERGeneralizedTime) - { - return (DERGeneralizedTime)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERGeneralizedTime(((ASN1OctetString)obj).getOctets()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a Generalized Time object from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERGeneralizedTime getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z - * for local time, or Z+-HHMM on the end, for difference between local - * time and UTC time. The fractional second amount f must consist of at - * least one number with trailing zeroes removed. - * - * @param time the time string. - * @exception IllegalArgumentException if String is an illegal format. - */ - public DERGeneralizedTime( - String time) - { - this.time = time; - try - { - this.getDate(); - } - catch (ParseException e) - { - throw new IllegalArgumentException("invalid date string: " + e.getMessage()); - } - } - - /** - * base constructer from a java.util.date object - */ - public DERGeneralizedTime( - Date time) - { - SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); - - dateF.setTimeZone(new SimpleTimeZone(0,"Z")); - - this.time = dateF.format(time); - } - - DERGeneralizedTime( - byte[] bytes) - { - // - // explicitly convert to characters - // - char[] dateC = new char[bytes.length]; - - for (int i = 0; i != dateC.length; i++) - { - dateC[i] = (char)(bytes[i] & 0xff); - } - - this.time = new String(dateC); - } - - /** - * Return the time. - * @return The time string as it appeared in the encoded object. - */ - public String getTimeString() - { - return time; - } - - /** - * return the time - always in the form of - * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm). - *

- * Normally in a certificate we would expect "Z" rather than "GMT", - * however adding the "GMT" means we can just use: - *

-     *     dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
-     * 
- * To read in the time and get a date which is compatible with our local - * time zone. - */ - public String getTime() - { - // - // standardise the format. - // - if (time.charAt(time.length() - 1) == 'Z') - { - return time.substring(0, time.length() - 1) + "GMT+00:00"; - } - else - { - int signPos = time.length() - 5; - char sign = time.charAt(signPos); - if (sign == '-' || sign == '+') - { - return time.substring(0, signPos) - + "GMT" - + time.substring(signPos, signPos + 3) - + ":" - + time.substring(signPos + 3); - } - else - { - signPos = time.length() - 3; - sign = time.charAt(signPos); - if (sign == '-' || sign == '+') - { - return time.substring(0, signPos) - + "GMT" - + time.substring(signPos) - + ":00"; - } - } - } - return time + calculateGMTOffset(); - } - - private String calculateGMTOffset() - { - String sign = "+"; - TimeZone timeZone = TimeZone.getDefault(); - int offset = timeZone.getRawOffset(); - if (offset < 0) - { - sign = "-"; - offset = -offset; - } - int hours = offset / (60 * 60 * 1000); - int minutes = (offset - (hours * 60 * 60 * 1000)) / (60 * 1000); - - try - { - if (timeZone.useDaylightTime() && timeZone.inDaylightTime(this.getDate())) - { - hours += sign.equals("+") ? 1 : -1; - } - } - catch (ParseException e) - { - // we'll do our best and ignore daylight savings - } - - return "GMT" + sign + convert(hours) + ":" + convert(minutes); - } - - private String convert(int time) - { - if (time < 10) - { - return "0" + time; - } - - return Integer.toString(time); - } - - public Date getDate() - throws ParseException - { - SimpleDateFormat dateF; - String d = time; - - if (time.endsWith("Z")) - { - if (hasFractionalSeconds()) - { - dateF = new SimpleDateFormat("yyyyMMddHHmmss.SSS'Z'"); - } - else - { - dateF = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); - } - - dateF.setTimeZone(new SimpleTimeZone(0, "Z")); - } - else if (time.indexOf('-') > 0 || time.indexOf('+') > 0) - { - d = this.getTime(); - if (hasFractionalSeconds()) - { - dateF = new SimpleDateFormat("yyyyMMddHHmmss.SSSz"); - } - else - { - dateF = new SimpleDateFormat("yyyyMMddHHmmssz"); - } - - dateF.setTimeZone(new SimpleTimeZone(0, "Z")); - } - else - { - if (hasFractionalSeconds()) - { - dateF = new SimpleDateFormat("yyyyMMddHHmmss.SSS"); - } - else - { - dateF = new SimpleDateFormat("yyyyMMddHHmmss"); - } - - dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID())); - } - - if (hasFractionalSeconds()) - { - // java misinterprets extra digits as being milliseconds... - String frac = d.substring(14); - int index; - for (index = 1; index < frac.length(); index++) - { - char ch = frac.charAt(index); - if (!('0' <= ch && ch <= '9')) - { - break; - } - } - if (index - 1 > 3) - { - frac = frac.substring(0, 4) + frac.substring(index); - d = d.substring(0, 14) + frac; - } - } - - return dateF.parse(d); - } - - private boolean hasFractionalSeconds() - { - return time.indexOf('.') == 14; - } - - private byte[] getOctets() - { - char[] cs = time.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(GENERALIZED_TIME, this.getOctets()); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERGeneralizedTime)) - { - return false; - } - - return time.equals(((DERGeneralizedTime)o).time); - } - - public int hashCode() - { - return time.hashCode(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERIA5String.java b/src/org/thoughtcrime/bouncycastle/asn1/DERIA5String.java deleted file mode 100644 index 9fd828f3d1..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERIA5String.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER IA5String object - this is an ascii string. - */ -public class DERIA5String - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a IA5 string from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERIA5String getInstance( - Object obj) - { - if (obj == null || obj instanceof DERIA5String) - { - return (DERIA5String)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERIA5String(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an IA5 String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERIA5String getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - with bytes. - */ - public DERIA5String( - byte[] string) - { - char[] cs = new char[string.length]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - - this.string = new String(cs); - } - - /** - * basic constructor - without validation. - */ - public DERIA5String( - String string) - { - this(string, false); - } - - /** - * Constructor with optional validation. - * - * @param string the base string to wrap. - * @param validate whether or not to check the string. - * @throws IllegalArgumentException if validate is true and the string - * contains characters that should not be in an IA5String. - */ - public DERIA5String( - String string, - boolean validate) - { - if (string == null) - { - throw new NullPointerException("string cannot be null"); - } - if (validate && !isIA5String(string)) - { - throw new IllegalArgumentException("string contains illegal characters"); - } - - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(IA5_STRING, this.getOctets()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERIA5String)) - { - return false; - } - - DERIA5String s = (DERIA5String)o; - - return this.getString().equals(s.getString()); - } - - /** - * return true if the passed in String can be represented without - * loss as an IA5String, false otherwise. - * - * @return true if in printable set, false otherwise. - */ - public static boolean isIA5String( - String str) - { - for (int i = str.length() - 1; i >= 0; i--) - { - char ch = str.charAt(i); - - if (ch > 0x007f) - { - return false; - } - } - - return true; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERInteger.java b/src/org/thoughtcrime/bouncycastle/asn1/DERInteger.java deleted file mode 100644 index d650f6e417..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERInteger.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.math.BigInteger; - -import org.bouncycastle.util.Arrays; - -public class DERInteger - extends ASN1Object -{ - byte[] bytes; - - /** - * return an integer from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERInteger getInstance( - Object obj) - { - if (obj == null || obj instanceof DERInteger) - { - return (DERInteger)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERInteger(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an Integer from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERInteger getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - public DERInteger( - int value) - { - bytes = BigInteger.valueOf(value).toByteArray(); - } - - public DERInteger( - BigInteger value) - { - bytes = value.toByteArray(); - } - - public DERInteger( - byte[] bytes) - { - this.bytes = bytes; - } - - public BigInteger getValue() - { - return new BigInteger(bytes); - } - - /** - * in some cases positive values get crammed into a space, - * that's not quite big enough... - */ - public BigInteger getPositiveValue() - { - return new BigInteger(1, bytes); - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(INTEGER, bytes); - } - - public int hashCode() - { - int value = 0; - - for (int i = 0; i != bytes.length; i++) - { - value ^= (bytes[i] & 0xff) << (i % 4); - } - - return value; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERInteger)) - { - return false; - } - - DERInteger other = (DERInteger)o; - - return Arrays.areEqual(bytes, other.bytes); - } - - public String toString() - { - return getValue().toString(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERNull.java b/src/org/thoughtcrime/bouncycastle/asn1/DERNull.java deleted file mode 100644 index ab959da1e3..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERNull.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * A NULL object. - */ -public class DERNull - extends ASN1Null -{ - public static final DERNull INSTANCE = new DERNull(); - - byte[] zeroBytes = new byte[0]; - - public DERNull() - { - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(NULL, zeroBytes); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERNumericString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERNumericString.java deleted file mode 100644 index dbf321e846..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERNumericString.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }. - */ -public class DERNumericString - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a Numeric string from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERNumericString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERNumericString) - { - return (DERNumericString)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERNumericString(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an Numeric String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERNumericString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - with bytes. - */ - public DERNumericString( - byte[] string) - { - char[] cs = new char[string.length]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - - this.string = new String(cs); - } - - /** - * basic constructor - without validation.. - */ - public DERNumericString( - String string) - { - this(string, false); - } - - /** - * Constructor with optional validation. - * - * @param string the base string to wrap. - * @param validate whether or not to check the string. - * @throws IllegalArgumentException if validate is true and the string - * contains characters that should not be in a NumericString. - */ - public DERNumericString( - String string, - boolean validate) - { - if (validate && !isNumericString(string)) - { - throw new IllegalArgumentException("string contains illegal characters"); - } - - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(NUMERIC_STRING, this.getOctets()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERNumericString)) - { - return false; - } - - DERNumericString s = (DERNumericString)o; - - return this.getString().equals(s.getString()); - } - - /** - * Return true if the string can be represented as a NumericString ('0'..'9', ' ') - * - * @param str string to validate. - * @return true if numeric, fale otherwise. - */ - public static boolean isNumericString( - String str) - { - for (int i = str.length() - 1; i >= 0; i--) - { - char ch = str.charAt(i); - - if (ch > 0x007f) - { - return false; - } - - if (('0' <= ch && ch <= '9') || ch == ' ') - { - continue; - } - - return false; - } - - return true; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERObject.java b/src/org/thoughtcrime/bouncycastle/asn1/DERObject.java deleted file mode 100644 index bc49a3f1f9..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERObject.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public abstract class DERObject - extends ASN1Encodable - implements DERTags -{ - public DERObject toASN1Object() - { - return this; - } - - public abstract int hashCode(); - - public abstract boolean equals(Object o); - - abstract void encode(DEROutputStream out) - throws IOException; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERObjectIdentifier.java b/src/org/thoughtcrime/bouncycastle/asn1/DERObjectIdentifier.java deleted file mode 100644 index 24dc9f548b..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERObjectIdentifier.java +++ /dev/null @@ -1,293 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigInteger; - -public class DERObjectIdentifier - extends ASN1Object -{ - String identifier; - - /** - * return an OID from the passed in object - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERObjectIdentifier getInstance( - Object obj) - { - if (obj == null || obj instanceof DERObjectIdentifier) - { - return (DERObjectIdentifier)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERObjectIdentifier(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an Object Identifier from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERObjectIdentifier getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - - DERObjectIdentifier( - byte[] bytes) - { - StringBuffer objId = new StringBuffer(); - long value = 0; - BigInteger bigValue = null; - boolean first = true; - - for (int i = 0; i != bytes.length; i++) - { - int b = bytes[i] & 0xff; - - if (value < 0x80000000000000L) - { - value = value * 128 + (b & 0x7f); - if ((b & 0x80) == 0) // end of number reached - { - if (first) - { - switch ((int)value / 40) - { - case 0: - objId.append('0'); - break; - case 1: - objId.append('1'); - value -= 40; - break; - default: - objId.append('2'); - value -= 80; - } - first = false; - } - - objId.append('.'); - objId.append(value); - value = 0; - } - } - else - { - if (bigValue == null) - { - bigValue = BigInteger.valueOf(value); - } - bigValue = bigValue.shiftLeft(7); - bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f)); - if ((b & 0x80) == 0) - { - objId.append('.'); - objId.append(bigValue); - bigValue = null; - value = 0; - } - } - } - - this.identifier = objId.toString(); - } - - public DERObjectIdentifier( - String identifier) - { - if (!isValidIdentifier(identifier)) - { - throw new IllegalArgumentException("string " + identifier + " not an OID"); - } - - this.identifier = identifier; - } - - public String getId() - { - return identifier; - } - - private void writeField( - OutputStream out, - long fieldValue) - throws IOException - { - if (fieldValue >= (1L << 7)) - { - if (fieldValue >= (1L << 14)) - { - if (fieldValue >= (1L << 21)) - { - if (fieldValue >= (1L << 28)) - { - if (fieldValue >= (1L << 35)) - { - if (fieldValue >= (1L << 42)) - { - if (fieldValue >= (1L << 49)) - { - if (fieldValue >= (1L << 56)) - { - out.write((int)(fieldValue >> 56) | 0x80); - } - out.write((int)(fieldValue >> 49) | 0x80); - } - out.write((int)(fieldValue >> 42) | 0x80); - } - out.write((int)(fieldValue >> 35) | 0x80); - } - out.write((int)(fieldValue >> 28) | 0x80); - } - out.write((int)(fieldValue >> 21) | 0x80); - } - out.write((int)(fieldValue >> 14) | 0x80); - } - out.write((int)(fieldValue >> 7) | 0x80); - } - out.write((int)fieldValue & 0x7f); - } - - private void writeField( - OutputStream out, - BigInteger fieldValue) - throws IOException - { - int byteCount = (fieldValue.bitLength()+6)/7; - if (byteCount == 0) - { - out.write(0); - } - else - { - BigInteger tmpValue = fieldValue; - byte[] tmp = new byte[byteCount]; - for (int i = byteCount-1; i >= 0; i--) - { - tmp[i] = (byte) ((tmpValue.intValue() & 0x7f) | 0x80); - tmpValue = tmpValue.shiftRight(7); - } - tmp[byteCount-1] &= 0x7f; - out.write(tmp); - } - - } - - void encode( - DEROutputStream out) - throws IOException - { - OIDTokenizer tok = new OIDTokenizer(identifier); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - writeField(bOut, - Integer.parseInt(tok.nextToken()) * 40 - + Integer.parseInt(tok.nextToken())); - - while (tok.hasMoreTokens()) - { - String token = tok.nextToken(); - if (token.length() < 18) - { - writeField(bOut, Long.parseLong(token)); - } - else - { - writeField(bOut, new BigInteger(token)); - } - } - - dOut.close(); - - byte[] bytes = bOut.toByteArray(); - - out.writeEncoded(OBJECT_IDENTIFIER, bytes); - } - - public int hashCode() - { - return identifier.hashCode(); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERObjectIdentifier)) - { - return false; - } - - return identifier.equals(((DERObjectIdentifier)o).identifier); - } - - public String toString() - { - return getId(); - } - - private static boolean isValidIdentifier( - String identifier) - { - if (identifier.length() < 3 - || identifier.charAt(1) != '.') - { - return false; - } - - char first = identifier.charAt(0); - if (first < '0' || first > '2') - { - return false; - } - - boolean periodAllowed = false; - for (int i = identifier.length() - 1; i >= 2; i--) - { - char ch = identifier.charAt(i); - - if ('0' <= ch && ch <= '9') - { - periodAllowed = true; - continue; - } - - if (ch == '.') - { - if (!periodAllowed) - { - return false; - } - - periodAllowed = false; - continue; - } - - return false; - } - - return periodAllowed; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEROctetString.java b/src/org/thoughtcrime/bouncycastle/asn1/DEROctetString.java deleted file mode 100644 index 8bde66be36..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEROctetString.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class DEROctetString - extends ASN1OctetString -{ - /** - * @param string the octets making up the octet string. - */ - public DEROctetString( - byte[] string) - { - super(string); - } - - public DEROctetString( - DEREncodable obj) - { - super(obj); - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(OCTET_STRING, string); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEROctetStringParser.java b/src/org/thoughtcrime/bouncycastle/asn1/DEROctetStringParser.java deleted file mode 100644 index 9e799b5c3c..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEROctetStringParser.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.InputStream; -import java.io.IOException; - -public class DEROctetStringParser - implements ASN1OctetStringParser -{ - private DefiniteLengthInputStream stream; - - DEROctetStringParser( - DefiniteLengthInputStream stream) - { - this.stream = stream; - } - - public InputStream getOctetStream() - { - return stream; - } - - public DERObject getDERObject() - { - try - { - return new DEROctetString(stream.toByteArray()); - } - catch (IOException e) - { - throw new IllegalStateException("IOException converting stream to byte array: " + e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DEROutputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/DEROutputStream.java deleted file mode 100644 index 5c4da9dfbb..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DEROutputStream.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class DEROutputStream - extends FilterOutputStream implements DERTags -{ - public DEROutputStream( - OutputStream os) - { - super(os); - } - - private void writeLength( - int length) - throws IOException - { - if (length > 127) - { - int size = 1; - int val = length; - - while ((val >>>= 8) != 0) - { - size++; - } - - write((byte)(size | 0x80)); - - for (int i = (size - 1) * 8; i >= 0; i -= 8) - { - write((byte)(length >> i)); - } - } - else - { - write((byte)length); - } - } - - void writeEncoded( - int tag, - byte[] bytes) - throws IOException - { - write(tag); - writeLength(bytes.length); - write(bytes); - } - - void writeTag(int flags, int tagNo) - throws IOException - { - if (tagNo < 31) - { - write(flags | tagNo); - } - else - { - write(flags | 0x1f); - if (tagNo < 128) - { - write(tagNo); - } - else - { - byte[] stack = new byte[5]; - int pos = stack.length; - - stack[--pos] = (byte)(tagNo & 0x7F); - - do - { - tagNo >>= 7; - stack[--pos] = (byte)(tagNo & 0x7F | 0x80); - } - while (tagNo > 127); - - write(stack, pos, stack.length - pos); - } - } - } - - void writeEncoded(int flags, int tagNo, byte[] bytes) - throws IOException - { - writeTag(flags, tagNo); - writeLength(bytes.length); - write(bytes); - } - - protected void writeNull() - throws IOException - { - write(NULL); - write(0x00); - } - - public void write(byte[] buf) - throws IOException - { - out.write(buf, 0, buf.length); - } - - public void write(byte[] buf, int offSet, int len) - throws IOException - { - out.write(buf, offSet, len); - } - - public void writeObject( - Object obj) - throws IOException - { - if (obj == null) - { - writeNull(); - } - else if (obj instanceof DERObject) - { - ((DERObject)obj).encode(this); - } - else if (obj instanceof DEREncodable) - { - ((DEREncodable)obj).getDERObject().encode(this); - } - else - { - throw new IOException("object not DEREncodable"); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERPrintableString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERPrintableString.java deleted file mode 100644 index f9b3aa2ae9..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERPrintableString.java +++ /dev/null @@ -1,204 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER PrintableString object. - */ -public class DERPrintableString - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a printable string from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERPrintableString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERPrintableString) - { - return (DERPrintableString)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERPrintableString(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a Printable String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERPrintableString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - byte encoded string. - */ - public DERPrintableString( - byte[] string) - { - char[] cs = new char[string.length]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - - this.string = new String(cs); - } - - /** - * basic constructor - this does not validate the string - */ - public DERPrintableString( - String string) - { - this(string, false); - } - - /** - * Constructor with optional validation. - * - * @param string the base string to wrap. - * @param validate whether or not to check the string. - * @throws IllegalArgumentException if validate is true and the string - * contains characters that should not be in a PrintableString. - */ - public DERPrintableString( - String string, - boolean validate) - { - if (validate && !isPrintableString(string)) - { - throw new IllegalArgumentException("string contains illegal characters"); - } - - this.string = string; - } - - public String getString() - { - return string; - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(PRINTABLE_STRING, this.getOctets()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERPrintableString)) - { - return false; - } - - DERPrintableString s = (DERPrintableString)o; - - return this.getString().equals(s.getString()); - } - - public String toString() - { - return string; - } - - /** - * return true if the passed in String can be represented without - * loss as a PrintableString, false otherwise. - * - * @return true if in printable set, false otherwise. - */ - public static boolean isPrintableString( - String str) - { - for (int i = str.length() - 1; i >= 0; i--) - { - char ch = str.charAt(i); - - if (ch > 0x007f) - { - return false; - } - - if ('a' <= ch && ch <= 'z') - { - continue; - } - - if ('A' <= ch && ch <= 'Z') - { - continue; - } - - if ('0' <= ch && ch <= '9') - { - continue; - } - - switch (ch) - { - case ' ': - case '\'': - case '(': - case ')': - case '+': - case '-': - case '.': - case ':': - case '=': - case '?': - case '/': - case ',': - continue; - } - - return false; - } - - return true; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERSequence.java b/src/org/thoughtcrime/bouncycastle/asn1/DERSequence.java deleted file mode 100644 index 4d4431e7f4..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERSequence.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; - -public class DERSequence - extends ASN1Sequence -{ - /** - * create an empty sequence - */ - public DERSequence() - { - } - - /** - * create a sequence containing one object - */ - public DERSequence( - DEREncodable obj) - { - this.addObject(obj); - } - - /** - * create a sequence containing a vector of objects. - */ - public DERSequence( - DEREncodableVector v) - { - for (int i = 0; i != v.size(); i++) - { - this.addObject(v.get(i)); - } - } - - /** - * create a sequence containing an array of objects. - */ - public DERSequence( - ASN1Encodable[] a) - { - for (int i = 0; i != a.length; i++) - { - this.addObject(a[i]); - } - } - - /* - * A note on the implementation: - *

- * As DER requires the constructed, definite-length model to - * be used for structured types, this varies slightly from the - * ASN.1 descriptions given. Rather than just outputing SEQUENCE, - * we also have to specify CONSTRUCTED, and the objects length. - */ - void encode( - DEROutputStream out) - throws IOException - { - // TODO Intermediate buffer could be avoided if we could calculate expected length - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - Enumeration e = this.getObjects(); - - while (e.hasMoreElements()) - { - Object obj = e.nextElement(); - - dOut.writeObject(obj); - } - - dOut.close(); - - byte[] bytes = bOut.toByteArray(); - - out.writeEncoded(SEQUENCE | CONSTRUCTED, bytes); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERSequenceParser.java b/src/org/thoughtcrime/bouncycastle/asn1/DERSequenceParser.java deleted file mode 100644 index 5cc21cf1e6..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERSequenceParser.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class DERSequenceParser - implements ASN1SequenceParser -{ - private ASN1StreamParser _parser; - - DERSequenceParser(ASN1StreamParser parser) - { - this._parser = parser; - } - - public DEREncodable readObject() - throws IOException - { - return _parser.readObject(); - } - - public DERObject getDERObject() - { - try - { - return new DERSequence(_parser.readVector()); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERSet.java b/src/org/thoughtcrime/bouncycastle/asn1/DERSet.java deleted file mode 100644 index 64bd211c54..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERSet.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; - -/** - * A DER encoded set object - */ -public class DERSet - extends ASN1Set -{ - /** - * create an empty set - */ - public DERSet() - { - } - - /** - * @param obj - a single object that makes up the set. - */ - public DERSet( - DEREncodable obj) - { - this.addObject(obj); - } - - /** - * @param v - a vector of objects making up the set. - */ - public DERSet( - DEREncodableVector v) - { - this(v, true); - } - - /** - * create a set from an array of objects. - */ - public DERSet( - ASN1Encodable[] a) - { - for (int i = 0; i != a.length; i++) - { - this.addObject(a[i]); - } - - this.sort(); - } - - /** - * @param v - a vector of objects making up the set. - */ - DERSet( - DEREncodableVector v, - boolean needsSorting) - { - for (int i = 0; i != v.size(); i++) - { - this.addObject(v.get(i)); - } - - if (needsSorting) - { - this.sort(); - } - } - - /* - * A note on the implementation: - *

- * As DER requires the constructed, definite-length model to - * be used for structured types, this varies slightly from the - * ASN.1 descriptions given. Rather than just outputing SET, - * we also have to specify CONSTRUCTED, and the objects length. - */ - void encode( - DEROutputStream out) - throws IOException - { - // TODO Intermediate buffer could be avoided if we could calculate expected length - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - Enumeration e = this.getObjects(); - - while (e.hasMoreElements()) - { - Object obj = e.nextElement(); - - dOut.writeObject(obj); - } - - dOut.close(); - - byte[] bytes = bOut.toByteArray(); - - out.writeEncoded(SET | CONSTRUCTED, bytes); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERSetParser.java b/src/org/thoughtcrime/bouncycastle/asn1/DERSetParser.java deleted file mode 100644 index 9fdc982bb4..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERSetParser.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -public class DERSetParser - implements ASN1SetParser -{ - private ASN1StreamParser _parser; - - DERSetParser(ASN1StreamParser parser) - { - this._parser = parser; - } - - public DEREncodable readObject() - throws IOException - { - return _parser.readObject(); - } - - public DERObject getDERObject() - { - try - { - return new DERSet(_parser.readVector(), false); - } - catch (IOException e) - { - throw new IllegalStateException(e.getMessage()); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERString.java deleted file mode 100644 index 99daa0d411..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERString.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -/** - * basic interface for DER string objects. - */ -public interface DERString -{ - public String getString(); -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERT61String.java b/src/org/thoughtcrime/bouncycastle/asn1/DERT61String.java deleted file mode 100644 index e87492467c..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERT61String.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER T61String (also the teletex string) - */ -public class DERT61String - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a T61 string from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERT61String getInstance( - Object obj) - { - if (obj == null || obj instanceof DERT61String) - { - return (DERT61String)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERT61String(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an T61 String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERT61String getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - with bytes. - */ - public DERT61String( - byte[] string) - { - char[] cs = new char[string.length]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - - this.string = new String(cs); - } - - /** - * basic constructor - with string. - */ - public DERT61String( - String string) - { - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(T61_STRING, this.getOctets()); - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERT61String)) - { - return false; - } - - return this.getString().equals(((DERT61String)o).getString()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERTaggedObject.java b/src/org/thoughtcrime/bouncycastle/asn1/DERTaggedObject.java deleted file mode 100644 index 98b2fa42e7..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERTaggedObject.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER TaggedObject - in ASN.1 notation this is any object preceded by - * a [n] where n is some number - these are assumed to follow the construction - * rules (as with sequences). - */ -public class DERTaggedObject - extends ASN1TaggedObject -{ - private static final byte[] ZERO_BYTES = new byte[0]; - - /** - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public DERTaggedObject( - int tagNo, - DEREncodable obj) - { - super(tagNo, obj); - } - - /** - * @param explicit true if an explicitly tagged object. - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - public DERTaggedObject( - boolean explicit, - int tagNo, - DEREncodable obj) - { - super(explicit, tagNo, obj); - } - - /** - * create an implicitly tagged object that contains a zero - * length sequence. - */ - public DERTaggedObject( - int tagNo) - { - super(false, tagNo, new DERSequence()); - } - - void encode( - DEROutputStream out) - throws IOException - { - if (!empty) - { - byte[] bytes = obj.getDERObject().getEncoded(DER); - - if (explicit) - { - out.writeEncoded(CONSTRUCTED | TAGGED, tagNo, bytes); - } - else - { - // - // need to mark constructed types... - // - int flags; - if ((bytes[0] & CONSTRUCTED) != 0) - { - flags = CONSTRUCTED | TAGGED; - } - else - { - flags = TAGGED; - } - - out.writeTag(flags, tagNo); - out.write(bytes, 1, bytes.length - 1); - } - } - else - { - out.writeEncoded(CONSTRUCTED | TAGGED, tagNo, ZERO_BYTES); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERTags.java b/src/org/thoughtcrime/bouncycastle/asn1/DERTags.java deleted file mode 100644 index fc55c92bcc..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERTags.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -public interface DERTags -{ - public static final int BOOLEAN = 0x01; - public static final int INTEGER = 0x02; - public static final int BIT_STRING = 0x03; - public static final int OCTET_STRING = 0x04; - public static final int NULL = 0x05; - public static final int OBJECT_IDENTIFIER = 0x06; - public static final int EXTERNAL = 0x08; - public static final int ENUMERATED = 0x0a; - public static final int SEQUENCE = 0x10; - public static final int SEQUENCE_OF = 0x10; // for completeness - public static final int SET = 0x11; - public static final int SET_OF = 0x11; // for completeness - - - public static final int NUMERIC_STRING = 0x12; - public static final int PRINTABLE_STRING = 0x13; - public static final int T61_STRING = 0x14; - public static final int VIDEOTEX_STRING = 0x15; - public static final int IA5_STRING = 0x16; - public static final int UTC_TIME = 0x17; - public static final int GENERALIZED_TIME = 0x18; - public static final int GRAPHIC_STRING = 0x19; - public static final int VISIBLE_STRING = 0x1a; - public static final int GENERAL_STRING = 0x1b; - public static final int UNIVERSAL_STRING = 0x1c; - public static final int BMP_STRING = 0x1e; - public static final int UTF8_STRING = 0x0c; - - public static final int CONSTRUCTED = 0x20; - public static final int APPLICATION = 0x40; - public static final int TAGGED = 0x80; -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERUTCTime.java b/src/org/thoughtcrime/bouncycastle/asn1/DERUTCTime.java deleted file mode 100644 index 09a0bca1bb..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERUTCTime.java +++ /dev/null @@ -1,254 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.SimpleTimeZone; - -/** - * UTC time object. - */ -public class DERUTCTime - extends ASN1Object -{ - String time; - - /** - * return an UTC Time from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERUTCTime getInstance( - Object obj) - { - if (obj == null || obj instanceof DERUTCTime) - { - return (DERUTCTime)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERUTCTime(((ASN1OctetString)obj).getOctets()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return an UTC Time from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERUTCTime getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were - * never encoded. When you're creating one of these objects from scratch, that's - * what you want to use, otherwise we'll try to deal with whatever gets read from - * the input stream... (this is why the input format is different from the getTime() - * method output). - *

- * - * @param time the time string. - */ - public DERUTCTime( - String time) - { - this.time = time; - try - { - this.getDate(); - } - catch (ParseException e) - { - throw new IllegalArgumentException("invalid date string: " + e.getMessage()); - } - } - - /** - * base constructer from a java.util.date object - */ - public DERUTCTime( - Date time) - { - SimpleDateFormat dateF = new SimpleDateFormat("yyMMddHHmmss'Z'"); - - dateF.setTimeZone(new SimpleTimeZone(0,"Z")); - - this.time = dateF.format(time); - } - - DERUTCTime( - byte[] bytes) - { - // - // explicitly convert to characters - // - char[] dateC = new char[bytes.length]; - - for (int i = 0; i != dateC.length; i++) - { - dateC[i] = (char)(bytes[i] & 0xff); - } - - this.time = new String(dateC); - } - - /** - * return the time as a date based on whatever a 2 digit year will return. For - * standardised processing use getAdjustedDate(). - * - * @return the resulting date - * @exception ParseException if the date string cannot be parsed. - */ - public Date getDate() - throws ParseException - { - SimpleDateFormat dateF = new SimpleDateFormat("yyMMddHHmmssz"); - - return dateF.parse(getTime()); - } - - /** - * return the time as an adjusted date - * in the range of 1950 - 2049. - * - * @return a date in the range of 1950 to 2049. - * @exception ParseException if the date string cannot be parsed. - */ - public Date getAdjustedDate() - throws ParseException - { - SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssz"); - - dateF.setTimeZone(new SimpleTimeZone(0, "Z")); - - return dateF.parse(getAdjustedTime()); - } - - /** - * return the time - always in the form of - * YYMMDDhhmmssGMT(+hh:mm|-hh:mm). - *

- * Normally in a certificate we would expect "Z" rather than "GMT", - * however adding the "GMT" means we can just use: - *

-     *     dateF = new SimpleDateFormat("yyMMddHHmmssz");
-     * 
- * To read in the time and get a date which is compatible with our local - * time zone. - *

- * Note: In some cases, due to the local date processing, this - * may lead to unexpected results. If you want to stick the normal - * convention of 1950 to 2049 use the getAdjustedTime() method. - */ - public String getTime() - { - // - // standardise the format. - // - if (time.indexOf('-') < 0 && time.indexOf('+') < 0) - { - if (time.length() == 11) - { - return time.substring(0, 10) + "00GMT+00:00"; - } - else - { - return time.substring(0, 12) + "GMT+00:00"; - } - } - else - { - int index = time.indexOf('-'); - if (index < 0) - { - index = time.indexOf('+'); - } - String d = time; - - if (index == time.length() - 3) - { - d += "00"; - } - - if (index == 10) - { - return d.substring(0, 10) + "00GMT" + d.substring(10, 13) + ":" + d.substring(13, 15); - } - else - { - return d.substring(0, 12) + "GMT" + d.substring(12, 15) + ":" + d.substring(15, 17); - } - } - } - - /** - * return a time string as an adjusted date with a 4 digit year. This goes - * in the range of 1950 - 2049. - */ - public String getAdjustedTime() - { - String d = this.getTime(); - - if (d.charAt(0) < '5') - { - return "20" + d; - } - else - { - return "19" + d; - } - } - - private byte[] getOctets() - { - char[] cs = time.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(UTC_TIME, this.getOctets()); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERUTCTime)) - { - return false; - } - - return time.equals(((DERUTCTime)o).time); - } - - public int hashCode() - { - return time.hashCode(); - } - - public String toString() - { - return time; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERUTF8String.java b/src/org/thoughtcrime/bouncycastle/asn1/DERUTF8String.java deleted file mode 100644 index 6c9320b3f6..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERUTF8String.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.Strings; - -import java.io.IOException; - -/** - * DER UTF8String object. - */ -public class DERUTF8String - extends ASN1Object - implements DERString -{ - String string; - - /** - * return an UTF8 string from the passed in object. - * - * @exception IllegalArgumentException - * if the object cannot be converted. - */ - public static DERUTF8String getInstance(Object obj) - { - if (obj == null || obj instanceof DERUTF8String) - { - return (DERUTF8String)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERUTF8String(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " - + obj.getClass().getName()); - } - - /** - * return an UTF8 String from a tagged object. - * - * @param obj - * the tagged object holding the object we want - * @param explicit - * true if the object is meant to be explicitly tagged false - * otherwise. - * @exception IllegalArgumentException - * if the tagged object cannot be converted. - */ - public static DERUTF8String getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - byte encoded string. - */ - DERUTF8String(byte[] string) - { - this.string = Strings.fromUTF8ByteArray(string); - } - - /** - * basic constructor - */ - public DERUTF8String(String string) - { - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public int hashCode() - { - return this.getString().hashCode(); - } - - boolean asn1Equals(DERObject o) - { - if (!(o instanceof DERUTF8String)) - { - return false; - } - - DERUTF8String s = (DERUTF8String)o; - - return this.getString().equals(s.getString()); - } - - void encode(DEROutputStream out) - throws IOException - { - out.writeEncoded(UTF8_STRING, Strings.toUTF8ByteArray(string)); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERUniversalString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERUniversalString.java deleted file mode 100644 index 810d4183e7..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERUniversalString.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * DER UniversalString object. - */ -public class DERUniversalString - extends ASN1Object - implements DERString -{ - private static final char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - private byte[] string; - - /** - * return a Universal String from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERUniversalString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERUniversalString) - { - return (DERUniversalString)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERUniversalString(((ASN1OctetString)obj).getOctets()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a Universal String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERUniversalString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - byte encoded string. - */ - public DERUniversalString( - byte[] string) - { - this.string = string; - } - - public String getString() - { - StringBuffer buf = new StringBuffer("#"); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - try - { - aOut.writeObject(this); - } - catch (IOException e) - { - throw new RuntimeException("internal error encoding BitString"); - } - - byte[] string = bOut.toByteArray(); - - for (int i = 0; i != string.length; i++) - { - buf.append(table[(string[i] >>> 4) & 0xf]); - buf.append(table[string[i] & 0xf]); - } - - return buf.toString(); - } - - public String toString() - { - return getString(); - } - - public byte[] getOctets() - { - return string; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(UNIVERSAL_STRING, this.getOctets()); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERUniversalString)) - { - return false; - } - - return this.getString().equals(((DERUniversalString)o).getString()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERUnknownTag.java b/src/org/thoughtcrime/bouncycastle/asn1/DERUnknownTag.java deleted file mode 100644 index 74192c22c5..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERUnknownTag.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.Arrays; - -import java.io.IOException; - -/** - * We insert one of these when we find a tag we don't recognise. - */ -public class DERUnknownTag - extends DERObject -{ - private boolean isConstructed; - private int tag; - private byte[] data; - - /** - * @param tag the tag value. - * @param data the contents octets. - */ - public DERUnknownTag( - int tag, - byte[] data) - { - this(false, tag, data); - } - - public DERUnknownTag( - boolean isConstructed, - int tag, - byte[] data) - { - this.isConstructed = isConstructed; - this.tag = tag; - this.data = data; - } - - public boolean isConstructed() - { - return isConstructed; - } - - public int getTag() - { - return tag; - } - - public byte[] getData() - { - return data; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(isConstructed ? DERTags.CONSTRUCTED : 0, tag, data); - } - - public boolean equals( - Object o) - { - if (!(o instanceof DERUnknownTag)) - { - return false; - } - - DERUnknownTag other = (DERUnknownTag)o; - - return isConstructed == other.isConstructed - && tag == other.tag - && Arrays.areEqual(data, other.data); - } - - public int hashCode() - { - return (isConstructed ? ~0 : 0) ^ tag ^ Arrays.hashCode(data); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DERVisibleString.java b/src/org/thoughtcrime/bouncycastle/asn1/DERVisibleString.java deleted file mode 100644 index 65827b45ee..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DERVisibleString.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; - -/** - * DER VisibleString object. - */ -public class DERVisibleString - extends ASN1Object - implements DERString -{ - String string; - - /** - * return a Visible String from the passed in object. - * - * @exception IllegalArgumentException if the object cannot be converted. - */ - public static DERVisibleString getInstance( - Object obj) - { - if (obj == null || obj instanceof DERVisibleString) - { - return (DERVisibleString)obj; - } - - if (obj instanceof ASN1OctetString) - { - return new DERVisibleString(((ASN1OctetString)obj).getOctets()); - } - - if (obj instanceof ASN1TaggedObject) - { - return getInstance(((ASN1TaggedObject)obj).getObject()); - } - - throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); - } - - /** - * return a Visible String from a tagged object. - * - * @param obj the tagged object holding the object we want - * @param explicit true if the object is meant to be explicitly - * tagged false otherwise. - * @exception IllegalArgumentException if the tagged object cannot - * be converted. - */ - public static DERVisibleString getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(obj.getObject()); - } - - /** - * basic constructor - byte encoded string. - */ - public DERVisibleString( - byte[] string) - { - char[] cs = new char[string.length]; - - for (int i = 0; i != cs.length; i++) - { - cs[i] = (char)(string[i] & 0xff); - } - - this.string = new String(cs); - } - - /** - * basic constructor - */ - public DERVisibleString( - String string) - { - this.string = string; - } - - public String getString() - { - return string; - } - - public String toString() - { - return string; - } - - public byte[] getOctets() - { - char[] cs = string.toCharArray(); - byte[] bs = new byte[cs.length]; - - for (int i = 0; i != cs.length; i++) - { - bs[i] = (byte)cs[i]; - } - - return bs; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(VISIBLE_STRING, this.getOctets()); - } - - boolean asn1Equals( - DERObject o) - { - if (!(o instanceof DERVisibleString)) - { - return false; - } - - return this.getString().equals(((DERVisibleString)o).getString()); - } - - public int hashCode() - { - return this.getString().hashCode(); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/DefiniteLengthInputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/DefiniteLengthInputStream.java deleted file mode 100644 index 9e33a92856..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/DefiniteLengthInputStream.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import org.bouncycastle.util.io.Streams; - -import java.io.EOFException; -import java.io.InputStream; -import java.io.IOException; - -class DefiniteLengthInputStream - extends LimitedInputStream -{ - private static final byte[] EMPTY_BYTES = new byte[0]; - - private final int _originalLength; - private int _remaining; - - DefiniteLengthInputStream( - InputStream in, - int length) - { - super(in); - - if (length < 0) - { - throw new IllegalArgumentException("negative lengths not allowed"); - } - - this._originalLength = length; - this._remaining = length; - - if (length == 0) - { - setParentEofDetect(true); - } - } - - public int read() - throws IOException - { - if (_remaining == 0) - { - return -1; - } - - int b = _in.read(); - - if (b < 0) - { - throw new EOFException("DEF length " + _originalLength + " object truncated by " + _remaining); - } - - if (--_remaining == 0) - { - setParentEofDetect(true); - } - - return b; - } - - public int read(byte[] buf, int off, int len) - throws IOException - { - if (_remaining == 0) - { - return -1; - } - - int toRead = Math.min(len, _remaining); - int numRead = _in.read(buf, off, toRead); - - if (numRead < 0) - { - throw new EOFException("DEF length " + _originalLength + " object truncated by " + _remaining); - } - - if ((_remaining -= numRead) == 0) - { - setParentEofDetect(true); - } - - return numRead; - } - - byte[] toByteArray() - throws IOException - { - if (_remaining == 0) - { - return EMPTY_BYTES; - } - - byte[] bytes = new byte[_remaining]; - if ((_remaining -= Streams.readFully(_in, bytes)) != 0) - { - throw new EOFException("DEF length " + _originalLength + " object truncated by " + _remaining); - } - setParentEofDetect(true); - return bytes; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/IndefiniteLengthInputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/IndefiniteLengthInputStream.java deleted file mode 100644 index 40a9335619..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/IndefiniteLengthInputStream.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -class IndefiniteLengthInputStream - extends LimitedInputStream -{ - private int _b1; - private int _b2; - private boolean _eofReached = false; - private boolean _eofOn00 = true; - - IndefiniteLengthInputStream( - InputStream in) - throws IOException - { - super(in); - - _b1 = in.read(); - _b2 = in.read(); - - if (_b2 < 0) - { - // Corrupted stream - throw new EOFException(); - } - - checkForEof(); - } - - void setEofOn00( - boolean eofOn00) - { - _eofOn00 = eofOn00; - checkForEof(); - } - - private boolean checkForEof() - { - if (!_eofReached && _eofOn00 && (_b1 == 0x00 && _b2 == 0x00)) - { - _eofReached = true; - setParentEofDetect(true); - } - return _eofReached; - } - - public int read(byte[] b, int off, int len) - throws IOException - { - // Only use this optimisation if we aren't checking for 00 - if (_eofOn00 || len < 3) - { - return super.read(b, off, len); - } - - if (_eofReached) - { - return -1; - } - - int numRead = _in.read(b, off + 2, len - 2); - - if (numRead < 0) - { - // Corrupted stream - throw new EOFException(); - } - - b[off] = (byte)_b1; - b[off + 1] = (byte)_b2; - - _b1 = _in.read(); - _b2 = _in.read(); - - if (_b2 < 0) - { - // Corrupted stream - throw new EOFException(); - } - - return numRead + 2; - } - - public int read() - throws IOException - { - if (checkForEof()) - { - return -1; - } - - int b = _in.read(); - - if (b < 0) - { - // Corrupted stream - throw new EOFException(); - } - - int v = _b1; - - _b1 = _b2; - _b2 = b; - - return v; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/LazyDERConstructionEnumeration.java b/src/org/thoughtcrime/bouncycastle/asn1/LazyDERConstructionEnumeration.java deleted file mode 100644 index d1f77246eb..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/LazyDERConstructionEnumeration.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.util.Enumeration; -import java.io.IOException; - -class LazyDERConstructionEnumeration - implements Enumeration -{ - private ASN1InputStream aIn; - private Object nextObj; - - public LazyDERConstructionEnumeration(byte[] encoded) - { - aIn = new ASN1InputStream(encoded, true); - nextObj = readObject(); - } - - public boolean hasMoreElements() - { - return nextObj != null; - } - - public Object nextElement() - { - Object o = nextObj; - - nextObj = readObject(); - - return o; - } - - private Object readObject() - { - try - { - return aIn.readObject(); - } - catch (IOException e) - { - throw new IllegalStateException("malformed DER construction: " + e); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/LazyDERSequence.java b/src/org/thoughtcrime/bouncycastle/asn1/LazyDERSequence.java deleted file mode 100644 index 2e0ffe63ed..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/LazyDERSequence.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.IOException; -import java.util.Enumeration; - -public class LazyDERSequence - extends DERSequence -{ - private byte[] encoded; - private boolean parsed = false; - private int size = -1; - - LazyDERSequence( - byte[] encoded) - throws IOException - { - this.encoded = encoded; - } - - private void parse() - { - Enumeration en = new LazyDERConstructionEnumeration(encoded); - - while (en.hasMoreElements()) - { - addObject((DEREncodable)en.nextElement()); - } - - parsed = true; - } - - public DEREncodable getObjectAt(int index) - { - if (!parsed) - { - parse(); - } - - return super.getObjectAt(index); - } - - public Enumeration getObjects() - { - if (parsed) - { - return super.getObjects(); - } - - return new LazyDERConstructionEnumeration(encoded); - } - - public int size() - { - if (size < 0) - { - Enumeration en = new LazyDERConstructionEnumeration(encoded); - - size = 0; - while (en.hasMoreElements()) - { - en.nextElement(); - size++; - } - } - - return size; - } - - void encode( - DEROutputStream out) - throws IOException - { - out.writeEncoded(SEQUENCE | CONSTRUCTED, encoded); - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/LimitedInputStream.java b/src/org/thoughtcrime/bouncycastle/asn1/LimitedInputStream.java deleted file mode 100644 index abd8fa0386..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/LimitedInputStream.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -import java.io.InputStream; - -abstract class LimitedInputStream - extends InputStream -{ - protected final InputStream _in; - - LimitedInputStream( - InputStream in) - { - this._in = in; - } - - protected void setParentEofDetect(boolean on) - { - if (_in instanceof IndefiniteLengthInputStream) - { - ((IndefiniteLengthInputStream)_in).setEofOn00(on); - } - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/OIDTokenizer.java b/src/org/thoughtcrime/bouncycastle/asn1/OIDTokenizer.java deleted file mode 100644 index bd1d11592f..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/OIDTokenizer.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1; - -/** - * class for breaking up an OID into it's component tokens, ala - * java.util.StringTokenizer. We need this class as some of the - * lightweight Java environment don't support classes like - * StringTokenizer. - */ -public class OIDTokenizer -{ - private String oid; - private int index; - - public OIDTokenizer( - String oid) - { - this.oid = oid; - this.index = 0; - } - - public boolean hasMoreTokens() - { - return (index != -1); - } - - public String nextToken() - { - if (index == -1) - { - return null; - } - - String token; - int end = oid.indexOf('.', index); - - if (end == -1) - { - token = oid.substring(index); - index = -1; - return token; - } - - token = oid.substring(index, end); - - index = end + 1; - return token; - } -} diff --git a/src/org/thoughtcrime/bouncycastle/asn1/x9/X9IntegerConverter.java b/src/org/thoughtcrime/bouncycastle/asn1/x9/X9IntegerConverter.java deleted file mode 100644 index 9c67f3585f..0000000000 --- a/src/org/thoughtcrime/bouncycastle/asn1/x9/X9IntegerConverter.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.thoughtcrime.bouncycastle.asn1.x9; - -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECFieldElement; - -import java.math.BigInteger; - -public class X9IntegerConverter -{ - public int getByteLength( - ECCurve c) - { - return (c.getFieldSize() + 7) / 8; - } - - public int getByteLength( - ECFieldElement fe) - { - return (fe.getFieldSize() + 7) / 8; - } - - public byte[] integerToBytes( - BigInteger s, - int qLength) - { - byte[] bytes = s.toByteArray(); - - if (qLength < bytes.length) - { - byte[] tmp = new byte[qLength]; - - System.arraycopy(bytes, bytes.length - tmp.length, tmp, 0, tmp.length); - - return tmp; - } - else if (qLength > bytes.length) - { - byte[] tmp = new byte[qLength]; - - System.arraycopy(bytes, 0, tmp, tmp.length - bytes.length, bytes.length); - - return tmp; - } - - return bytes; - } -} diff --git a/src/org/thoughtcrime/securesms/ApplicationPreferencesActivity.java b/src/org/thoughtcrime/securesms/ApplicationPreferencesActivity.java index 443d07837a..6aff35cfc0 100644 --- a/src/org/thoughtcrime/securesms/ApplicationPreferencesActivity.java +++ b/src/org/thoughtcrime/securesms/ApplicationPreferencesActivity.java @@ -47,7 +47,7 @@ import com.actionbarsherlock.view.MenuItem; import com.google.android.gcm.GCMRegistrar; import org.thoughtcrime.securesms.contacts.ContactAccessor; import org.thoughtcrime.securesms.contacts.ContactIdentityManager; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.DynamicLanguage; diff --git a/src/org/thoughtcrime/securesms/AutoInitiateActivity.java b/src/org/thoughtcrime/securesms/AutoInitiateActivity.java index 99844bbc5b..03ee88c44f 100644 --- a/src/org/thoughtcrime/securesms/AutoInitiateActivity.java +++ b/src/org/thoughtcrime/securesms/AutoInitiateActivity.java @@ -26,9 +26,9 @@ import android.view.View; import android.widget.Button; import org.thoughtcrime.securesms.crypto.KeyExchangeInitiator; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; -import org.thoughtcrime.securesms.database.keys.RemoteKeyRecord; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.storage.LocalKeyRecord; +import org.whispersystems.textsecure.storage.RemoteKeyRecord; import org.thoughtcrime.securesms.protocol.Tag; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.MemoryCleaner; diff --git a/src/org/thoughtcrime/securesms/ConversationActivity.java b/src/org/thoughtcrime/securesms/ConversationActivity.java index 2225699d3a..e67bdc68cf 100644 --- a/src/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationActivity.java @@ -59,9 +59,10 @@ import org.thoughtcrime.securesms.contacts.ContactAccessor.ContactData; import org.thoughtcrime.securesms.contacts.ContactAccessor.NumberData; import org.thoughtcrime.securesms.crypto.KeyExchangeInitiator; import org.thoughtcrime.securesms.crypto.KeyExchangeProcessor; -import org.thoughtcrime.securesms.crypto.KeyUtil; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.DraftDatabase; import org.thoughtcrime.securesms.database.DraftDatabase.Draft; @@ -86,7 +87,6 @@ import org.thoughtcrime.securesms.util.CharacterCalculator; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.DynamicTheme; import org.thoughtcrime.securesms.util.EncryptedCharacterCalculator; -import org.thoughtcrime.securesms.util.InvalidMessageException; import org.thoughtcrime.securesms.util.MemoryCleaner; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.textsecure.util.Util; diff --git a/src/org/thoughtcrime/securesms/ConversationAdapter.java b/src/org/thoughtcrime/securesms/ConversationAdapter.java index 9f204f8a05..839a23f867 100644 --- a/src/org/thoughtcrime/securesms/ConversationAdapter.java +++ b/src/org/thoughtcrime/securesms/ConversationAdapter.java @@ -25,7 +25,7 @@ import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.CursorAdapter; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsSmsColumns; import org.thoughtcrime.securesms.database.MmsSmsDatabase; diff --git a/src/org/thoughtcrime/securesms/ConversationFragment.java b/src/org/thoughtcrime/securesms/ConversationFragment.java index 2727ad6cd7..c4e608cb9b 100644 --- a/src/org/thoughtcrime/securesms/ConversationFragment.java +++ b/src/org/thoughtcrime/securesms/ConversationFragment.java @@ -20,7 +20,7 @@ import android.widget.CursorAdapter; import com.actionbarsherlock.app.SherlockListFragment; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.loaders.ConversationLoader; import org.thoughtcrime.securesms.database.model.MessageRecord; diff --git a/src/org/thoughtcrime/securesms/ConversationItem.java b/src/org/thoughtcrime/securesms/ConversationItem.java index 294029bd70..9d3ae7f500 100644 --- a/src/org/thoughtcrime/securesms/ConversationItem.java +++ b/src/org/thoughtcrime/securesms/ConversationItem.java @@ -43,7 +43,7 @@ import android.webkit.MimeTypeMap; import org.thoughtcrime.securesms.contacts.ContactIdentityManager; import org.thoughtcrime.securesms.contacts.ContactPhotoFactory; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord; import org.thoughtcrime.securesms.database.model.MessageRecord; diff --git a/src/org/thoughtcrime/securesms/ConversationListActivity.java b/src/org/thoughtcrime/securesms/ConversationListActivity.java index ef7f3056c6..9de2d7029b 100644 --- a/src/org/thoughtcrime/securesms/ConversationListActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationListActivity.java @@ -23,6 +23,8 @@ import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.notifications.MessageNotifier; diff --git a/src/org/thoughtcrime/securesms/ConversationListAdapter.java b/src/org/thoughtcrime/securesms/ConversationListAdapter.java index 54ecc2ed6f..8755d69ba6 100644 --- a/src/org/thoughtcrime/securesms/ConversationListAdapter.java +++ b/src/org/thoughtcrime/securesms/ConversationListAdapter.java @@ -24,7 +24,7 @@ import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.CursorAdapter; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.database.model.ThreadRecord; diff --git a/src/org/thoughtcrime/securesms/ConversationListFragment.java b/src/org/thoughtcrime/securesms/ConversationListFragment.java index 2e516279b5..a602857c7c 100644 --- a/src/org/thoughtcrime/securesms/ConversationListFragment.java +++ b/src/org/thoughtcrime/securesms/ConversationListFragment.java @@ -33,7 +33,7 @@ import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.loaders.ConversationListLoader; import org.thoughtcrime.securesms.notifications.MessageNotifier; diff --git a/src/org/thoughtcrime/securesms/DatabaseUpgradeActivity.java b/src/org/thoughtcrime/securesms/DatabaseUpgradeActivity.java index 5c8d08556b..1bb540ba99 100644 --- a/src/org/thoughtcrime/securesms/DatabaseUpgradeActivity.java +++ b/src/org/thoughtcrime/securesms/DatabaseUpgradeActivity.java @@ -10,7 +10,7 @@ import android.util.Log; import android.view.View; import android.widget.ProgressBar; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.util.VersionTracker; diff --git a/src/org/thoughtcrime/securesms/ExportFragment.java b/src/org/thoughtcrime/securesms/ExportFragment.java index eb5fdf3c0f..2f4a38193f 100644 --- a/src/org/thoughtcrime/securesms/ExportFragment.java +++ b/src/org/thoughtcrime/securesms/ExportFragment.java @@ -14,7 +14,7 @@ import android.view.ViewGroup; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.EncryptedBackupExporter; import org.thoughtcrime.securesms.database.NoExternalStorageException; import org.thoughtcrime.securesms.database.PlaintextBackupExporter; diff --git a/src/org/thoughtcrime/securesms/IdentityKeyView.java b/src/org/thoughtcrime/securesms/IdentityKeyView.java index be3e245762..dc1bdcbf94 100644 --- a/src/org/thoughtcrime/securesms/IdentityKeyView.java +++ b/src/org/thoughtcrime/securesms/IdentityKeyView.java @@ -26,7 +26,7 @@ import android.widget.QuickContactBadge; import android.widget.RelativeLayout; import android.widget.TextView; -import org.thoughtcrime.securesms.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.IdentityKey; import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.Recipients; diff --git a/src/org/thoughtcrime/securesms/ImportExportActivity.java b/src/org/thoughtcrime/securesms/ImportExportActivity.java index f1926957e2..e14f3d8531 100644 --- a/src/org/thoughtcrime/securesms/ImportExportActivity.java +++ b/src/org/thoughtcrime/securesms/ImportExportActivity.java @@ -9,7 +9,7 @@ import android.support.v4.view.ViewPager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.MenuItem; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; public class ImportExportActivity extends PassphraseRequiredSherlockFragmentActivity { diff --git a/src/org/thoughtcrime/securesms/ImportFragment.java b/src/org/thoughtcrime/securesms/ImportFragment.java index 57e824ce56..0d94061a18 100644 --- a/src/org/thoughtcrime/securesms/ImportFragment.java +++ b/src/org/thoughtcrime/securesms/ImportFragment.java @@ -14,7 +14,7 @@ import android.view.ViewGroup; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.EncryptedBackupExporter; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.NoExternalStorageException; diff --git a/src/org/thoughtcrime/securesms/KeyScanningActivity.java b/src/org/thoughtcrime/securesms/KeyScanningActivity.java index fd84ae0208..2c1bf04d90 100644 --- a/src/org/thoughtcrime/securesms/KeyScanningActivity.java +++ b/src/org/thoughtcrime/securesms/KeyScanningActivity.java @@ -20,7 +20,7 @@ import android.content.Intent; import android.os.Bundle; import android.widget.Toast; -import org.thoughtcrime.securesms.crypto.SerializableKey; +import org.whispersystems.textsecure.crypto.SerializableKey; import org.whispersystems.textsecure.util.Base64; import org.thoughtcrime.securesms.util.Dialogs; import org.thoughtcrime.securesms.util.DynamicTheme; diff --git a/src/org/thoughtcrime/securesms/PassphraseActivity.java b/src/org/thoughtcrime/securesms/PassphraseActivity.java index c3ffa72285..8dcf575cec 100644 --- a/src/org/thoughtcrime/securesms/PassphraseActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseActivity.java @@ -22,7 +22,7 @@ import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.MemoryCleaner; diff --git a/src/org/thoughtcrime/securesms/PassphraseChangeActivity.java b/src/org/thoughtcrime/securesms/PassphraseChangeActivity.java index 6832da1561..182b37a9c5 100644 --- a/src/org/thoughtcrime/securesms/PassphraseChangeActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseChangeActivity.java @@ -17,7 +17,6 @@ package org.thoughtcrime.securesms; import android.os.Bundle; -import android.preference.PreferenceManager; import android.text.Editable; import android.view.View; import android.view.View.OnClickListener; @@ -27,7 +26,7 @@ import android.widget.TextView; import android.widget.Toast; import org.thoughtcrime.securesms.crypto.InvalidPassphraseException; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.util.MemoryCleaner; import org.thoughtcrime.securesms.util.TextSecurePreferences; diff --git a/src/org/thoughtcrime/securesms/PassphraseCreateActivity.java b/src/org/thoughtcrime/securesms/PassphraseCreateActivity.java index b467c74a3e..f45ab95bb9 100644 --- a/src/org/thoughtcrime/securesms/PassphraseCreateActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseCreateActivity.java @@ -25,9 +25,8 @@ import android.widget.LinearLayout; import android.widget.Toast; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; -import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.util.MemoryCleaner; import org.thoughtcrime.securesms.util.VersionTracker; import org.whispersystems.textsecure.util.Util; diff --git a/src/org/thoughtcrime/securesms/PassphrasePromptActivity.java b/src/org/thoughtcrime/securesms/PassphrasePromptActivity.java index c7d6f50705..d9155fd01e 100644 --- a/src/org/thoughtcrime/securesms/PassphrasePromptActivity.java +++ b/src/org/thoughtcrime/securesms/PassphrasePromptActivity.java @@ -25,7 +25,7 @@ import android.widget.EditText; import android.widget.Toast; import org.thoughtcrime.securesms.crypto.InvalidPassphraseException; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.util.MemoryCleaner; diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredActivity.java b/src/org/thoughtcrime/securesms/PassphraseRequiredActivity.java index 45fd862676..ef79955f04 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredActivity.java @@ -1,6 +1,6 @@ package org.thoughtcrime.securesms; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; public interface PassphraseRequiredActivity { public void onMasterSecretCleared(); diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredMixin.java b/src/org/thoughtcrime/securesms/PassphraseRequiredMixin.java index 860c43f4d4..79fd3eea7d 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredMixin.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredMixin.java @@ -8,7 +8,7 @@ import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.IBinder; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.service.KeyCachingService; diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockActivity.java b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockActivity.java index b9726e6a3c..209b61f130 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockActivity.java @@ -2,7 +2,7 @@ package org.thoughtcrime.securesms; import android.os.Bundle; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import com.actionbarsherlock.app.SherlockActivity; diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockFragmentActivity.java b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockFragmentActivity.java index 462f1cefc2..910eba01da 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockFragmentActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockFragmentActivity.java @@ -2,7 +2,7 @@ package org.thoughtcrime.securesms; import android.os.Bundle; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import com.actionbarsherlock.app.SherlockFragmentActivity; diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockListActivity.java b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockListActivity.java index 3d061cbb18..b4bc7fda5e 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockListActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockListActivity.java @@ -2,7 +2,7 @@ package org.thoughtcrime.securesms; import android.os.Bundle; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import com.actionbarsherlock.app.SherlockListActivity; diff --git a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockPreferenceActivity.java b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockPreferenceActivity.java index a643a69fc7..02e2b2d60f 100644 --- a/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockPreferenceActivity.java +++ b/src/org/thoughtcrime/securesms/PassphraseRequiredSherlockPreferenceActivity.java @@ -2,7 +2,7 @@ package org.thoughtcrime.securesms; import android.os.Bundle; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import com.actionbarsherlock.app.SherlockPreferenceActivity; diff --git a/src/org/thoughtcrime/securesms/ReceiveKeyActivity.java b/src/org/thoughtcrime/securesms/ReceiveKeyActivity.java index a3882d3d39..435907a4cd 100644 --- a/src/org/thoughtcrime/securesms/ReceiveKeyActivity.java +++ b/src/org/thoughtcrime/securesms/ReceiveKeyActivity.java @@ -30,11 +30,11 @@ import android.view.View; import android.widget.Button; import android.widget.TextView; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.InvalidKeyException; import org.thoughtcrime.securesms.crypto.InvalidVersionException; import org.thoughtcrime.securesms.crypto.KeyExchangeMessage; import org.thoughtcrime.securesms.crypto.KeyExchangeProcessor; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.MemoryCleaner; diff --git a/src/org/thoughtcrime/securesms/RegistrationActivity.java b/src/org/thoughtcrime/securesms/RegistrationActivity.java index af061ef722..4dc9888a28 100644 --- a/src/org/thoughtcrime/securesms/RegistrationActivity.java +++ b/src/org/thoughtcrime/securesms/RegistrationActivity.java @@ -24,7 +24,7 @@ import com.google.i18n.phonenumbers.AsYouTypeFormatter; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.textsecure.util.PhoneNumberFormatter; import org.whispersystems.textsecure.util.Util; diff --git a/src/org/thoughtcrime/securesms/RegistrationProgressActivity.java b/src/org/thoughtcrime/securesms/RegistrationProgressActivity.java index 9ed2da33d2..0fe5fb924a 100644 --- a/src/org/thoughtcrime/securesms/RegistrationProgressActivity.java +++ b/src/org/thoughtcrime/securesms/RegistrationProgressActivity.java @@ -29,7 +29,7 @@ import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.service.RegistrationService; import org.whispersystems.textsecure.push.PushServiceSocket; import org.whispersystems.textsecure.push.RateLimitException; diff --git a/src/org/thoughtcrime/securesms/ReviewIdentitiesFragment.java b/src/org/thoughtcrime/securesms/ReviewIdentitiesFragment.java index 9a08d8f44e..73aae03e27 100644 --- a/src/org/thoughtcrime/securesms/ReviewIdentitiesFragment.java +++ b/src/org/thoughtcrime/securesms/ReviewIdentitiesFragment.java @@ -13,7 +13,7 @@ import android.widget.CursorAdapter; import android.widget.ListView; import com.actionbarsherlock.app.SherlockListFragment; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.database.loaders.IdentityLoader; diff --git a/src/org/thoughtcrime/securesms/RoutingActivity.java b/src/org/thoughtcrime/securesms/RoutingActivity.java index a6c4ac6dd3..958a1dbe76 100644 --- a/src/org/thoughtcrime/securesms/RoutingActivity.java +++ b/src/org/thoughtcrime/securesms/RoutingActivity.java @@ -3,7 +3,7 @@ package org.thoughtcrime.securesms; import android.content.Intent; import android.net.Uri; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.recipients.RecipientFactory; diff --git a/src/org/thoughtcrime/securesms/VerifyIdentityActivity.java b/src/org/thoughtcrime/securesms/VerifyIdentityActivity.java index 86c9baf2e6..062004ab9b 100644 --- a/src/org/thoughtcrime/securesms/VerifyIdentityActivity.java +++ b/src/org/thoughtcrime/securesms/VerifyIdentityActivity.java @@ -20,11 +20,10 @@ import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; -import com.actionbarsherlock.view.MenuItem; -import org.thoughtcrime.securesms.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.IdentityKey; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.database.keys.SessionRecord; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.storage.SessionRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.MemoryCleaner; diff --git a/src/org/thoughtcrime/securesms/VerifyKeysActivity.java b/src/org/thoughtcrime/securesms/VerifyKeysActivity.java index 1da01cd930..9c7f3f6b51 100644 --- a/src/org/thoughtcrime/securesms/VerifyKeysActivity.java +++ b/src/org/thoughtcrime/securesms/VerifyKeysActivity.java @@ -19,11 +19,11 @@ package org.thoughtcrime.securesms; import android.os.Bundle; import android.widget.TextView; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.SerializableKey; -import org.thoughtcrime.securesms.database.keys.SessionRecord; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.SerializableKey; +import org.whispersystems.textsecure.storage.SessionRecord; import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Hex; +import org.whispersystems.textsecure.util.Hex; import org.thoughtcrime.securesms.util.MemoryCleaner; /** diff --git a/src/org/thoughtcrime/securesms/ViewIdentityActivity.java b/src/org/thoughtcrime/securesms/ViewIdentityActivity.java index b145b1bd7e..4db357f142 100644 --- a/src/org/thoughtcrime/securesms/ViewIdentityActivity.java +++ b/src/org/thoughtcrime/securesms/ViewIdentityActivity.java @@ -19,7 +19,7 @@ package org.thoughtcrime.securesms; import android.os.Bundle; import android.widget.TextView; -import org.thoughtcrime.securesms.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.IdentityKey; /** * Activity for displaying an identity key. diff --git a/src/org/thoughtcrime/securesms/contacts/ContactAccessor.java b/src/org/thoughtcrime/securesms/contacts/ContactAccessor.java index 6fbacc0602..d3854ebced 100644 --- a/src/org/thoughtcrime/securesms/contacts/ContactAccessor.java +++ b/src/org/thoughtcrime/securesms/contacts/ContactAccessor.java @@ -34,8 +34,8 @@ import android.support.v4.content.CursorLoader; import android.telephony.PhoneNumberUtils; import android.util.Log; -import org.thoughtcrime.securesms.crypto.IdentityKey; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; import org.whispersystems.textsecure.util.Base64; import java.io.IOException; diff --git a/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterCipher.java b/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterCipher.java index f6ae8c2518..9c5f3f0be1 100644 --- a/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterCipher.java +++ b/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterCipher.java @@ -23,12 +23,17 @@ import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.agreement.ECDHBasicAgreement; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PublicKey; import org.whispersystems.textsecure.util.Base64; import org.whispersystems.textsecure.util.Conversions; -import org.thoughtcrime.securesms.util.InvalidMessageException; /** * This class is used to asymmetricly encrypt local data. This is used in the case @@ -58,7 +63,7 @@ public class AsymmetricMasterCipher { this.asymmetricMasterSecret = asymmetricMasterSecret; } - public String decryptBody(String body) throws IOException, org.thoughtcrime.securesms.crypto.InvalidMessageException { + public String decryptBody(String body) throws IOException, InvalidMessageException { try { byte[] combined = Base64.decode(body); PublicKey theirPublicKey = new PublicKey(combined, 0); @@ -74,9 +79,9 @@ public class AsymmetricMasterCipher { return new String(decryptedBodyBytes); } catch (InvalidKeyException ike) { - throw new org.thoughtcrime.securesms.crypto.InvalidMessageException(ike); + throw new InvalidMessageException(ike); } catch (InvalidMessageException e) { - throw new org.thoughtcrime.securesms.crypto.InvalidMessageException(e); + throw new InvalidMessageException(e); } } diff --git a/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterSecret.java b/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterSecret.java index 8f73df984e..ddb7de7892 100644 --- a/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterSecret.java +++ b/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterSecret.java @@ -16,7 +16,8 @@ */ package org.thoughtcrime.securesms.crypto; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; +import org.whispersystems.textsecure.crypto.PublicKey; /** * When a user first initializes TextSecure, a few secrets diff --git a/src/org/thoughtcrime/securesms/crypto/DecryptingPartInputStream.java b/src/org/thoughtcrime/securesms/crypto/DecryptingPartInputStream.java index 82e7805339..dc23d84f26 100644 --- a/src/org/thoughtcrime/securesms/crypto/DecryptingPartInputStream.java +++ b/src/org/thoughtcrime/securesms/crypto/DecryptingPartInputStream.java @@ -37,6 +37,8 @@ import javax.crypto.spec.SecretKeySpec; import android.util.Log; +import org.whispersystems.textsecure.crypto.MasterSecret; + /** * Class for streaming an encrypted MMS "part" off the disk. * diff --git a/src/org/thoughtcrime/securesms/crypto/DecryptingQueue.java b/src/org/thoughtcrime/securesms/crypto/DecryptingQueue.java index f65285e417..17f38fa3c3 100644 --- a/src/org/thoughtcrime/securesms/crypto/DecryptingQueue.java +++ b/src/org/thoughtcrime/securesms/crypto/DecryptingQueue.java @@ -18,10 +18,8 @@ package org.thoughtcrime.securesms.crypto; import android.content.Context; import android.database.Cursor; -import android.preference.PreferenceManager; import android.util.Log; -import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; import org.thoughtcrime.securesms.database.MmsDatabase; @@ -35,9 +33,14 @@ import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.RecipientFormattingException; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.sms.SmsTransportDetails; -import org.thoughtcrime.securesms.util.Hex; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.SessionCipher; +import org.whispersystems.textsecure.util.Hex; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.WorkerThread; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterSecret; import java.io.IOException; import java.util.LinkedList; @@ -48,7 +51,6 @@ import ws.com.google.android.mms.MmsException; import ws.com.google.android.mms.pdu.MultimediaMessagePdu; import ws.com.google.android.mms.pdu.PduParser; import ws.com.google.android.mms.pdu.RetrieveConf; -import ws.com.google.android.mms.pdu.SendReq; /** * A work queue for processing a number of encryption operations. @@ -170,10 +172,10 @@ public class DecryptingQueue { MmsDatabase database = DatabaseFactory.getMmsDatabase(context); try { - String messageFrom = pdu.getFrom().getString(); - Recipients recipients = RecipientFactory.getRecipientsFromString(context, messageFrom, false); - Recipient recipient = recipients.getPrimaryRecipient(); - byte[] ciphertextPduBytes = getEncryptedData(); + String messageFrom = pdu.getFrom().getString(); + Recipients recipients = RecipientFactory.getRecipientsFromString(context, messageFrom, false); + Recipient recipient = recipients.getPrimaryRecipient(); + byte[] ciphertextPduBytes = getEncryptedData(); if (ciphertextPduBytes == null) { Log.w("DecryptingQueue", "No encoded PNG data found on parts."); @@ -261,7 +263,7 @@ public class DecryptingQueue { try { Log.w("DecryptingQueue", "Parsing recipient for originator: " + originator); Recipients recipients = RecipientFactory.getRecipientsFromString(context, originator, false); - Recipient recipient = recipients.getPrimaryRecipient(); + Recipient recipient = recipients.getPrimaryRecipient(); Log.w("DecryptingQueue", "Parsed Recipient: " + recipient.getNumber()); if (!KeyUtil.isSessionFor(context, recipient)) { diff --git a/src/org/thoughtcrime/securesms/crypto/EncryptingPartOutputStream.java b/src/org/thoughtcrime/securesms/crypto/EncryptingPartOutputStream.java index 7a1856f7a2..2ae2039cdd 100644 --- a/src/org/thoughtcrime/securesms/crypto/EncryptingPartOutputStream.java +++ b/src/org/thoughtcrime/securesms/crypto/EncryptingPartOutputStream.java @@ -32,6 +32,8 @@ import javax.crypto.spec.SecretKeySpec; import android.util.Log; +import org.whispersystems.textsecure.crypto.MasterSecret; + /** * A class for streaming an encrypted MMS "part" to disk. * diff --git a/src/org/thoughtcrime/securesms/crypto/IdentityKeyUtil.java b/src/org/thoughtcrime/securesms/crypto/IdentityKeyUtil.java index 3595fc59aa..7ccd1fc657 100644 --- a/src/org/thoughtcrime/securesms/crypto/IdentityKeyUtil.java +++ b/src/org/thoughtcrime/securesms/crypto/IdentityKeyUtil.java @@ -16,29 +16,36 @@ */ package org.thoughtcrime.securesms.crypto; -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.signers.ECDSASigner; -import org.thoughtcrime.bouncycastle.asn1.ASN1Encodable; -import org.thoughtcrime.bouncycastle.asn1.ASN1Object; -import org.thoughtcrime.bouncycastle.asn1.ASN1Sequence; -import org.thoughtcrime.bouncycastle.asn1.DERInteger; -import org.thoughtcrime.bouncycastle.asn1.DERSequence; -import org.whispersystems.textsecure.util.Base64; -import org.thoughtcrime.securesms.util.Combiner; -import org.whispersystems.textsecure.util.Conversions; - import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; +import org.spongycastle.asn1.ASN1Encoding; +import org.spongycastle.asn1.ASN1Object; +import org.spongycastle.asn1.ASN1Primitive; +import org.spongycastle.asn1.ASN1Sequence; +import org.spongycastle.asn1.DERInteger; +import org.spongycastle.asn1.DERSequence; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.params.ECPublicKeyParameters; +import org.spongycastle.crypto.signers.ECDSASigner; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PublicKey; +import org.whispersystems.textsecure.util.Base64; +import org.whispersystems.textsecure.util.Conversions; +import org.whispersystems.textsecure.util.Util; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + /** * Utility class for working with identity keys. * @@ -108,7 +115,7 @@ public class IdentityKeyUtil { verifier.init(false, identityKey.getPublicKeyParameters()); - ASN1Sequence sequence = (ASN1Sequence)ASN1Object.fromByteArray(signatureBytes); + ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(signatureBytes); BigInteger[] signatureIntegers = new BigInteger[]{ ((DERInteger)sequence.getObjectAt(0)).getValue(), ((DERInteger)sequence.getObjectAt(1)).getValue() @@ -139,13 +146,13 @@ public class IdentityKeyUtil { BigInteger[] messageSignatureInts = signer.generateSignature(messageHash); DERInteger[] derMessageSignatureInts = new DERInteger[]{ new DERInteger(messageSignatureInts[0]), new DERInteger(messageSignatureInts[1]) }; - byte[] messageSignatureBytes = new DERSequence(derMessageSignatureInts).getEncoded(ASN1Encodable.DER); + byte[] messageSignatureBytes = new DERSequence(derMessageSignatureInts).getEncoded(ASN1Encoding.DER); byte[] messageSignature = new byte[2 + messageSignatureBytes.length]; Conversions.shortToByteArray(messageSignature, 0, messageSignatureBytes.length); System.arraycopy(messageSignatureBytes, 0, messageSignature, 2, messageSignatureBytes.length); - byte[] combined = Combiner.combine(keyExchangeBytes, publicKeyBytes, messageSignature); + byte[] combined = Util.combine(keyExchangeBytes, publicKeyBytes, messageSignature); return combined; } catch (IOException ioe) { diff --git a/src/org/thoughtcrime/securesms/crypto/InvalidMessageException.java b/src/org/thoughtcrime/securesms/crypto/InvalidMessageException.java deleted file mode 100644 index e46af039d9..0000000000 --- a/src/org/thoughtcrime/securesms/crypto/InvalidMessageException.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (C) 2011 Whisper Systems - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.thoughtcrime.securesms.crypto; - -public class InvalidMessageException extends Exception { - - public InvalidMessageException() { - // TODO Auto-generated constructor stub - } - - public InvalidMessageException(String detailMessage) { - super(detailMessage); - // TODO Auto-generated constructor stub - } - - public InvalidMessageException(Throwable throwable) { - super(throwable); - // TODO Auto-generated constructor stub - } - - public InvalidMessageException(String detailMessage, Throwable throwable) { - super(detailMessage, throwable); - // TODO Auto-generated constructor stub - } - -} diff --git a/src/org/thoughtcrime/securesms/crypto/KeyExchangeInitiator.java b/src/org/thoughtcrime/securesms/crypto/KeyExchangeInitiator.java index 1c8d08e7b8..66d034d692 100644 --- a/src/org/thoughtcrime/securesms/crypto/KeyExchangeInitiator.java +++ b/src/org/thoughtcrime/securesms/crypto/KeyExchangeInitiator.java @@ -22,10 +22,12 @@ import android.content.DialogInterface; import android.util.Log; import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.sms.MessageSender; import org.thoughtcrime.securesms.sms.OutgoingKeyExchangeMessage; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.storage.LocalKeyRecord; public class KeyExchangeInitiator { diff --git a/src/org/thoughtcrime/securesms/crypto/KeyExchangeMessage.java b/src/org/thoughtcrime/securesms/crypto/KeyExchangeMessage.java index 4b90758614..64a00c82cd 100644 --- a/src/org/thoughtcrime/securesms/crypto/KeyExchangeMessage.java +++ b/src/org/thoughtcrime/securesms/crypto/KeyExchangeMessage.java @@ -19,8 +19,12 @@ package org.thoughtcrime.securesms.crypto; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; -import org.thoughtcrime.securesms.protocol.Message; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PublicKey; +import org.whispersystems.textsecure.storage.LocalKeyRecord; +import org.whispersystems.textsecure.protocol.Message; import org.whispersystems.textsecure.util.Base64; import org.whispersystems.textsecure.util.Conversions; @@ -54,9 +58,9 @@ public class KeyExchangeMessage { private final int messageVersion; private final int supportedVersion; - private final PublicKey publicKey; + private final PublicKey publicKey; private final String serialized; - private IdentityKey identityKey; + private IdentityKey identityKey; public KeyExchangeMessage(Context context, MasterSecret masterSecret, int messageVersion, LocalKeyRecord record, int highIdBits) { this.publicKey = new PublicKey(record.getCurrentKeyPair().getPublicKey()); diff --git a/src/org/thoughtcrime/securesms/crypto/KeyExchangeProcessor.java b/src/org/thoughtcrime/securesms/crypto/KeyExchangeProcessor.java index 18f0c64ea5..50787c78e8 100644 --- a/src/org/thoughtcrime/securesms/crypto/KeyExchangeProcessor.java +++ b/src/org/thoughtcrime/securesms/crypto/KeyExchangeProcessor.java @@ -20,12 +20,13 @@ import android.content.Context; import android.content.Intent; import android.util.Log; -import org.bouncycastle.util.Arrays; import org.thoughtcrime.securesms.database.DatabaseFactory; -import org.thoughtcrime.securesms.database.keys.LocalKeyRecord; -import org.thoughtcrime.securesms.database.keys.RemoteKeyRecord; -import org.thoughtcrime.securesms.database.keys.SessionRecord; -import org.thoughtcrime.securesms.protocol.Message; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.storage.LocalKeyRecord; +import org.whispersystems.textsecure.storage.RemoteKeyRecord; +import org.whispersystems.textsecure.storage.SessionRecord; +import org.whispersystems.textsecure.protocol.Message; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.sms.MessageSender; diff --git a/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java b/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java index 45882c7625..df102813fc 100644 --- a/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java +++ b/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java @@ -21,9 +21,16 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.spongycastle.crypto.AsymmetricCipherKeyPair; +import org.spongycastle.crypto.params.ECPrivateKeyParameters; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.KeyPair; +import org.whispersystems.textsecure.crypto.KeyUtil; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PublicKey; import org.whispersystems.textsecure.util.Base64; +import org.whispersystems.textsecure.util.Util; import java.io.IOException; import java.security.GeneralSecurityException; @@ -203,8 +210,8 @@ public class MasterSecretUtil { SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, 0); String encodedValue = settings.getString(key, ""); - if (encodedValue == "") return null; - else return Base64.decode(encodedValue); + if (Util.isEmpty(encodedValue)) return null; + else return Base64.decode(encodedValue); } private static byte[] generateEncryptionSecret() { @@ -252,7 +259,7 @@ public class MasterSecretUtil { return cipher; } - private static byte[] encryptWithPassphrase(Context context, byte[] data, String passphrase) throws NoSuchAlgorithmException, GeneralSecurityException { + private static byte[] encryptWithPassphrase(Context context, byte[] data, String passphrase) throws GeneralSecurityException { byte[] encryptionSalt = generateSalt(); Cipher cipher = getCipherFromPassphrase(passphrase, encryptionSalt, Cipher.ENCRYPT_MODE); byte[] cipherText = cipher.doFinal(data); diff --git a/src/org/thoughtcrime/securesms/crypto/PublicKeyAndVersion.java b/src/org/thoughtcrime/securesms/crypto/PublicKeyAndVersion.java index 02debd71bf..39ab4a62ca 100644 --- a/src/org/thoughtcrime/securesms/crypto/PublicKeyAndVersion.java +++ b/src/org/thoughtcrime/securesms/crypto/PublicKeyAndVersion.java @@ -16,9 +16,12 @@ */ package org.thoughtcrime.securesms.crypto; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.PublicKey; + public class PublicKeyAndVersion { - public IdentityKey identityKey; + public IdentityKey identityKey; public final PublicKey key; public final int version; public final int maxVersion; diff --git a/src/org/thoughtcrime/securesms/database/DatabaseFactory.java b/src/org/thoughtcrime/securesms/database/DatabaseFactory.java index 5863bb075a..4ef1cb5be4 100644 --- a/src/org/thoughtcrime/securesms/database/DatabaseFactory.java +++ b/src/org/thoughtcrime/securesms/database/DatabaseFactory.java @@ -26,13 +26,13 @@ import android.util.Log; import org.thoughtcrime.securesms.DatabaseUpgradeActivity; import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream; import org.thoughtcrime.securesms.crypto.DecryptingQueue; -import org.thoughtcrime.securesms.crypto.IdentityKey; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.database.keys.SessionRecord; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.storage.SessionRecord; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.whispersystems.textsecure.util.Base64; -import org.thoughtcrime.securesms.util.InvalidMessageException; import org.whispersystems.textsecure.util.Util; import java.io.File; diff --git a/src/org/thoughtcrime/securesms/database/DraftDatabase.java b/src/org/thoughtcrime/securesms/database/DraftDatabase.java index e0d9c7810f..487e03a07d 100644 --- a/src/org/thoughtcrime/securesms/database/DraftDatabase.java +++ b/src/org/thoughtcrime/securesms/database/DraftDatabase.java @@ -7,8 +7,8 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.util.InvalidMessageException; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.MasterCipher; import java.util.LinkedList; import java.util.List; diff --git a/src/org/thoughtcrime/securesms/database/EncryptingPartDatabase.java b/src/org/thoughtcrime/securesms/database/EncryptingPartDatabase.java index 948d66dde6..d668602b4a 100644 --- a/src/org/thoughtcrime/securesms/database/EncryptingPartDatabase.java +++ b/src/org/thoughtcrime/securesms/database/EncryptingPartDatabase.java @@ -22,7 +22,7 @@ import android.util.Log; import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream; import org.thoughtcrime.securesms.crypto.EncryptingPartOutputStream; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import ws.com.google.android.mms.pdu.PduPart; diff --git a/src/org/thoughtcrime/securesms/database/EncryptingSmsDatabase.java b/src/org/thoughtcrime/securesms/database/EncryptingSmsDatabase.java index 7b6d396cda..d4ed2f0f4b 100644 --- a/src/org/thoughtcrime/securesms/database/EncryptingSmsDatabase.java +++ b/src/org/thoughtcrime/securesms/database/EncryptingSmsDatabase.java @@ -24,12 +24,12 @@ import android.util.Pair; import org.thoughtcrime.securesms.crypto.AsymmetricMasterCipher; import org.thoughtcrime.securesms.crypto.AsymmetricMasterSecret; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.DisplayRecord; import org.thoughtcrime.securesms.sms.IncomingTextMessage; import org.thoughtcrime.securesms.sms.OutgoingTextMessage; -import org.thoughtcrime.securesms.util.InvalidMessageException; import org.thoughtcrime.securesms.util.LRUCache; import java.lang.ref.SoftReference; diff --git a/src/org/thoughtcrime/securesms/database/IdentityDatabase.java b/src/org/thoughtcrime/securesms/database/IdentityDatabase.java index 02997625a1..dc1f209d56 100644 --- a/src/org/thoughtcrime/securesms/database/IdentityDatabase.java +++ b/src/org/thoughtcrime/securesms/database/IdentityDatabase.java @@ -24,10 +24,10 @@ import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; -import org.thoughtcrime.securesms.crypto.IdentityKey; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.IdentityKey; +import org.whispersystems.textsecure.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; diff --git a/src/org/thoughtcrime/securesms/database/MmsDatabase.java b/src/org/thoughtcrime/securesms/database/MmsDatabase.java index a80356b699..7d6b484d2c 100644 --- a/src/org/thoughtcrime/securesms/database/MmsDatabase.java +++ b/src/org/thoughtcrime/securesms/database/MmsDatabase.java @@ -27,8 +27,9 @@ import android.util.Pair; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.contacts.ContactPhotoFactory; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.DisplayRecord; import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord; import org.thoughtcrime.securesms.database.model.MessageRecord; @@ -41,7 +42,6 @@ import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.RecipientFormattingException; import org.thoughtcrime.securesms.recipients.Recipients; -import org.thoughtcrime.securesms.util.InvalidMessageException; import org.thoughtcrime.securesms.util.LRUCache; import org.thoughtcrime.securesms.util.ListenableFutureTask; import org.thoughtcrime.securesms.util.Trimmer; diff --git a/src/org/thoughtcrime/securesms/database/MmsSmsDatabase.java b/src/org/thoughtcrime/securesms/database/MmsSmsDatabase.java index a0298b2dc8..97210e6092 100644 --- a/src/org/thoughtcrime/securesms/database/MmsSmsDatabase.java +++ b/src/org/thoughtcrime/securesms/database/MmsSmsDatabase.java @@ -23,7 +23,7 @@ import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.MessageRecord; import java.util.HashSet; diff --git a/src/org/thoughtcrime/securesms/database/PlaintextBackupExporter.java b/src/org/thoughtcrime/securesms/database/PlaintextBackupExporter.java index 453dab4763..4721a86922 100644 --- a/src/org/thoughtcrime/securesms/database/PlaintextBackupExporter.java +++ b/src/org/thoughtcrime/securesms/database/PlaintextBackupExporter.java @@ -4,7 +4,7 @@ package org.thoughtcrime.securesms.database; import android.content.Context; import android.os.Environment; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import java.io.File; diff --git a/src/org/thoughtcrime/securesms/database/PlaintextBackupImporter.java b/src/org/thoughtcrime/securesms/database/PlaintextBackupImporter.java index cae3221fb9..0ffde41a06 100644 --- a/src/org/thoughtcrime/securesms/database/PlaintextBackupImporter.java +++ b/src/org/thoughtcrime/securesms/database/PlaintextBackupImporter.java @@ -6,8 +6,8 @@ import android.database.sqlite.SQLiteStatement; import android.os.Environment; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.RecipientFormattingException; import org.thoughtcrime.securesms.recipients.Recipients; @@ -16,8 +16,6 @@ import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.IOException; import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; import java.util.Set; diff --git a/src/org/thoughtcrime/securesms/database/SmsMigrator.java b/src/org/thoughtcrime/securesms/database/SmsMigrator.java index f25eb352bd..bf72a18eda 100644 --- a/src/org/thoughtcrime/securesms/database/SmsMigrator.java +++ b/src/org/thoughtcrime/securesms/database/SmsMigrator.java @@ -23,8 +23,8 @@ import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.RecipientFormattingException; import org.thoughtcrime.securesms.recipients.Recipients; diff --git a/src/org/thoughtcrime/securesms/database/ThreadDatabase.java b/src/org/thoughtcrime/securesms/database/ThreadDatabase.java index 4634bb953f..d629dd69e5 100644 --- a/src/org/thoughtcrime/securesms/database/ThreadDatabase.java +++ b/src/org/thoughtcrime/securesms/database/ThreadDatabase.java @@ -23,15 +23,15 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterCipher; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.InvalidMessageException; +import org.whispersystems.textsecure.crypto.MasterCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.DisplayRecord; import org.thoughtcrime.securesms.database.model.MessageRecord; import org.thoughtcrime.securesms.database.model.ThreadRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; -import org.thoughtcrime.securesms.util.InvalidMessageException; import org.whispersystems.textsecure.util.Util; import java.util.Arrays; diff --git a/src/org/thoughtcrime/securesms/database/loaders/IdentityLoader.java b/src/org/thoughtcrime/securesms/database/loaders/IdentityLoader.java index f884a635a9..e906f8e6be 100644 --- a/src/org/thoughtcrime/securesms/database/loaders/IdentityLoader.java +++ b/src/org/thoughtcrime/securesms/database/loaders/IdentityLoader.java @@ -2,12 +2,9 @@ package org.thoughtcrime.securesms.database.loaders; import android.content.Context; import android.database.Cursor; -import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.CursorLoader; -import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; -import org.thoughtcrime.securesms.database.IdentityDatabase; public class IdentityLoader extends CursorLoader { diff --git a/src/org/thoughtcrime/securesms/mms/ImageSlide.java b/src/org/thoughtcrime/securesms/mms/ImageSlide.java index f993b059b5..0b4fc29a9b 100644 --- a/src/org/thoughtcrime/securesms/mms/ImageSlide.java +++ b/src/org/thoughtcrime/securesms/mms/ImageSlide.java @@ -30,7 +30,7 @@ import android.util.Log; import android.widget.ImageView; import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.util.BitmapDecodingException; import org.thoughtcrime.securesms.util.BitmapUtil; diff --git a/src/org/thoughtcrime/securesms/mms/PngTransport.java b/src/org/thoughtcrime/securesms/mms/PngTransport.java index 283a3f9bd5..923e9ec1fc 100644 --- a/src/org/thoughtcrime/securesms/mms/PngTransport.java +++ b/src/org/thoughtcrime/securesms/mms/PngTransport.java @@ -24,8 +24,8 @@ import java.util.zip.CRC32; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import org.thoughtcrime.securesms.crypto.SessionCipher; -import org.thoughtcrime.securesms.crypto.TransportDetails; +import org.whispersystems.textsecure.crypto.SessionCipher; +import org.whispersystems.textsecure.crypto.TransportDetails; import org.whispersystems.textsecure.util.Conversions; import android.util.Log; diff --git a/src/org/thoughtcrime/securesms/mms/Slide.java b/src/org/thoughtcrime/securesms/mms/Slide.java index 60d0b90518..d3a0af680f 100644 --- a/src/org/thoughtcrime/securesms/mms/Slide.java +++ b/src/org/thoughtcrime/securesms/mms/Slide.java @@ -20,7 +20,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.providers.PartProvider; diff --git a/src/org/thoughtcrime/securesms/mms/SlideDeck.java b/src/org/thoughtcrime/securesms/mms/SlideDeck.java index a51dd405db..5de29f3578 100644 --- a/src/org/thoughtcrime/securesms/mms/SlideDeck.java +++ b/src/org/thoughtcrime/securesms/mms/SlideDeck.java @@ -18,7 +18,7 @@ package org.thoughtcrime.securesms.mms; import android.content.Context; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import java.io.UnsupportedEncodingException; import java.util.LinkedList; diff --git a/src/org/thoughtcrime/securesms/mms/TextSlide.java b/src/org/thoughtcrime/securesms/mms/TextSlide.java index 330490d93f..3034d6690c 100644 --- a/src/org/thoughtcrime/securesms/mms/TextSlide.java +++ b/src/org/thoughtcrime/securesms/mms/TextSlide.java @@ -20,7 +20,7 @@ import android.content.Context; import android.net.Uri; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.util.LRUCache; import java.io.UnsupportedEncodingException; diff --git a/src/org/thoughtcrime/securesms/mms/TextTransport.java b/src/org/thoughtcrime/securesms/mms/TextTransport.java index 5c80e1b8d6..ad18fd3043 100644 --- a/src/org/thoughtcrime/securesms/mms/TextTransport.java +++ b/src/org/thoughtcrime/securesms/mms/TextTransport.java @@ -18,7 +18,7 @@ package org.thoughtcrime.securesms.mms; import java.io.IOException; -import org.thoughtcrime.securesms.crypto.TransportDetails; +import org.whispersystems.textsecure.crypto.TransportDetails; import org.whispersystems.textsecure.util.Base64; public class TextTransport implements TransportDetails { diff --git a/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java b/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java index 4338a7a42c..2a30c4d8b5 100644 --- a/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java +++ b/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java @@ -7,7 +7,7 @@ import android.content.Intent; import android.os.AsyncTask; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; public class MarkReadReceiver extends BroadcastReceiver { diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java index ce9872e786..a186ae83ff 100644 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java +++ b/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java @@ -21,14 +21,12 @@ import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.BitmapFactory; import android.graphics.Color; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; -import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.BigTextStyle; import android.support.v4.app.NotificationCompat.InboxStyle; @@ -39,10 +37,9 @@ import android.text.TextUtils; import android.text.style.StyleSpan; import android.util.Log; -import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.RoutingActivity; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsSmsDatabase; import org.thoughtcrime.securesms.database.model.MessageRecord; diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationState.java b/src/org/thoughtcrime/securesms/notifications/NotificationState.java index 0b4c9ecfc5..0da6a43e0d 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationState.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationState.java @@ -6,7 +6,7 @@ import android.content.Intent; import android.graphics.Bitmap; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import java.util.HashSet; import java.util.LinkedList; diff --git a/src/org/thoughtcrime/securesms/providers/PartProvider.java b/src/org/thoughtcrime/securesms/providers/PartProvider.java index 4220d2115d..d1e364413c 100644 --- a/src/org/thoughtcrime/securesms/providers/PartProvider.java +++ b/src/org/thoughtcrime/securesms/providers/PartProvider.java @@ -31,7 +31,7 @@ import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.service.KeyCachingService; diff --git a/src/org/thoughtcrime/securesms/recipients/Recipient.java b/src/org/thoughtcrime/securesms/recipients/Recipient.java index 3aa2b95b5d..d120fa8127 100644 --- a/src/org/thoughtcrime/securesms/recipients/Recipient.java +++ b/src/org/thoughtcrime/securesms/recipients/Recipient.java @@ -16,19 +16,22 @@ */ package org.thoughtcrime.securesms.recipients; +import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; +import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; import org.thoughtcrime.securesms.recipients.RecipientProvider.RecipientDetails; import org.thoughtcrime.securesms.util.FutureTaskListener; import org.thoughtcrime.securesms.util.ListenableFutureTask; +import org.whispersystems.textsecure.storage.CanonicalRecipientAddress; import java.util.HashSet; -public class Recipient implements Parcelable { +public class Recipient implements Parcelable, CanonicalRecipientAddress { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Recipient createFromParcel(Parcel in) { @@ -145,6 +148,10 @@ public class Recipient implements Parcelable { return contactPhoto; } + public long getCanonicalAddress(Context context) { + return CanonicalAddressDatabase.getInstance(context).getCanonicalAddress(getNumber()); + } + public static interface RecipientModifiedListener { public void onModified(Recipient recipient); } diff --git a/src/org/thoughtcrime/securesms/recipients/Recipients.java b/src/org/thoughtcrime/securesms/recipients/Recipients.java index c7a0bb3f45..7ea7a56dff 100644 --- a/src/org/thoughtcrime/securesms/recipients/Recipients.java +++ b/src/org/thoughtcrime/securesms/recipients/Recipients.java @@ -16,12 +16,10 @@ */ package org.thoughtcrime.securesms.recipients; -import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.util.Patterns; -import org.thoughtcrime.securesms.crypto.KeyUtil; import org.thoughtcrime.securesms.recipients.Recipient.RecipientModifiedListener; import org.thoughtcrime.securesms.util.NumberUtil; diff --git a/src/org/thoughtcrime/securesms/service/ApplicationMigrationService.java b/src/org/thoughtcrime/securesms/service/ApplicationMigrationService.java index 464ad2f208..21258085ca 100644 --- a/src/org/thoughtcrime/securesms/service/ApplicationMigrationService.java +++ b/src/org/thoughtcrime/securesms/service/ApplicationMigrationService.java @@ -19,7 +19,7 @@ import android.util.Log; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.RoutingActivity; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.SmsMigrator; import org.thoughtcrime.securesms.database.SmsMigrator.ProgressDescription; diff --git a/src/org/thoughtcrime/securesms/service/KeyCachingService.java b/src/org/thoughtcrime/securesms/service/KeyCachingService.java index 0445d3ca81..2d4d7e9a71 100644 --- a/src/org/thoughtcrime/securesms/service/KeyCachingService.java +++ b/src/org/thoughtcrime/securesms/service/KeyCachingService.java @@ -22,24 +22,20 @@ import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.os.SystemClock; -import android.preference.PreferenceManager; -import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.RemoteViews; -import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.DatabaseUpgradeActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.RoutingActivity; import org.thoughtcrime.securesms.crypto.DecryptingQueue; import org.thoughtcrime.securesms.crypto.InvalidPassphraseException; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.util.TextSecurePreferences; diff --git a/src/org/thoughtcrime/securesms/service/MmsDownloader.java b/src/org/thoughtcrime/securesms/service/MmsDownloader.java index 6083b9a433..2921716601 100644 --- a/src/org/thoughtcrime/securesms/service/MmsDownloader.java +++ b/src/org/thoughtcrime/securesms/service/MmsDownloader.java @@ -24,7 +24,7 @@ import android.util.Pair; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.DecryptingQueue; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.database.model.NotificationMmsMessageRecord; diff --git a/src/org/thoughtcrime/securesms/service/MmsReceiver.java b/src/org/thoughtcrime/securesms/service/MmsReceiver.java index 85fe9ef0a4..871fdbae0d 100644 --- a/src/org/thoughtcrime/securesms/service/MmsReceiver.java +++ b/src/org/thoughtcrime/securesms/service/MmsReceiver.java @@ -21,14 +21,13 @@ import android.content.Intent; import android.util.Log; import android.util.Pair; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.mms.IncomingMediaMessage; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.textsecure.push.IncomingPushMessage; import org.whispersystems.textsecure.push.PushServiceSocket; -import org.whispersystems.textsecure.push.RateLimitException; import java.io.File; import java.io.IOException; diff --git a/src/org/thoughtcrime/securesms/service/MmsSender.java b/src/org/thoughtcrime/securesms/service/MmsSender.java index e0be5d9457..e63c576dfc 100644 --- a/src/org/thoughtcrime/securesms/service/MmsSender.java +++ b/src/org/thoughtcrime/securesms/service/MmsSender.java @@ -21,14 +21,13 @@ import android.content.Intent; import android.util.Log; import android.util.Pair; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.service.SendReceiveService.ToastHandler; -import org.thoughtcrime.securesms.transport.MmsTransport; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import org.thoughtcrime.securesms.transport.UniversalTransport; diff --git a/src/org/thoughtcrime/securesms/service/RegistrationService.java b/src/org/thoughtcrime/securesms/service/RegistrationService.java index 6370865a8f..eefa969396 100644 --- a/src/org/thoughtcrime/securesms/service/RegistrationService.java +++ b/src/org/thoughtcrime/securesms/service/RegistrationService.java @@ -13,9 +13,9 @@ import android.util.Pair; import com.google.android.gcm.GCMRegistrar; import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.PreKeyUtil; -import org.thoughtcrime.securesms.database.keys.PreKeyRecord; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.PreKeyUtil; +import org.whispersystems.textsecure.storage.PreKeyRecord; import org.thoughtcrime.securesms.gcm.GcmIntentService; import org.thoughtcrime.securesms.gcm.GcmRegistrationTimeoutException; import org.thoughtcrime.securesms.util.TextSecurePreferences; diff --git a/src/org/thoughtcrime/securesms/service/SendReceiveService.java b/src/org/thoughtcrime/securesms/service/SendReceiveService.java index b59f537f54..28573124d8 100644 --- a/src/org/thoughtcrime/securesms/service/SendReceiveService.java +++ b/src/org/thoughtcrime/securesms/service/SendReceiveService.java @@ -29,7 +29,7 @@ import android.os.Message; import android.util.Log; import android.widget.Toast; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.CanonicalSessionMigrator; import org.thoughtcrime.securesms.util.WorkerThread; diff --git a/src/org/thoughtcrime/securesms/service/SmsReceiver.java b/src/org/thoughtcrime/securesms/service/SmsReceiver.java index 7b0fadd518..9fb53684b8 100644 --- a/src/org/thoughtcrime/securesms/service/SmsReceiver.java +++ b/src/org/thoughtcrime/securesms/service/SmsReceiver.java @@ -18,17 +18,15 @@ package org.thoughtcrime.securesms.service; import android.content.Context; import android.content.Intent; -import android.preference.PreferenceManager; import android.util.Log; import android.util.Pair; -import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.crypto.DecryptingQueue; -import org.thoughtcrime.securesms.crypto.InvalidKeyException; +import org.whispersystems.textsecure.crypto.InvalidKeyException; import org.thoughtcrime.securesms.crypto.InvalidVersionException; import org.thoughtcrime.securesms.crypto.KeyExchangeMessage; import org.thoughtcrime.securesms.crypto.KeyExchangeProcessor; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; diff --git a/src/org/thoughtcrime/securesms/service/SmsSender.java b/src/org/thoughtcrime/securesms/service/SmsSender.java index 5132978606..a982bda673 100644 --- a/src/org/thoughtcrime/securesms/service/SmsSender.java +++ b/src/org/thoughtcrime/securesms/service/SmsSender.java @@ -25,7 +25,7 @@ import android.telephony.SmsMessage; import android.util.Log; import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; diff --git a/src/org/thoughtcrime/securesms/sms/MessageSender.java b/src/org/thoughtcrime/securesms/sms/MessageSender.java index 2716643fa3..8ef6347a18 100644 --- a/src/org/thoughtcrime/securesms/sms/MessageSender.java +++ b/src/org/thoughtcrime/securesms/sms/MessageSender.java @@ -20,7 +20,7 @@ import android.content.Context; import android.content.Intent; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.mms.SlideDeck; diff --git a/src/org/thoughtcrime/securesms/sms/SmsTransportDetails.java b/src/org/thoughtcrime/securesms/sms/SmsTransportDetails.java index 4de3ba15dd..0a7283a9fc 100644 --- a/src/org/thoughtcrime/securesms/sms/SmsTransportDetails.java +++ b/src/org/thoughtcrime/securesms/sms/SmsTransportDetails.java @@ -18,8 +18,8 @@ package org.thoughtcrime.securesms.sms; import android.util.Log; -import org.thoughtcrime.securesms.crypto.SessionCipher; -import org.thoughtcrime.securesms.crypto.TransportDetails; +import org.whispersystems.textsecure.crypto.SessionCipher; +import org.whispersystems.textsecure.crypto.TransportDetails; import org.thoughtcrime.securesms.protocol.WirePrefix; import org.whispersystems.textsecure.util.Base64; diff --git a/src/org/thoughtcrime/securesms/transport/BaseTransportDetails.java b/src/org/thoughtcrime/securesms/transport/BaseTransportDetails.java index b93d837196..f18001cde0 100644 --- a/src/org/thoughtcrime/securesms/transport/BaseTransportDetails.java +++ b/src/org/thoughtcrime/securesms/transport/BaseTransportDetails.java @@ -1,6 +1,6 @@ package org.thoughtcrime.securesms.transport; -import org.thoughtcrime.securesms.crypto.TransportDetails; +import org.whispersystems.textsecure.crypto.TransportDetails; import org.whispersystems.textsecure.util.Base64; import java.io.IOException; diff --git a/src/org/thoughtcrime/securesms/transport/MmsTransport.java b/src/org/thoughtcrime/securesms/transport/MmsTransport.java index 9b150f9fd2..fd7e320b12 100644 --- a/src/org/thoughtcrime/securesms/transport/MmsTransport.java +++ b/src/org/thoughtcrime/securesms/transport/MmsTransport.java @@ -5,8 +5,8 @@ import android.telephony.TelephonyManager; import android.util.Log; import android.util.Pair; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.SessionCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.SessionCipher; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.mms.MmsRadio; import org.thoughtcrime.securesms.mms.MmsRadioException; @@ -14,7 +14,7 @@ import org.thoughtcrime.securesms.mms.MmsSendHelper; import org.thoughtcrime.securesms.mms.TextTransport; import org.thoughtcrime.securesms.protocol.WirePrefix; import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Hex; +import org.whispersystems.textsecure.util.Hex; import java.io.IOException; import java.util.Arrays; diff --git a/src/org/thoughtcrime/securesms/transport/PushTransport.java b/src/org/thoughtcrime/securesms/transport/PushTransport.java index 173041ad92..fc3155ec74 100644 --- a/src/org/thoughtcrime/securesms/transport/PushTransport.java +++ b/src/org/thoughtcrime/securesms/transport/PushTransport.java @@ -3,7 +3,7 @@ package org.thoughtcrime.securesms.transport; import android.content.Context; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.mms.PartParser; import org.thoughtcrime.securesms.util.TextSecurePreferences; diff --git a/src/org/thoughtcrime/securesms/transport/SmsTransport.java b/src/org/thoughtcrime/securesms/transport/SmsTransport.java index 3da72406eb..fbe4061891 100644 --- a/src/org/thoughtcrime/securesms/transport/SmsTransport.java +++ b/src/org/thoughtcrime/securesms/transport/SmsTransport.java @@ -2,13 +2,11 @@ package org.thoughtcrime.securesms.transport; import android.app.PendingIntent; import android.content.Context; -import android.content.Intent; -import android.net.Uri; import android.telephony.SmsManager; import android.util.Log; -import org.thoughtcrime.securesms.crypto.MasterSecret; -import org.thoughtcrime.securesms.crypto.SessionCipher; +import org.whispersystems.textsecure.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.SessionCipher; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.service.SendReceiveService; diff --git a/src/org/thoughtcrime/securesms/transport/UniversalTransport.java b/src/org/thoughtcrime/securesms/transport/UniversalTransport.java index 597b48418c..e468cc1c62 100644 --- a/src/org/thoughtcrime/securesms/transport/UniversalTransport.java +++ b/src/org/thoughtcrime/securesms/transport/UniversalTransport.java @@ -4,13 +4,12 @@ import android.content.Context; import android.util.Log; import android.util.Pair; -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.textsecure.directory.NumberFilter; -import org.whispersystems.textsecure.util.PhoneNumberFormatter; import java.io.IOException; import java.util.LinkedList; diff --git a/src/org/thoughtcrime/securesms/util/Combiner.java b/src/org/thoughtcrime/securesms/util/Combiner.java deleted file mode 100644 index 75d83df181..0000000000 --- a/src/org/thoughtcrime/securesms/util/Combiner.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (C) 2011 Whisper Systems - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.thoughtcrime.securesms.util; - -public class Combiner { - - public static byte[] combine(byte[] a, byte[] b) { - byte[] combined = new byte[a.length + b.length]; - System.arraycopy(a, 0, combined, 0, a.length); - System.arraycopy(b, 0, combined, a.length, b.length); - return combined; - } - - public static byte[] combine(byte[] a, byte[] b, byte[] c) { - byte[] combined = new byte[a.length + b.length + c.length]; - System.arraycopy(a, 0, combined, 0, a.length); - System.arraycopy(b, 0, combined, a.length, b.length); - System.arraycopy(c, 0, combined, a.length + b.length, c.length); - return combined; - } - - public static byte[] combine(byte[] a, byte[] b, byte[] c, byte[] d) { - byte[] combined = new byte[a.length + b.length + c.length + d.length]; - System.arraycopy(a, 0, combined, 0, a.length); - System.arraycopy(b, 0, combined, a.length, b.length); - System.arraycopy(c, 0, combined, a.length + b.length, c.length); - System.arraycopy(d, 0, combined, a.length + b.length + c.length, d.length); - return combined; - } - -} diff --git a/src/org/thoughtcrime/securesms/util/MemoryCleaner.java b/src/org/thoughtcrime/securesms/util/MemoryCleaner.java index 5100d7dacc..cf6ec1d056 100644 --- a/src/org/thoughtcrime/securesms/util/MemoryCleaner.java +++ b/src/org/thoughtcrime/securesms/util/MemoryCleaner.java @@ -19,9 +19,7 @@ package org.thoughtcrime.securesms.util; import java.lang.reflect.Field; import java.util.Arrays; -import javax.crypto.spec.SecretKeySpec; - -import org.thoughtcrime.securesms.crypto.MasterSecret; +import org.whispersystems.textsecure.crypto.MasterSecret; import android.util.Log; diff --git a/src/org/thoughtcrime/securesms/util/Util.java b/src/org/thoughtcrime/securesms/util/Util.java index ad1fb81126..59779dcc22 100644 --- a/src/org/thoughtcrime/securesms/util/Util.java +++ b/src/org/thoughtcrime/securesms/util/Util.java @@ -43,34 +43,6 @@ import ws.com.google.android.mms.pdu.EncodedStringValue; public class Util { - public static byte[] combine(byte[] one, byte[] two) { - byte[] combined = new byte[one.length + two.length]; - System.arraycopy(one, 0, combined, 0, one.length); - System.arraycopy(two, 0, combined, one.length, two.length); - - return combined; - } - - public static byte[] combine(byte[] one, byte[] two, byte[] three) { - byte[] combined = new byte[one.length + two.length + three.length]; - System.arraycopy(one, 0, combined, 0, one.length); - System.arraycopy(two, 0, combined, one.length, two.length); - System.arraycopy(three, 0, combined, one.length + two.length, three.length); - - return combined; - } - - public static byte[] combine(byte[] one, byte[] two, byte[] three, byte[] four) { - byte[] combined = new byte[one.length + two.length + three.length + four.length]; - System.arraycopy(one, 0, combined, 0, one.length); - System.arraycopy(two, 0, combined, one.length, two.length); - System.arraycopy(three, 0, combined, one.length + two.length, three.length); - System.arraycopy(four, 0, combined, one.length + two.length + three.length, four.length); - - return combined; - - } - public static String[] splitString(String string, int maxLength) { int count = string.length() / maxLength;