Skip to content

Commit

Permalink
Merge pull request #1594 from bemusementpark/shared-random
Browse files Browse the repository at this point in the history
Share SecureRandom
  • Loading branch information
bemusementpark authored Aug 5, 2024
2 parents cd1a064 + f5d1deb commit 415264e
Show file tree
Hide file tree
Showing 26 changed files with 98 additions and 155 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,16 @@ import android.view.View
import com.annimon.stream.Stream
import com.google.android.mms.pdu_alt.CharacterSets
import com.google.android.mms.pdu_alt.EncodedStringValue
import network.loki.messenger.R
import org.session.libsignal.utilities.Log
import org.thoughtcrime.securesms.components.ComposeText
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.security.SecureRandom
import java.util.Arrays
import java.util.Collections
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min
import network.loki.messenger.R
import org.session.libsignal.utilities.Log
import org.thoughtcrime.securesms.components.ComposeText

object Util {
private val TAG: String = Log.tag(Util::class.java)
Expand Down Expand Up @@ -248,32 +246,6 @@ object Util {
return result
}

fun getSecretBytes(size: Int): ByteArray {
return getSecretBytes(SecureRandom(), size)
}

fun getSecretBytes(secureRandom: SecureRandom, size: Int): ByteArray {
val secret = ByteArray(size)
secureRandom.nextBytes(secret)
return secret
}

fun <T> getRandomElement(elements: Array<T>): T {
return elements[SecureRandom().nextInt(elements.size)]
}

fun <T> getRandomElement(elements: List<T>): T {
return elements[SecureRandom().nextInt(elements.size)]
}

fun equals(a: Any?, b: Any?): Boolean {
return a === b || (a != null && a == b)
}

fun hashCode(vararg objects: Any?): Int {
return objects.contentHashCode()
}

fun uri(uri: String?): Uri? {
return if (uri == null) null
else Uri.parse(uri)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package org.thoughtcrime.securesms.crypto;


import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;

import org.session.libsession.utilities.TextSecurePreferences;

import java.security.SecureRandom;

/**
* A provider that is responsible for creating or retrieving the AttachmentSecret model.
*
Expand Down Expand Up @@ -81,9 +81,8 @@ private AttachmentSecret getEncryptedAttachmentSecret(@NonNull String serialized
}

private AttachmentSecret createAndStoreAttachmentSecret(@NonNull Context context) {
SecureRandom random = new SecureRandom();
byte[] secret = new byte[32];
random.nextBytes(secret);
SECURE_RANDOM.nextBytes(secret);

AttachmentSecret attachmentSecret = new AttachmentSecret(null, null, secret);
storeAttachmentSecret(context, attachmentSecret);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package org.thoughtcrime.securesms.crypto;


import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;

import org.session.libsession.utilities.TextSecurePreferences;

import java.io.IOException;
import java.security.SecureRandom;

public class DatabaseSecretProvider {

Expand Down Expand Up @@ -60,9 +61,8 @@ private DatabaseSecret getEncryptedDatabaseSecret(@NonNull String serializedEncr
}

private DatabaseSecret createAndStoreDatabaseSecret(@NonNull Context context) {
SecureRandom random = new SecureRandom();
byte[] secret = new byte[32];
random.nextBytes(secret);
SECURE_RANDOM.nextBytes(secret);

DatabaseSecret databaseSecret = new DatabaseSecret(secret);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.thoughtcrime.securesms.crypto;


import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import androidx.annotation.NonNull;
import android.util.Pair;

Expand All @@ -11,7 +13,6 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
Expand All @@ -31,7 +32,7 @@ public static Pair<byte[], OutputStream> createFor(@NonNull AttachmentSecret att
throws IOException
{
byte[] random = new byte[32];
new SecureRandom().nextBytes(random);
SECURE_RANDOM.nextBytes(random);

try {
Mac mac = Mac.getInstance("HmacSHA256");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.thoughtcrime.securesms.database;

import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
Expand All @@ -26,7 +28,6 @@
import org.thoughtcrime.securesms.util.BitmapUtil;

import java.io.Closeable;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
Expand Down Expand Up @@ -303,7 +304,7 @@ public void updateProfilePicture(String groupID, Bitmap newValue) {
public void updateProfilePicture(String groupID, byte[] newValue) {
long avatarId;

if (newValue != null) avatarId = Math.abs(new SecureRandom().nextLong());
if (newValue != null) avatarId = Math.abs(SECURE_RANDOM.nextLong());
else avatarId = 0;


Expand Down Expand Up @@ -458,12 +459,6 @@ public void setActive(String groupId, boolean active) {
database.update(TABLE_NAME, values, GROUP_ID + " = ?", new String[] {groupId});
}

public byte[] allocateGroupId() {
byte[] groupId = new byte[16];
new SecureRandom().nextBytes(groupId);
return groupId;
}

public boolean hasGroup(@NonNull String groupId) {
try (Cursor cursor = databaseHelper.getReadableDatabase().rawQuery(
"SELECT 1 FROM " + TABLE_NAME + " WHERE " + GROUP_ID + " = ? LIMIT 1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ import org.session.libsession.utilities.IdentityKeyMismatchList
import org.session.libsession.utilities.NetworkFailure
import org.session.libsession.utilities.NetworkFailureList
import org.session.libsession.utilities.TextSecurePreferences.Companion.isReadReceiptsEnabled
import org.session.libsession.utilities.Util.toIsoBytes
import org.session.libsession.utilities.recipients.Recipient
import org.session.libsignal.utilities.JsonUtil
import org.session.libsignal.utilities.Log
import org.session.libsignal.utilities.ThreadUtils.queue
import org.session.libsignal.utilities.Util.SECURE_RANDOM
import org.session.libsignal.utilities.guava.Optional
import org.thoughtcrime.securesms.attachments.MmsNotificationAttachment
import org.thoughtcrime.securesms.database.SmsDatabase.InsertListener
Expand All @@ -66,7 +66,6 @@ import org.thoughtcrime.securesms.mms.SlideDeck
import org.thoughtcrime.securesms.util.asSequence
import java.io.Closeable
import java.io.IOException
import java.security.SecureRandom
import java.util.LinkedList

class MmsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : MessagingDatabase(context, databaseHelper) {
Expand Down Expand Up @@ -1200,7 +1199,7 @@ class MmsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : Messa

inner class OutgoingMessageReader(private val message: OutgoingMediaMessage?,
private val threadId: Long) {
private val id = SecureRandom().nextLong()
private val id = SECURE_RANDOM.nextLong()
val current: MessageRecord
get() {
val slideDeck = SlideDeck(context, message!!.attachments)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
*/
package org.thoughtcrime.securesms.database;

import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
Expand Down Expand Up @@ -49,7 +51,6 @@
import org.thoughtcrime.securesms.dependencies.DatabaseComponent;
import java.io.Closeable;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
Expand Down Expand Up @@ -784,7 +785,7 @@ public class OutgoingMessageReader {
public OutgoingMessageReader(OutgoingTextMessage message, long threadId) {
this.message = message;
this.threadId = threadId;
this.id = new SecureRandom().nextLong();
this.id = SECURE_RANDOM.nextLong();
}

public MessageRecord getCurrent() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package org.thoughtcrime.securesms.glide;

import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.security.SecureRandom;

import okhttp3.Headers;
import okhttp3.Interceptor;
Expand All @@ -30,15 +31,15 @@ public class PaddedHeadersInterceptor implements Interceptor {

private @NonNull Headers getPaddedHeaders(@NonNull Headers headers) {
return headers.newBuilder()
.add(PADDING_HEADER, getRandomString(new SecureRandom(), MIN_RANDOM_BYTES, MAX_RANDOM_BYTES))
.add(PADDING_HEADER, getRandomString(MIN_RANDOM_BYTES, MAX_RANDOM_BYTES))
.build();
}

private static @NonNull String getRandomString(@NonNull SecureRandom secureRandom, int minLength, int maxLength) {
char[] buffer = new char[secureRandom.nextInt(maxLength - minLength) + minLength];
private static @NonNull String getRandomString(int minLength, int maxLength) {
char[] buffer = new char[SECURE_RANDOM.nextInt(maxLength - minLength) + minLength];

for (int i = 0 ; i < buffer.length; i++) {
buffer[i] = (char) (secureRandom.nextInt(74) + 48); // Random char from 0-Z
buffer[i] = (char) (SECURE_RANDOM.nextInt(74) + 48); // Random char from 0-Z
}

return new String(buffer);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.thoughtcrime.securesms.logging;

import static org.session.libsignal.crypto.CipherUtil.CIPHER_LOCK;
import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import androidx.annotation.NonNull;

Expand All @@ -17,7 +18,6 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
Expand Down Expand Up @@ -64,7 +64,7 @@ public static class Writer {
}

void writeEntry(@NonNull String entry) throws IOException {
new SecureRandom().nextBytes(ivBuffer);
SECURE_RANDOM.nextBytes(ivBuffer);

byte[] plaintext = entry.getBytes();
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.thoughtcrime.securesms.logging;

import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;
Expand All @@ -9,7 +11,6 @@
import org.session.libsession.utilities.TextSecurePreferences;

import java.io.IOException;
import java.security.SecureRandom;

class LogSecretProvider {

Expand Down Expand Up @@ -40,9 +41,8 @@ private static byte[] parseEncryptedSecret(String secret) {
}

private static byte[] createAndStoreSecret(@NonNull Context context) {
SecureRandom random = new SecureRandom();
byte[] secret = new byte[32];
random.nextBytes(secret);
SECURE_RANDOM.nextBytes(secret);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
KeyStoreHelper.SealedData encryptedSecret = KeyStoreHelper.seal(secret);
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/org/thoughtcrime/securesms/mms/Slide.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ import android.content.res.Resources
import android.net.Uri
import androidx.annotation.DrawableRes
import com.squareup.phrase.Phrase
import java.security.SecureRandom
import network.loki.messenger.R
import org.session.libsession.messaging.sending_receiving.attachments.Attachment
import org.session.libsession.messaging.sending_receiving.attachments.AttachmentTransferProgress
import org.session.libsession.messaging.sending_receiving.attachments.UriAttachment
import org.session.libsession.utilities.StringSubstitutionConstants.EMOJI_KEY
import org.session.libsession.utilities.Util.equals
import org.session.libsession.utilities.Util.hashCode
import org.session.libsignal.utilities.Util.SECURE_RANDOM
import org.session.libsignal.utilities.guava.Optional
import org.thoughtcrime.securesms.conversation.v2.Util
import org.thoughtcrime.securesms.util.MediaUtil
Expand Down Expand Up @@ -160,7 +160,7 @@ abstract class Slide(@JvmField protected val context: Context, protected val att
): Attachment {
val resolvedType =
Optional.fromNullable(MediaUtil.getMimeType(context, uri)).or(defaultMime)
val fastPreflightId = SecureRandom().nextLong().toString()
val fastPreflightId = SECURE_RANDOM.nextLong().toString()
return UriAttachment(
uri,
if (hasThumbnail) uri else null,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.thoughtcrime.securesms.net;

import static org.session.libsignal.utilities.Util.SECURE_RANDOM;

import androidx.annotation.NonNull;
import android.text.TextUtils;

Expand All @@ -15,7 +17,6 @@
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
Expand Down Expand Up @@ -54,7 +55,7 @@ public RequestController fetch(@NonNull String url, long contentLength, @NonNull
private RequestController fetchChunksWithUnknownTotalSize(@NonNull String url, @NonNull Callback callback) {
CompositeRequestController compositeController = new CompositeRequestController();

long chunkSize = new SecureRandom().nextInt(1024) + 1024;
long chunkSize = SECURE_RANDOM.nextInt(1024) + 1024;
Request request = new Request.Builder()
.url(url)
.cacheControl(NO_CACHE)
Expand Down
Loading

0 comments on commit 415264e

Please sign in to comment.