[flutter] 플러터에서 path_provider를 이용하여 파일 암호화 방식 설정하기
소개
플러터는 크로스 플랫폼 어플리케이션 개발을 위한 프레임워크로, 다양한 기기에서 동작하는 앱을 만들 수 있습니다. 파일을 암호화해서 저장하고자 할 때, path_provider 패키지를 사용하여 플랫폼별로 파일 시스템에 접근할 수 있습니다. 이번 포스트에서는 path_provider를 이용하여 파일 암호화 방식을 설정하는 방법에 대해 알아보겠습니다.
단계별 설명
1. path_provider 패키지 추가
프로젝트의 pubspec.yaml 파일을 열고 dependencies 섹션에 path_provider 패키지를 추가합니다.
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.5
2. 앱의 파일 시스템 경로 가져오기
path_provider 패키지를 사용하여 앱의 파일 시스템 경로를 가져올 수 있습니다. 아래와 같은 코드로 앱의 디렉토리 경로를 가져올 수 있습니다.
import 'package:path_provider/path_provider.dart';
import 'dart:io';
Future<String> getApplicationDocumentsDirectoryPath() async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
3. 파일 암호화 및 저장
암호화된 파일을 저장하기 위해, crypto 패키지를 사용할 수 있습니다. 다음과 같은 코드로 파일을 암호화하여 저장할 수 있습니다.
import 'package:path/path.dart' as path;
import 'package:crypto/crypto.dart';
import 'dart:io';
Future<void> encryptAndSaveFile(File file, String key) async {
final bytes = await file.readAsBytes();
final encryptedBytes = encrypt(bytes, key);
final directoryPath = await getApplicationDocumentsDirectoryPath();
final encryptedFilePath = path.join(directoryPath, 'encrypted_file');
final encryptedFile = File(encryptedFilePath);
await encryptedFile.writeAsBytes(encryptedBytes);
}
4. 파일 복호화 및 사용
암호화된 파일을 복호화하여 사용하고자 할 때, 다음과 같은 코드로 파일을 복호화할 수 있습니다.
import 'package:path/path.dart' as path;
import 'package:crypto/crypto.dart';
import 'dart:io';
Future<File> decryptAndLoadFile(String key) async {
final directoryPath = await getApplicationDocumentsDirectoryPath();
final encryptedFilePath = path.join(directoryPath, 'encrypted_file');
final encryptedFile = File(encryptedFilePath);
final encryptedBytes = await encryptedFile.readAsBytes();
final decryptedBytes = decrypt(encryptedBytes, key);
final decryptedFilePath = path.join(directoryPath, 'decrypted_file');
final decryptedFile = File(decryptedFilePath);
await decryptedFile.writeAsBytes(decryptedBytes);
return decryptedFile;
}
요약
이번 포스트에서는 path_provider 패키지를 이용하여 플러터 앱에서 파일 암호화 방식을 설정하는 방법에 대해 살펴보았습니다. 파일 시스템 경로를 가져오는 방법과 파일을 암호화하여 저장하고 복호화하여 사용하는 방법을 소개했습니다. 이를 활용하여 앱의 보안성을 증가시킬 수 있습니다.