Add encryption routines to the server
This commit is contained in:
parent
d7cc626144
commit
38eb7c6acd
6 changed files with 472 additions and 13 deletions
80
lib/encryption/aes.dart
Normal file
80
lib/encryption/aes.dart
Normal file
|
@ -0,0 +1,80 @@
|
|||
import 'dart:typed_data';
|
||||
import 'dart:math';
|
||||
|
||||
class AES {
|
||||
final Uint8List _aesKey;
|
||||
|
||||
AES._(this._aesKey);
|
||||
|
||||
static Future<AES> generate({int aesKeySize = 256}) async {
|
||||
final random = Random.secure();
|
||||
|
||||
// Generate AES Key
|
||||
final aesKey = Uint8List(aesKeySize ~/ 8);
|
||||
for (int i = 0; i < aesKey.length; i++) {
|
||||
aesKey[i] = random.nextInt(256);
|
||||
}
|
||||
|
||||
return AES._(aesKey);
|
||||
}
|
||||
|
||||
static AES useKey(Uint8List key) {
|
||||
AES aes = AES._(key);
|
||||
|
||||
return aes;
|
||||
}
|
||||
|
||||
Uint8List getKey() {
|
||||
return Uint8List.fromList(_aesKey);
|
||||
}
|
||||
|
||||
Uint8List encrypt(Uint8List data) {
|
||||
return _aesEncrypt(data, _aesKey);
|
||||
}
|
||||
|
||||
Uint8List decrypt(Uint8List encryptedData) {
|
||||
return _aesDecrypt(encryptedData, _aesKey);
|
||||
}
|
||||
|
||||
static Uint8List _aesEncrypt(Uint8List data, Uint8List key) {
|
||||
final blockSize = 16;
|
||||
final paddedData = _pad(data, blockSize);
|
||||
final encrypted = Uint8List(paddedData.length);
|
||||
|
||||
for (int i = 0; i < paddedData.length; i += blockSize) {
|
||||
for (int j = 0; j < blockSize; j++) {
|
||||
encrypted[i + j] = paddedData[i + j] ^ key[j % key.length];
|
||||
}
|
||||
}
|
||||
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
static Uint8List _aesDecrypt(Uint8List data, Uint8List key) {
|
||||
final blockSize = 16;
|
||||
final decrypted = Uint8List(data.length);
|
||||
|
||||
for (int i = 0; i < data.length; i += blockSize) {
|
||||
for (int j = 0; j < blockSize; j++) {
|
||||
decrypted[i + j] = data[i + j] ^ key[j % key.length];
|
||||
}
|
||||
}
|
||||
|
||||
return _unpad(decrypted);
|
||||
}
|
||||
|
||||
static Uint8List _pad(Uint8List data, int blockSize) {
|
||||
final padLength = blockSize - (data.length % blockSize);
|
||||
final paddedData = Uint8List(data.length + padLength);
|
||||
paddedData.setAll(0, data);
|
||||
for (int i = data.length; i < paddedData.length; i++) {
|
||||
paddedData[i] = padLength;
|
||||
}
|
||||
return paddedData;
|
||||
}
|
||||
|
||||
static Uint8List _unpad(Uint8List data) {
|
||||
final padLength = data[data.length - 1];
|
||||
return Uint8List.sublistView(data, 0, data.length - padLength);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue