feat: Also hash the file on encryption and decryption

This commit is contained in:
PapaTutuWawa 2022-10-05 15:05:43 +02:00
parent 35138e102e
commit 31f33a0413
6 changed files with 167 additions and 30 deletions

View File

@ -61,15 +61,21 @@ class _MyHomePageState extends State<MyHomePage> {
return;
}
final start = DateTime.now();
final path = result.files.single.path;
await MoxplatformPlugin.crypto.encryptFile(
final enc = await MoxplatformPlugin.crypto.encryptFile(
path!,
path + '.enc',
Uint8List.fromList(List.filled(32, 1)),
Uint8List.fromList(List.filled(16, 2)),
CipherAlgorithm.aes256CbcPkcs7,
'SHA-256',
);
print('DONE');
final end = DateTime.now();
final diff = end.millisecondsSinceEpoch - start.millisecondsSinceEpoch;
print('TIME: ${diff / 1000}s');
print('DONE (${enc != null})');
final lengthEnc = await File(path + ".enc").length();
final lengthOrig = await File(path).length();
print('Encrypted file is $lengthEnc Bytes large (Orig $lengthOrig)');
@ -80,6 +86,7 @@ class _MyHomePageState extends State<MyHomePage> {
Uint8List.fromList(List.filled(32, 1)),
Uint8List.fromList(List.filled(16, 2)),
CipherAlgorithm.aes256CbcPkcs7,
'SHA-256',
);
print('DONE');

View File

@ -0,0 +1,34 @@
package me.polynom.moxplatform_android;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashedFileOutputStream extends FileOutputStream {
public MessageDigest digest;
public HashedFileOutputStream(String name, String hashSpec) throws FileNotFoundException, NoSuchAlgorithmException {
super(name);
digest = MessageDigest.getInstance(hashSpec);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
super.write(b, off, len);
digest.update(b, off, len);
}
public String getHexHash() {
StringBuffer result = new StringBuffer();
for (byte b : digest.digest()) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
public byte[] getHash() {
return digest.digest();
}
}

View File

@ -6,7 +6,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
@ -14,8 +13,9 @@ import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.crypto.Cipher;
@ -154,8 +154,9 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
byte[] key = (byte[]) args.get(2);
byte[] iv = (byte[]) args.get(3);
int algorithm = (int) args.get(4);
String hashSpec = (String) args.get(5);
result.success(encryptFile(src, dest, key, iv, algorithm));
result.success(encryptFile(src, dest, key, iv, algorithm, hashSpec));
}
});
encryptionThread.start();
@ -170,12 +171,26 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
byte[] key = (byte[]) args.get(2);
byte[] iv = (byte[]) args.get(3);
int algorithm = (int) args.get(4);
String hashSpec = (String) args.get(5);
result.success(decryptFile(src, dest, key, iv, algorithm));
result.success(decryptFile(src, dest, key, iv, algorithm, hashSpec));
}
});
decryptionThread.start();
break;
case "hashFile":
Thread hashingThread = new Thread(new Runnable() {
@Override
public void run() {
ArrayList args = (ArrayList) call.arguments;
String src = (String) args.get(0);
String hashSpec = (String) args.get(1);
result.success(hashFile(src, hashSpec));
}
});
hashingThread.start();
break;
default:
result.notImplemented();
break;
@ -227,25 +242,28 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
}
}
public boolean encryptFile(String src, String dest, byte[] key, byte[] iv, int algorithm) {
public HashMap<String, byte[]> encryptFile(String src, String dest, byte[] key, byte[] iv, int algorithm, String hashSpec) {
String spec = getCipherSpecFromInteger(algorithm);
if (spec.isEmpty()) {
return false;
return null;
}
// Shamelessly stolen from https://github.com/hugo-pcl/native-crypto-flutter/pull/3
byte[] buffer = new byte[8096];
SecretKeySpec sk = new SecretKeySpec(key, spec);
try {
MessageDigest md = MessageDigest.getInstance(hashSpec);
Cipher cipher = Cipher.getInstance(spec);
cipher.init(Cipher.ENCRYPT_MODE, sk, new IvParameterSpec(iv));
FileInputStream fin = new FileInputStream(src);
FileOutputStream fout = new FileOutputStream(dest);
HashedFileOutputStream fout = new HashedFileOutputStream(dest, hashSpec);
CipherOutputStream cout = new CipherOutputStream(fout, cipher);
int len = 0;
int bufLen = 0;
while (true) {
len = fin.read(buffer);
if (len != 0 && len > 0) {
md.update(buffer, 0, len);
cout.write(buffer, 0, len);
} else {
break;
@ -254,17 +272,21 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
cout.flush();
cout.close();
fin.close();
return true;
return new HashMap<String, byte[]>() {{
put("plaintext_hash", md.digest());
put("ciphertext_hash", fout.getHash());
}};
} catch (Exception ex) {
Log.d(TAG, "ENC: " + ex.getMessage());
return false;
return null;
}
}
public boolean decryptFile(String src, String dest, byte[] key, byte[] iv, int algorithm) {
public HashMap<String, byte[]> decryptFile(String src, String dest, byte[] key, byte[] iv, int algorithm, String hashSpec) {
String spec = getCipherSpecFromInteger(algorithm);
if (spec.isEmpty()) {
return false;
return null;
}
// Shamelessly stolen from https://github.com/hugo-pcl/native-crypto-flutter/pull/3
@ -274,14 +296,16 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
Cipher cipher = Cipher.getInstance(spec);
cipher.init(Cipher.DECRYPT_MODE, sk, new IvParameterSpec(iv));
FileInputStream fin = new FileInputStream(src);
FileOutputStream fout = new FileOutputStream(dest);
HashedFileOutputStream fout = new HashedFileOutputStream(dest, hashSpec);
CipherOutputStream cout = new CipherOutputStream(fout, cipher);
MessageDigest md = MessageDigest.getInstance(hashSpec);
Log.d(TAG, "Reading from " + src + ", writing to " + dest);
int len = 0;
while (true) {
len = fin.read(buffer);
if (len != 0 && len > 0) {
cout.write(buffer, 0, len);
md.update(buffer, 0, len);
} else {
break;
}
@ -289,10 +313,36 @@ public class MoxplatformAndroidPlugin extends BroadcastReceiver implements Flutt
cout.flush();
cout.close();
fin.close();
return true;
return new HashMap<String, byte[]>() {{
put("plaintext_hash", md.digest());
put("ciphertext_hash", fout.getHash());
}};
} catch (Exception ex) {
Log.d(TAG, "DEC: " + ex.getMessage());
return false;
return null;
}
}
public byte[] hashFile(String src, String algorithm) {
byte[] buffer = new byte[8096];
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
FileInputStream fin = new FileInputStream(src);
int len = 0;
while (true) {
len = fin.read(buffer);
if (len != 0 && len > 0) {
md.update(buffer, 0, len);
} else {
break;
}
}
return md.digest();
} catch (Exception ex) {
Log.d(TAG, "Hash: " + ex.getMessage());
return null;
}
}
}

View File

@ -6,26 +6,52 @@ class AndroidCryptographyImplementation extends CryptographyImplementation {
final _methodChannel = const MethodChannel('me.polynom.moxplatform_android');
@override
Future<bool> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm) async {
final result = await _methodChannel.invokeMethod<bool>('encryptFile', [
Future<CryptographyResult?> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec) async {
final dynamic resultRaw = await _methodChannel.invokeMethod<dynamic>('encryptFile', [
sourcePath,
destPath,
key,
iv,
algorithm.toInt(),
hashSpec,
]);
return result ?? false;
if (resultRaw == null) return null;
final result = Map<String, Uint8List>.from(resultRaw as Map<String, dynamic>);
return CryptographyResult(
result['plaintext_hash']!,
result['ciphertext_hash']!,
);
}
@override
Future<bool> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm) async {
final result = await _methodChannel.invokeMethod<bool>('decryptFile', [
Future<CryptographyResult?> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec) async {
final dynamic resultRaw = await _methodChannel.invokeMethod<dynamic>('decryptFile', [
sourcePath,
destPath,
key,
iv,
algorithm.toInt(),
hashSpec,
]);
return result ?? false;
if (resultRaw == null) return null;
final result = Map<String, Uint8List>.from(resultRaw as Map<String, dynamic>);
return CryptographyResult(
result['plaintext_hash']!,
result['ciphertext_hash']!,
);
}
@override
Future<Uint8List?> hashFile(String path, String hashSpec) async {
final dynamic resultsRaw = await _methodChannel.invokeMethod<dynamic>('hashFile', [
path,
hashSpec,
]);
if (resultsRaw == null) return null;
return resultsRaw as Uint8List;
}
}

View File

@ -16,17 +16,32 @@ extension CipherAlgorithmToIntExtension on CipherAlgorithm {
}
}
class CryptographyResult {
const CryptographyResult(this.plaintextHash, this.ciphertextHash);
final Uint8List plaintextHash;
final Uint8List ciphertextHash;
}
/// Wrapper around platform-native cryptography APIs
abstract class CryptographyImplementation {
/// Encrypt the file at [sourcePath] using [algorithm] and write the result back to
/// [destPath]. Note that this function runs off-thread as to not block the UI thread.
/// [destPath]. [hashSpec] is the name of the Hash function to use, i.e. "SHA-256".
/// Note that this function runs off-thread as to not block the UI thread.
///
/// Resolves to true if the encryption was successful. Resolves to fale on failure.
Future<bool> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm);
Future<CryptographyResult?> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec);
/// Decrypt the file at [sourcePath] using [algorithm] and write the result back to
/// [destPath]. Note that this function runs off-thread as to not block the UI thread.
/// [destPath]. [hashSpec] is the name of the Hash function to use, i.e. "SHA-256".
/// Note that this function runs off-thread as to not block the UI thread.
///
/// Resolves to true if the encryption was successful. Resolves to fale on failure.
Future<bool> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm);
Future<CryptographyResult?> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec);
/// Hashes the file at [path] using the Hash function with name [hashSpec].
/// Note that this function runs off-thread as to not block the UI thread.
///
/// Returns the hash of the file.
Future<Uint8List?> hashFile(String path, String hashSpec);
}

View File

@ -3,12 +3,17 @@ import 'package:moxplatform_platform_interface/src/crypto.dart';
class StubCryptographyImplementation extends CryptographyImplementation {
@override
Future<bool> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm) async {
return false;
Future<CryptographyResult?> encryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec) async {
return null;
}
@override
Future<bool> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm) async {
return false;
Future<CryptographyResult?> decryptFile(String sourcePath, String destPath, Uint8List key, Uint8List iv, CipherAlgorithm algorithm, String hashSpec) async {
return null;
}
@override
Future<Uint8List?> hashFile(String path, String hashSpec) async {
return null;
}
}