2021-04-10 18:51:51 +00:00
|
|
|
import 'package:fast_rsa/model/bridge.pb.dart';
|
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import 'dart:io';
|
|
|
|
|
|
|
|
class KeyFileManager {
|
2021-04-10 20:26:38 +00:00
|
|
|
static KeyPair keyPair = KeyPair();
|
|
|
|
|
2021-04-10 18:51:51 +00:00
|
|
|
static Future<String> get _localPath async {
|
|
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
|
|
return directory.path;
|
|
|
|
}
|
|
|
|
|
|
|
|
static Future<File> get _pubKeyFile async {
|
|
|
|
final path = await _localPath;
|
|
|
|
return File('$path/rsa.pub');
|
|
|
|
}
|
|
|
|
|
|
|
|
static Future<File> get _privKeyFile async {
|
|
|
|
final path = await _localPath;
|
|
|
|
return File('$path/rsa');
|
|
|
|
}
|
|
|
|
|
|
|
|
static Future<KeyPair> readKeyPair() async {
|
2021-04-10 20:26:38 +00:00
|
|
|
if (keyPair.hasPublicKey() && keyPair.hasPrivateKey()) {
|
|
|
|
return keyPair;
|
|
|
|
}
|
2021-04-10 18:51:51 +00:00
|
|
|
try {
|
|
|
|
String privKey = await _privKeyFile.then(
|
|
|
|
(file) => file.readAsString(),
|
|
|
|
);
|
|
|
|
String pubKey = await _pubKeyFile.then(
|
|
|
|
(file) => file.readAsString(),
|
|
|
|
);
|
2021-04-10 20:26:38 +00:00
|
|
|
keyPair = KeyPair(
|
2021-04-10 18:51:51 +00:00
|
|
|
privateKey: privKey,
|
|
|
|
publicKey: pubKey,
|
|
|
|
);
|
2021-04-10 20:26:38 +00:00
|
|
|
return keyPair;
|
2021-04-10 18:51:51 +00:00
|
|
|
} catch (e) {
|
|
|
|
print(e);
|
|
|
|
return KeyPair();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static Future<void> writeKeyPair(KeyPair pair) async {
|
2021-04-10 20:26:38 +00:00
|
|
|
keyPair = pair;
|
2021-04-10 18:51:51 +00:00
|
|
|
final File privKeyFile = await _privKeyFile;
|
|
|
|
final File pubKeyFile = await _pubKeyFile;
|
2021-04-10 20:26:38 +00:00
|
|
|
pubKeyFile.writeAsString(keyPair.publicKey);
|
|
|
|
privKeyFile.writeAsString(keyPair.privateKey);
|
2021-04-10 18:51:51 +00:00
|
|
|
}
|
|
|
|
}
|