Compare commits

...
Author SHA1 Message Date
tobiasKaminsky db407b0b6a test with 500mb
long to support more than 2gb files

Signed-off-by: tobiasKaminsky <[email protected]>
2023-07-28 18:49:28 +02:00
tobiasKaminsky 5b2c912a66 Encrypt large files with temporary file
Signed-off-by: tobiasKaminsky <[email protected]>
2023-07-28 18:49:28 +02:00
5 changed files with 223 additions and 79 deletions

No files matched your search

@@ -55,6 +55,7 @@ import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.Objects;
@@ -244,12 +245,35 @@ public abstract class AbstractIT {
}
}
public static File createFile(String name, int iteration) throws IOException {
File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name);
public static File createFile(String name, long size) throws IOException {
File file = new File(FileStorageUtils.getInternalTemporalPath(account.name, targetContext) + File.separator + name);
if (!file.getParentFile().exists()) {
assertTrue(file.getParentFile().mkdirs());
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.setLength(size);
randomAccessFile.close();
return file;
}
public static File createFile(String name, int iteration) throws IOException {
File file = new File(FileStorageUtils.getInternalTemporalPath(account.name, targetContext) + File.separator + name);
if (!file.getParentFile().exists()) {
assertTrue(file.getParentFile().mkdirs());
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter writer = new FileWriter(file);
@@ -35,6 +35,7 @@ import com.owncloud.android.datamodel.DecryptedFolderMetadata;
import com.owncloud.android.datamodel.EncryptedFolderMetadata;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.utils.CsrHelper;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.EncryptionUtils;
import org.apache.commons.codec.binary.Hex;
@@ -44,7 +45,6 @@ import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
@@ -65,7 +65,6 @@ import javax.crypto.BadPaddingException;
import androidx.test.runner.AndroidJUnit4;
import static com.owncloud.android.utils.EncryptionUtils.EncryptedFile;
import static com.owncloud.android.utils.EncryptionUtils.decodeStringToBase64Bytes;
import static com.owncloud.android.utils.EncryptionUtils.decryptFile;
import static com.owncloud.android.utils.EncryptionUtils.decryptFolderMetaData;
@@ -91,6 +90,7 @@ import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(AndroidJUnit4.class)
@@ -401,6 +401,19 @@ public class EncryptionTestIT extends AbstractIT {
assertTrue(cryptFile("ia7OEEEyXMoRa1QWQk8r", "78f42172166f9dc8fd1a7156b1753353", key, iv, authTag));
}
@Test
public void testLargeFile() throws Exception {
byte[] key = decodeStringToBase64Bytes("WANM0gRv+DhaexIsI0T3Lg==");
byte[] iv = decodeStringToBase64Bytes("gKm3n+mJzeY26q4OfuZEqg==");
createFile("large1", 500 * 1024 * 1024L);
File file = getDummyFile("large1");
String md5 = getMD5Sum(file);
Log_OC.d("Large file", "Size: " + DisplayUtils.bytesToHumanReadable(file.length()));
assertTrue(cryptFile(file, md5, key, iv, null));
}
@Test
public void cryptFileWithMetadata() throws Exception {
DecryptedFolderMetadata metadata = generateFolderMetadata();
@@ -751,28 +764,34 @@ public class EncryptionTestIT extends AbstractIT {
private boolean cryptFile(String fileName, String md5, byte[] key, byte[] iv, byte[] expectedAuthTag)
throws Exception {
File file = getFile(fileName);
return cryptFile(file, md5, key, iv, expectedAuthTag);
}
private boolean cryptFile(File file, String md5, byte[] key, byte[] iv, byte[] expectedAuthTag)
throws Exception {
assertEquals(md5, getMD5Sum(file));
EncryptedFile encryptedFile = encryptFile(file, key, iv);
File encryptedLargeTempFile = File.createTempFile("largeEncrypted", "tmp");
byte[] authenticationTag = encryptFile(file, encryptedLargeTempFile, key, iv);
File encryptedTempFile = File.createTempFile("file", "tmp");
FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
fileOutputStream.write(encryptedFile.encryptedBytes);
fileOutputStream.close();
byte[] authenticationTag = decodeStringToBase64Bytes(encryptedFile.authenticationTag);
assertNotNull(authenticationTag);
// verify authentication tag
assertTrue(Arrays.equals(expectedAuthTag, authenticationTag));
if (expectedAuthTag != null) {
assertEquals(expectedAuthTag, authenticationTag);
}
byte[] decryptedBytes = decryptFile(encryptedTempFile, key, iv, authenticationTag);
File decryptedLargeTempFile = File.createTempFile("largeDecrypted", "tmp");
assertTrue(decryptFile(encryptedLargeTempFile,
decryptedLargeTempFile,
key,
iv,
authenticationTag
)
);
File decryptedFile = File.createTempFile("file", "dec");
FileOutputStream fileOutputStream1 = new FileOutputStream(decryptedFile);
fileOutputStream1.write(decryptedBytes);
fileOutputStream1.close();
return md5.compareTo(getMD5Sum(decryptedFile)) == 0;
return md5.compareTo(getMD5Sum(decryptedLargeTempFile)) == 0;
}
private String getMD5Sum(File file) {
@@ -41,7 +41,6 @@ import com.owncloud.android.utils.FileExportUtils;
import com.owncloud.android.utils.FileStorageUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
@@ -213,11 +212,18 @@ public class DownloadFileOperation extends RemoteOperation {
.get(file.getEncryptedFileName()).getAuthenticationTag());
try {
byte[] decryptedBytes = EncryptionUtils.decryptFile(tmpFile, key, iv, authenticationTag);
File decryptedFile = new File(getTmpPath() + "_dec");
boolean success = EncryptionUtils.decryptFile(tmpFile, decryptedFile, key, iv, authenticationTag);
try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile)) {
fileOutputStream.write(decryptedBytes);
if (!success) {
return new RemoteOperationResult(new IllegalStateException("Decryption went wrong!"));
}
decryptedFile.renameTo(tmpFile);
if (decryptedFile.exists()) {
decryptedFile.delete();
}
} catch (Exception e) {
return new RemoteOperationResult(e);
}
@@ -509,8 +509,6 @@ public class UploadFileOperation extends SyncOperation {
// IV, always generate new one
byte[] iv = EncryptionUtils.randomBytes(EncryptionUtils.ivLength);
EncryptionUtils.EncryptedFile encryptedFile = EncryptionUtils.encryptFile(mFile, key, iv);
// new random file name, check if it exists in metadata
String encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
@@ -519,9 +517,7 @@ public class UploadFileOperation extends SyncOperation {
}
File encryptedTempFile = File.createTempFile("encFile", encryptedFileName);
FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
fileOutputStream.write(encryptedFile.encryptedBytes);
fileOutputStream.close();
byte[] authenticationTag = EncryptionUtils.encryptFile(mFile, encryptedTempFile, key, iv);
/***** E2E *****/
@@ -614,7 +610,7 @@ public class UploadFileOperation extends SyncOperation {
decryptedFile.setEncrypted(data);
decryptedFile.setInitializationVector(EncryptionUtils.encodeBytesToBase64String(iv));
decryptedFile.setAuthenticationTag(encryptedFile.authenticationTag);
decryptedFile.setAuthenticationTag(EncryptionUtils.encodeBytesToBase64String(authenticationTag));
metadata.getFiles().put(encryptedFileName, decryptedFile);
@@ -54,10 +54,11 @@ import org.apache.commons.httpclient.HttpStatus;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
@@ -123,6 +124,7 @@ public final class EncryptionUtils {
private static final String AES = "AES";
private static final String RSA_CIPHER = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private static final String RSA = "RSA";
private static final int AUTHENTICATION_TAG_LENGTH = 16;
@VisibleForTesting
public static final String MIGRATED_FOLDER_IDS = "MIGRATED_FOLDER_IDS";
@@ -250,7 +252,7 @@ public final class EncryptionUtils {
// check authentication tag
byte[] extractedAuthenticationTag = Arrays.copyOfRange(bytes,
bytes.length - (128 / 8),
bytes.length - AUTHENTICATION_TAG_LENGTH,
bytes.length);
String encryptedTag = encodeBytesToBase64String(extractedAuthenticationTag);
@@ -488,76 +490,173 @@ public final class EncryptionUtils {
* {@link EncryptionUtils#randomBytes(int)}
* @return encryptedFile with encryptedBytes and authenticationTag
*/
public static EncryptedFile encryptFile(OCFile ocFile, byte[] encryptionKeyBytes, byte[] iv)
throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException, IOException {
File file = new File(ocFile.getStoragePath());
public static byte[] encryptFile(OCFile ocFile,
File outputFile,
byte[] encryptionKeyBytes,
byte[] iv) {
File inputFile = new File(ocFile.getStoragePath());
return encryptFile(file, encryptionKeyBytes, iv);
return encryptFile(inputFile, outputFile, encryptionKeyBytes, iv);
}
/**
* @param file file do crypt
* @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()}
* @param iv initialization vector, either from metadata or
* {@link EncryptionUtils#randomBytes(int)}
* @return encryptedFile with encryptedBytes and authenticationTag
*/
public static EncryptedFile encryptFile(File file, byte[] encryptionKeyBytes, byte[] iv)
throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException, IOException {
// /**
// * @param file file do crypt
// * @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()}
// * @param iv initialization vector, either from metadata or
// * {@link EncryptionUtils#randomBytes(int)}
// * @return encryptedFile with encryptedBytes and authenticationTag
// */
// public static EncryptedFile encryptFile(File file, byte[] encryptionKeyBytes, byte[] iv)
// throws NoSuchAlgorithmException,
// InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException,
// BadPaddingException, IllegalBlockSizeException, IOException {
//
// Cipher cipher = Cipher.getInstance(AES_CIPHER);
//
// Key key = new SecretKeySpec(encryptionKeyBytes, AES);
//
// GCMParameterSpec spec = new GCMParameterSpec(128, iv);
// cipher.init(Cipher.ENCRYPT_MODE, key, spec);
//
// RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
// byte[] fileBytes = new byte[(int) randomAccessFile.length()];
// randomAccessFile.readFully(fileBytes);
//
// byte[] cryptedBytes = cipher.doFinal(fileBytes);
// String authenticationTag = encodeBytesToBase64String(Arrays.copyOfRange(cryptedBytes,
// cryptedBytes.length - AUTHENTICATION_TAG_LENGTH,
// cryptedBytes.length));
//
// return new EncryptedFile(cryptedBytes, authenticationTag);
// }
Cipher cipher = Cipher.getInstance(AES_CIPHER);
public static byte[] encryptFile(File inputFile,
File outputFile,
byte[] encryptionKeyBytes,
byte[] iv) {
// TODO
// use https://stackoverflow.com/a/65874176
// write test to make sure it is the same
// check for storage size
// delete copy of file, make sure it is a random file
Key key = new SecretKeySpec(encryptionKeyBytes, AES);
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
Cipher cipher = Cipher.getInstance(AES_CIPHER);
Key key = new SecretKeySpec(encryptionKeyBytes, AES);
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
byte[] fileBytes = new byte[(int) randomAccessFile.length()];
randomAccessFile.readFully(fileBytes);
byte[] inputBytes = new byte[4096];
for (int n = inputStream.read(inputBytes); n > 0; n = inputStream.read(inputBytes)) {
byte[] outputBytes = cipher.update(inputBytes, 0, n);
outputStream.write(outputBytes);
}
byte[] outputBytes = cipher.doFinal();
outputStream.write(outputBytes);
byte[] cryptedBytes = cipher.doFinal(fileBytes);
String authenticationTag = encodeBytesToBase64String(Arrays.copyOfRange(cryptedBytes,
cryptedBytes.length - (128 / 8), cryptedBytes.length));
// authentication tag
byte[] authenticationTag = Arrays.copyOfRange(outputBytes,
outputBytes.length - AUTHENTICATION_TAG_LENGTH,
outputBytes.length);
return new EncryptedFile(cryptedBytes, authenticationTag);
if (authenticationTag.length != AUTHENTICATION_TAG_LENGTH) {
throw new SecurityException("Authentication tag length mismatches!");
}
return authenticationTag;
} catch (Exception e) {
return null;
}
}
// /**
// * @param file encrypted file
// * @param encryptionKeyBytes key from metadata
// * @param iv initialization vector from metadata
// * @param authenticationTag authenticationTag from metadata
// * @return decrypted byte[]
// */
// public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag)
// throws NoSuchAlgorithmException,
// InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException,
// BadPaddingException, IllegalBlockSizeException, IOException {
//
//
// Cipher cipher = Cipher.getInstance(AES_CIPHER);
// Key key = new SecretKeySpec(encryptionKeyBytes, AES);
// GCMParameterSpec spec = new GCMParameterSpec(128, iv);
// cipher.init(Cipher.DECRYPT_MODE, key, spec);
//
// RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
// byte[] fileBytes = new byte[(int) randomAccessFile.length()];
// randomAccessFile.readFully(fileBytes);
//
// // check authentication tag
// byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes,
// fileBytes.length - AUTHENTICATION_TAG_LENGTH,
// fileBytes.length);
//
// if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) {
// throw new SecurityException("Tag not correct");
// }
//
// return cipher.doFinal(fileBytes);
// }
/**
* @param file encrypted file
* @param inputFile encrypted file
* @param outputFile file to store decryptedFile
* @param encryptionKeyBytes key from metadata
* @param iv initialization vector from metadata
* @param authenticationTag authenticationTag from metadata
* @return decrypted byte[]
*/
public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag)
throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException, IOException {
public static boolean decryptFile(File inputFile,
File outputFile,
byte[] encryptionKeyBytes,
byte[] iv,
byte[] authenticationTag) {
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
Cipher cipher = Cipher.getInstance(AES_CIPHER);
Key key = new SecretKeySpec(encryptionKeyBytes, AES);
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
Cipher cipher = Cipher.getInstance(AES_CIPHER);
Key key = new SecretKeySpec(encryptionKeyBytes, AES);
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
byte[] fileBytes = new byte[(int) randomAccessFile.length()];
randomAccessFile.readFully(fileBytes);
// check authentication tag
byte[] extractedAuthenticationTag = new byte[AUTHENTICATION_TAG_LENGTH];
inputStream.getChannel().position(inputFile.length() - AUTHENTICATION_TAG_LENGTH);
// check authentication tag
byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes,
fileBytes.length - (128 / 8), fileBytes.length);
int readBytes = inputStream.read(extractedAuthenticationTag,
0,
AUTHENTICATION_TAG_LENGTH);
if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) {
throw new SecurityException("Tag not correct");
if (readBytes != AUTHENTICATION_TAG_LENGTH) {
throw new SecurityException("Authentication tag length mismatches!");
}
inputStream.getChannel().position(0);
if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) {
throw new SecurityException("Tag not correct");
}
byte[] inputBytes = new byte[4096];
for (int n = inputStream.read(inputBytes); n > 0; n = inputStream.read(inputBytes)) {
byte[] outputBytes = cipher.update(inputBytes, 0, n);
outputStream.write(outputBytes);
}
byte[] outputBytes = cipher.doFinal();
outputStream.write(outputBytes);
return true;
} catch (Exception e) {
return false;
}
return cipher.doFinal(fileBytes);
}
public static class EncryptedFile {
@@ -729,7 +828,7 @@ public final class EncryptionUtils {
// check authentication tag
byte[] extractedAuthenticationTag = Arrays.copyOfRange(bytes,
bytes.length - (128 / 8),
bytes.length - AUTHENTICATION_TAG_LENGTH,
bytes.length);
if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) {