46 lines
1.6 KiB
Dart
46 lines
1.6 KiB
Dart
import 'dart:convert';
|
|
import 'package:login_vault_app/constants.dart';
|
|
|
|
/// XOR cipher keyed by [AppConstants.encryptionKey], then base64-encoded.
|
|
///
|
|
/// Operates on raw bytes so any Unicode content round-trips correctly.
|
|
class Encryptor {
|
|
static List<int> _xorBytes(List<int> input, List<int> key) {
|
|
final out = List<int>.filled(input.length, 0);
|
|
for (var i = 0; i < input.length; i++) {
|
|
out[i] = input[i] ^ key[i % key.length];
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/// Encrypt [plain] -> base64 string using the constant key.
|
|
static String encrypt(String plain) {
|
|
final keyBytes = utf8.encode(AppConstants.encryptionKey);
|
|
final xored = _xorBytes(utf8.encode(plain), keyBytes);
|
|
return base64.encode(xored);
|
|
}
|
|
|
|
/// Decrypt a base64 [cipher] produced by [encrypt].
|
|
static String decrypt(String cipher) {
|
|
final keyBytes = utf8.encode(AppConstants.encryptionKey);
|
|
final xored = _xorBytes(base64.decode(cipher), keyBytes);
|
|
return utf8.decode(xored);
|
|
}
|
|
|
|
/// Encrypt [plain] with a user password (for backup files).
|
|
/// Uses the password bytes as the XOR key so the backup is protected by the
|
|
/// app password, not the in-app constant key.
|
|
static String encryptWithPassword(String plain, String password) {
|
|
final keyBytes = utf8.encode(password);
|
|
final xored = _xorBytes(utf8.encode(plain), keyBytes);
|
|
return base64.encode(xored);
|
|
}
|
|
|
|
/// Decrypt a backup [cipher] produced by [encryptWithPassword].
|
|
static String decryptWithPassword(String cipher, String password) {
|
|
final keyBytes = utf8.encode(password);
|
|
final xored = _xorBytes(base64.decode(cipher), keyBytes);
|
|
return utf8.decode(xored);
|
|
}
|
|
}
|