use of com.owncloud.android.datamodel.EncryptedFolderMetadata in project android by nextcloud.
the class EncryptionTestIT method bigMetadata.
@Test
public void bigMetadata() throws Exception {
DecryptedFolderMetadata decryptedFolderMetadata1 = generateFolderMetadata();
// encrypt
EncryptedFolderMetadata encryptedFolderMetadata1 = encryptFolderMetadata(decryptedFolderMetadata1, privateKey);
// serialize
String encryptedJson = serializeJSON(encryptedFolderMetadata1);
// de-serialize
EncryptedFolderMetadata encryptedFolderMetadata2 = deserializeJSON(encryptedJson, new TypeToken<EncryptedFolderMetadata>() {
});
// decrypt
DecryptedFolderMetadata decryptedFolderMetadata2 = decryptFolderMetaData(encryptedFolderMetadata2, privateKey);
// compare
assertTrue(compareJsonStrings(serializeJSON(decryptedFolderMetadata1), serializeJSON(decryptedFolderMetadata2)));
// prefill with 500
for (int i = 0; i < 500; i++) {
addFile(decryptedFolderMetadata1, i);
}
int max = 505;
for (int i = 500; i < max; i++) {
Log_OC.d(this, "Big metadata: " + i + " of " + max);
addFile(decryptedFolderMetadata1, i);
// encrypt
encryptedFolderMetadata1 = encryptFolderMetadata(decryptedFolderMetadata1, privateKey);
// serialize
encryptedJson = serializeJSON(encryptedFolderMetadata1);
// de-serialize
encryptedFolderMetadata2 = deserializeJSON(encryptedJson, new TypeToken<EncryptedFolderMetadata>() {
});
// decrypt
decryptedFolderMetadata2 = decryptFolderMetaData(encryptedFolderMetadata2, privateKey);
// compare
assertTrue(compareJsonStrings(serializeJSON(decryptedFolderMetadata1), serializeJSON(decryptedFolderMetadata2)));
assertEquals(i + 3, decryptedFolderMetadata1.getFiles().size());
assertEquals(i + 3, decryptedFolderMetadata2.getFiles().size());
}
}
use of com.owncloud.android.datamodel.EncryptedFolderMetadata in project android by nextcloud.
the class UploadFileOperation method encryptedUpload.
// gson cannot handle sparse arrays easily, therefore use hashmap
@SuppressLint("AndroidLintUseSparseArrays")
private RemoteOperationResult encryptedUpload(OwnCloudClient client, OCFile parentFile) {
RemoteOperationResult result = null;
File temporalFile = null;
File originalFile = new File(mOriginalStoragePath);
File expectedFile = null;
FileLock fileLock = null;
long size;
boolean metadataExists = false;
String token = null;
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContext().getContentResolver());
String privateKey = arbitraryDataProvider.getValue(getAccount().name, EncryptionUtils.PRIVATE_KEY);
String publicKey = arbitraryDataProvider.getValue(getAccount().name, EncryptionUtils.PUBLIC_KEY);
try {
// check conditions
result = checkConditions(originalFile);
if (result != null) {
return result;
}
/**
*** E2E ****
*/
token = EncryptionUtils.lockFolder(parentFile, client);
// immediately store it
mUpload.setFolderUnlockToken(token);
uploadsStorageManager.updateUpload(mUpload);
// Update metadata
Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parentFile, client, privateKey, publicKey);
metadataExists = metadataPair.first;
DecryptedFolderMetadata metadata = metadataPair.second;
/**
** E2E ****
*/
// check name collision
RemoteOperationResult collisionResult = checkNameCollision(client, metadata, parentFile.isEncrypted());
if (collisionResult != null) {
result = collisionResult;
return collisionResult;
}
mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
expectedFile = new File(expectedPath);
result = copyFile(originalFile, expectedPath);
if (!result.isSuccess()) {
return result;
}
// Get the last modification date of the file from the file system
String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
/**
*** E2E ****
*/
// Key, always generate new one
byte[] key = EncryptionUtils.generateKey();
// 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("-", "");
while (metadata.getFiles().get(encryptedFileName) != null) {
encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
}
File encryptedTempFile = File.createTempFile("encFile", encryptedFileName);
FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
fileOutputStream.write(encryptedFile.encryptedBytes);
fileOutputStream.close();
/**
*** E2E ****
*/
FileChannel channel = null;
try {
channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
fileLock = channel.tryLock();
} catch (FileNotFoundException e) {
// this basically means that the file is on SD card
// try to copy file to temporary dir if it doesn't exist
String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) + mFile.getRemotePath();
mFile.setStoragePath(temporalPath);
temporalFile = new File(temporalPath);
Files.deleteIfExists(Paths.get(temporalPath));
result = copy(originalFile, temporalFile);
if (result.isSuccess()) {
if (temporalFile.length() == originalFile.length()) {
channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
fileLock = channel.tryLock();
} else {
result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
}
}
}
try {
size = channel.size();
} catch (IOException e1) {
size = new File(mFile.getStoragePath()).length();
}
for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
if (ocUpload.getUploadId() == getOCUploadId()) {
ocUpload.setFileSize(size);
uploadsStorageManager.updateUpload(ocUpload);
break;
}
}
// / perform the upload
if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
mUploadOperation = new ChunkedFileUploadRemoteOperation(encryptedTempFile.getAbsolutePath(), mFile.getParentRemotePath() + encryptedFileName, mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, onWifiConnection, token, creationTimestamp, mDisableRetries);
} else {
mUploadOperation = new UploadFileRemoteOperation(encryptedTempFile.getAbsolutePath(), mFile.getParentRemotePath() + encryptedFileName, mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, token, mDisableRetries);
}
for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
}
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
result = mUploadOperation.execute(client);
// location in the Nextcloud local folder
if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
}
if (result.isSuccess()) {
mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
mFile.setRemotePath(parentFile.getRemotePath() + encryptedFileName);
// update metadata
DecryptedFolderMetadata.DecryptedFile decryptedFile = new DecryptedFolderMetadata.DecryptedFile();
DecryptedFolderMetadata.Data data = new DecryptedFolderMetadata.Data();
data.setFilename(mFile.getDecryptedFileName());
data.setMimetype(mFile.getMimeType());
data.setKey(EncryptionUtils.encodeBytesToBase64String(key));
decryptedFile.setEncrypted(data);
decryptedFile.setInitializationVector(EncryptionUtils.encodeBytesToBase64String(iv));
decryptedFile.setAuthenticationTag(encryptedFile.authenticationTag);
metadata.getFiles().put(encryptedFileName, decryptedFile);
EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata, privateKey);
String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
// upload metadata
EncryptionUtils.uploadMetadata(parentFile, serializedFolderMetadata, token, client, metadataExists);
// unlock
result = EncryptionUtils.unlockFolder(parentFile, client, token);
if (result.isSuccess()) {
token = null;
}
}
} catch (FileNotFoundException e) {
Log_OC.d(TAG, mFile.getStoragePath() + " not exists anymore");
result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
} catch (OverlappingFileLockException e) {
Log_OC.d(TAG, "Overlapping file lock exception");
result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
} catch (Exception e) {
result = new RemoteOperationResult(e);
} finally {
mUploadStarted.set(false);
if (fileLock != null) {
try {
fileLock.release();
} catch (IOException e) {
Log_OC.e(TAG, "Failed to unlock file with path " + mFile.getStoragePath());
}
}
if (temporalFile != null && !originalFile.equals(temporalFile)) {
temporalFile.delete();
}
if (result == null) {
result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
}
logResult(result, mFile.getStoragePath(), mFile.getRemotePath());
}
if (result.isSuccess()) {
handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
} else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
}
// unlock must be done always
if (token != null) {
RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parentFile, client, token);
if (!unlockFolderResult.isSuccess()) {
return unlockFolderResult;
}
}
// delete temporal file
if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
}
return result;
}
use of com.owncloud.android.datamodel.EncryptedFolderMetadata in project android by nextcloud.
the class CreateFolderOperation method encryptedCreate.
private RemoteOperationResult encryptedCreate(OCFile parent, OwnCloudClient client) {
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
String privateKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY);
String publicKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY);
String token = null;
Boolean metadataExists;
DecryptedFolderMetadata metadata;
String encryptedRemotePath = null;
String filename = new File(remotePath).getName();
try {
// lock folder
token = EncryptionUtils.lockFolder(parent, client);
// get metadata
Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parent, client, privateKey, publicKey);
metadataExists = metadataPair.first;
metadata = metadataPair.second;
// check if filename already exists
if (isFileExisting(metadata, filename)) {
return new RemoteOperationResult(RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS);
}
// generate new random file name, check if it exists in metadata
String encryptedFileName = createRandomFileName(metadata);
encryptedRemotePath = parent.getRemotePath() + encryptedFileName;
RemoteOperationResult result = new CreateFolderRemoteOperation(encryptedRemotePath, true, token).execute(client);
if (result.isSuccess()) {
// update metadata
metadata.getFiles().put(encryptedFileName, createDecryptedFile(filename));
EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata, privateKey);
String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
// upload metadata
EncryptionUtils.uploadMetadata(parent, serializedFolderMetadata, token, client, metadataExists);
// unlock folder
if (token != null) {
RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
if (unlockFolderResult.isSuccess()) {
token = null;
} else {
// TODO do better
throw new RuntimeException("Could not unlock folder!");
}
}
RemoteOperationResult remoteFolderOperationResult = new ReadFolderRemoteOperation(encryptedRemotePath).execute(client);
createdRemoteFolder = (RemoteFile) remoteFolderOperationResult.getData().get(0);
OCFile newDir = createRemoteFolderOcFile(parent, filename, createdRemoteFolder);
getStorageManager().saveFile(newDir);
RemoteOperationResult encryptionOperationResult = new ToggleEncryptionRemoteOperation(newDir.getLocalId(), newDir.getRemotePath(), true).execute(client);
if (!encryptionOperationResult.isSuccess()) {
throw new RuntimeException("Error creating encrypted subfolder!");
}
} else {
// revert to sane state in case of any error
Log_OC.e(TAG, remotePath + " hasn't been created");
}
return result;
} catch (Exception e) {
if (!EncryptionUtils.unlockFolder(parent, client, token).isSuccess()) {
throw new RuntimeException("Could not clean up after failing folder creation!");
}
// remove folder
if (encryptedRemotePath != null) {
RemoteOperationResult removeResult = new RemoveRemoteEncryptedFileOperation(encryptedRemotePath, parent.getLocalId(), user.toPlatformAccount(), context, filename).execute(client);
if (!removeResult.isSuccess()) {
throw new RuntimeException("Could not clean up after failing folder creation!");
}
}
// TODO do better
return new RemoteOperationResult(e);
} finally {
// unlock folder
if (token != null) {
RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
if (!unlockFolderResult.isSuccess()) {
// TODO do better
throw new RuntimeException("Could not unlock folder!");
}
}
}
}
use of com.owncloud.android.datamodel.EncryptedFolderMetadata in project android by nextcloud.
the class EncryptionUtils method encryptFolderMetadata.
/*
METADATA
*/
/**
* Encrypt folder metaData
*
* @param decryptedFolderMetadata folder metaData to encrypt
* @return EncryptedFolderMetadata encrypted folder metadata
*/
public static EncryptedFolderMetadata encryptFolderMetadata(DecryptedFolderMetadata decryptedFolderMetadata, String privateKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
HashMap<String, EncryptedFolderMetadata.EncryptedFile> files = new HashMap<>();
EncryptedFolderMetadata encryptedFolderMetadata = new EncryptedFolderMetadata(decryptedFolderMetadata.getMetadata(), files);
// Encrypt each file in "files"
for (Map.Entry<String, DecryptedFolderMetadata.DecryptedFile> entry : decryptedFolderMetadata.getFiles().entrySet()) {
String key = entry.getKey();
DecryptedFolderMetadata.DecryptedFile decryptedFile = entry.getValue();
EncryptedFolderMetadata.EncryptedFile encryptedFile = new EncryptedFolderMetadata.EncryptedFile();
encryptedFile.setInitializationVector(decryptedFile.getInitializationVector());
encryptedFile.setMetadataKey(decryptedFile.getMetadataKey());
encryptedFile.setAuthenticationTag(decryptedFile.getAuthenticationTag());
byte[] decryptedMetadataKey = EncryptionUtils.decodeStringToBase64Bytes(EncryptionUtils.decryptStringAsymmetric(decryptedFolderMetadata.getMetadata().getMetadataKeys().get(encryptedFile.getMetadataKey()), privateKey));
// encrypt
String dataJson = EncryptionUtils.serializeJSON(decryptedFile.getEncrypted());
encryptedFile.setEncrypted(EncryptionUtils.encryptStringSymmetric(dataJson, decryptedMetadataKey));
files.put(key, encryptedFile);
}
return encryptedFolderMetadata;
}
use of com.owncloud.android.datamodel.EncryptedFolderMetadata in project android by nextcloud.
the class EncryptionUtils method decryptFolderMetaData.
/*
* decrypt folder metaData with private key
*/
public static DecryptedFolderMetadata decryptFolderMetaData(EncryptedFolderMetadata encryptedFolderMetadata, String privateKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
HashMap<String, DecryptedFolderMetadata.DecryptedFile> files = new HashMap<>();
DecryptedFolderMetadata decryptedFolderMetadata = new DecryptedFolderMetadata(encryptedFolderMetadata.getMetadata(), files);
for (Map.Entry<String, EncryptedFolderMetadata.EncryptedFile> entry : encryptedFolderMetadata.getFiles().entrySet()) {
String key = entry.getKey();
EncryptedFolderMetadata.EncryptedFile encryptedFile = entry.getValue();
DecryptedFolderMetadata.DecryptedFile decryptedFile = new DecryptedFolderMetadata.DecryptedFile();
decryptedFile.setInitializationVector(encryptedFile.getInitializationVector());
decryptedFile.setMetadataKey(encryptedFile.getMetadataKey());
decryptedFile.setAuthenticationTag(encryptedFile.getAuthenticationTag());
byte[] decryptedMetadataKey = EncryptionUtils.decodeStringToBase64Bytes(EncryptionUtils.decryptStringAsymmetric(decryptedFolderMetadata.getMetadata().getMetadataKeys().get(encryptedFile.getMetadataKey()), privateKey));
// decrypt
String dataJson = EncryptionUtils.decryptStringSymmetric(encryptedFile.getEncrypted(), decryptedMetadataKey);
decryptedFile.setEncrypted(EncryptionUtils.deserializeJSON(dataJson, new TypeToken<DecryptedFolderMetadata.Data>() {
}));
files.put(key, decryptedFile);
}
return decryptedFolderMetadata;
}
Aggregations