-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.dart
84 lines (66 loc) · 2.44 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import 'package:cryptography/cryptography.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:args/args.dart';
import 'dart:typed_data';
import 'dart:convert';
import 'dart:io';
void main(List<String> argv) async {
var decoder = utf8.fuse(base64);
var parser = ArgParser();
parser.addOption('license-file', abbr: 'f', mandatory: true);
parser.addOption('license-key', abbr: 'k', mandatory: true);
parser.addOption('public-key', abbr: 'p', mandatory: true);
var args = parser.parse(argv);
// Read and parse license file
var cert = await File(args['license-file']).readAsString();
var enc = cert.replaceFirst('-----BEGIN LICENSE FILE-----', "")
.replaceFirst('-----END LICENSE FILE-----', "")
.replaceAll('\n', '');
var dec = decoder.decode(enc);
var lic = json.decode(dec);
// Assert algorithm is supported
if (lic['alg'] != 'aes-256-gcm+ed25519') {
throw new Exception('unsupported license file algorithm');
}
// Verify the license file's signature
bool ok;
try {
var pubkey = SimplePublicKey(hex.decode(args['public-key']), type: KeyPairType.ed25519);
var msg = Uint8List.fromList(utf8.encode("license/" + lic['enc']));
var sig = base64.decode(lic['sig']);
var ed = Ed25519();
ok = await ed.verify(msg, signature: Signature(sig, publicKey: pubkey));
} catch (e) {
throw new Exception('failed to verify license file: $e');
}
if (!ok) {
throw new Exception('invalid license file signature');
}
// Print license file
print("license file was successfully verified!");
print(" > $lic");
// Hash the license key to obtain decryption secret
var digest = sha256.convert(utf8.encode(args['license-key']));
var secret = SecretKey(digest.bytes);
// Decrypt the license file's dataset
String plaintext;
try {
var parts = (lic['enc'] as String).split('.').map((s) => base64.decode(s)).toList();
var ciphertext = parts[0];
var nonce = parts[1];
var mac = parts[2];
var aes = AesGcm.with256bits(nonceLength: 16);
var bytes = await aes.decrypt(
SecretBox(ciphertext, mac: Mac(mac), nonce: nonce),
secretKey: secret,
);
plaintext = utf8.decode(bytes);
} catch (e) {
throw new Exception('failed to decrypt license file: $e');
}
// Print decrypted dataset
var data = json.decode(plaintext);
print("license file was successfully decrypted!");
print(" > $data");
}