Encrypt.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. import 'dart:convert';
  2. import 'dart:ffi';
  3. import 'dart:io';
  4. import 'dart:math';
  5. import 'dart:typed_data';
  6. import 'package:ffi/ffi.dart';
  7. import 'package:path_provider/path_provider.dart';
  8. // TODO: 让_Block的size可以设置
  9. class Block16 extends Struct {
  10. @Array(16) external Array<Uint8> buf;
  11. }
  12. class Block32 extends Struct {
  13. @Array(32) external Array<Uint8> buf;
  14. }
  15. extension ExBlock16 on Pointer<Block16> {
  16. Pointer<Uint8> get p => Pointer.fromAddress(address);
  17. Uint8List get list => p.asTypedList(16);
  18. }
  19. extension ExBlock32 on Pointer<Block32> {
  20. Pointer<Uint8> get p => Pointer.fromAddress(address);
  21. Uint8List get list => p.asTypedList(32);
  22. void copy(Pointer<Block32> key) {
  23. for (int i=0; i<32; ++i) {
  24. key.ref.buf[i]=1;
  25. }
  26. }
  27. }
  28. class SM2Point extends Struct {
  29. external Block32 x, y;
  30. }
  31. extension ExSM2Point on Pointer<SM2Point> {
  32. Pointer<Block32> get x => Pointer.fromAddress(address);
  33. Pointer<Block32> get y => x.elementAt(1);
  34. }
  35. class Block {
  36. Block(this.size): p = malloc.allocate(size);
  37. final int size;
  38. final Pointer<Uint8> p;
  39. Uint8List get list => p.asTypedList(size);
  40. // Pointer<Uint8> elementAt(int index) => p.elementAt(index);
  41. // int operator[](int index) => p[index];
  42. // void operator[]=(int index, int value) => p[index] = value;
  43. }
  44. class SM2Key extends Struct {
  45. external SM2Point publicKey;
  46. external Block32 privateKey;
  47. }
  48. extension ExSM2Key on Pointer<SM2Key> {
  49. Pointer<SM2Point> get publicKey => Pointer.fromAddress(address);
  50. Pointer<Block32> get privateKey => Pointer.fromAddress(address + 64);
  51. void generate() {
  52. assert(gm.sm2KeyGenerate(this) == 1);
  53. }
  54. void copy(Pointer<SM2Key> key) {
  55. }
  56. }
  57. class SM4cbcCtx extends Struct {
  58. @Array(32)
  59. external Array<Uint32> sm4Key;
  60. external Block16 iv, block;
  61. @Size()
  62. external int blockNBytes;
  63. }
  64. extension ExSM4CBCCtx on Pointer<SM4cbcCtx> {
  65. Pointer<Uint32> get sm4Key => Pointer.fromAddress(address);
  66. Pointer<Block16> get iv => Pointer.fromAddress(sm4Key.elementAt(32).address);
  67. Pointer<Block16> get block => iv.elementAt(1);
  68. int get size => ref.blockNBytes;
  69. }
  70. final _lib = DynamicLibrary.open("libgmssl.so");
  71. final gm = GmSSL._();
  72. final stderrAddress = _lib.lookup<UintPtr>("stderr").value;
  73. final stdoutAddress = _lib.lookup<UintPtr>("stdout").value;
  74. final _fputs = _lib.lookupFunction<Int Function(Pointer<Utf8>, UintPtr),
  75. int Function(Pointer<Utf8>, int)>("fputs");
  76. int fputs(String str, int stream) {
  77. return _fputs(str.toNativeUtf8(), stream);
  78. }
  79. final _puts = _lib.lookupFunction<Int Function(Pointer<Utf8>),
  80. int Function(Pointer<Utf8>)>("puts");
  81. int puts(String str) {
  82. return _puts(str.toNativeUtf8());
  83. }
  84. final _freopen = _lib.lookupFunction<
  85. UintPtr Function(Pointer<Utf8>, Pointer<Utf8>, UintPtr),
  86. int Function(Pointer<Utf8>, Pointer<Utf8>, int)>("freopen");
  87. int freopen(String path, String mode, int stream) {
  88. return _freopen(path.toNativeUtf8(), mode.toNativeUtf8(), stream);
  89. }
  90. const sm2MaxPlainText = 255;
  91. const sm2MaxCipherTextSize = 366;
  92. class GmSSL {
  93. GmSSL._();
  94. Pointer<SM2Key> newSM2Key() => malloc<SM2Key>();
  95. final _fopen = _lib.lookupFunction<
  96. UintPtr Function(Pointer<Utf8>, Pointer<Utf8>),
  97. int Function(Pointer<Utf8>, Pointer<Utf8>)
  98. >("fopen");
  99. final fflush = _lib.lookupFunction<Uint32 Function(UintPtr),
  100. int Function(int)>("fflush");
  101. final fclose = _lib.lookupFunction<Uint32 Function(UintPtr),
  102. int Function(int)>("fclose");
  103. int fopen(String path, String mode) {
  104. return _fopen(path.toNativeUtf8(), mode.toNativeUtf8());
  105. }
  106. final sm2KeyGenerate = _lib.lookupFunction<Int Function(Pointer<SM2Key>),
  107. int Function(Pointer<SM2Key>)>("sm2_key_generate");
  108. // TODO: something wrong ...
  109. final sm2PrivateKeyInfoEncryptToDER = _lib.lookupFunction<
  110. Int Function(SM2Key, Pointer<Utf8>, Pointer<Pointer<Uint8>>, Pointer<Size>),
  111. int Function(SM2Key, Pointer<Utf8>, Pointer<Pointer<Uint8>>, Pointer<Size>)
  112. >("sm2_private_key_info_encrypt_to_der");
  113. // TODO: unimplemented ...
  114. final sm2PrivateKeyInfoDecryptFromDER = _lib.lookupFunction<
  115. Int Function(SM2Key, Pointer<Pointer<Uint8>>, Pointer<Size>,
  116. Pointer<Utf8>, Pointer<Pointer<Uint8>>, Pointer<Size>),
  117. int Function(SM2Key, Pointer<Pointer<Uint8>>, Pointer<Size>,
  118. Pointer<Utf8>, Pointer<Pointer<Uint8>>, Pointer<Size>)
  119. >("sm2_private_key_info_decrypt_from_der");
  120. final sm2PrivateKeyInfoEncryptToPEM = _lib.lookupFunction<
  121. Int Function(Pointer<SM2Key>, Pointer<Utf8>, UintPtr),
  122. int Function(Pointer<SM2Key>, Pointer<Utf8>, int)
  123. >("sm2_private_key_info_encrypt_to_pem");
  124. final sm2PrivateKeyInfoDecryptFromPEM = _lib.lookupFunction<
  125. Int Function(Pointer<SM2Key>, Pointer<Utf8>, UintPtr),
  126. int Function(Pointer<SM2Key>, Pointer<Utf8>, int)
  127. >("sm2_private_key_info_decrypt_from_pem");
  128. final sm2PublicKeyInfoToPEM = _lib.lookupFunction<
  129. Int Function(Pointer<SM2Key>, UintPtr), int Function(Pointer<SM2Key>, int)
  130. >("sm2_public_key_info_to_pem");
  131. final sm2PublicKeyInfoFromPEM = _lib.lookupFunction<
  132. Int Function(Pointer<SM2Key>, UintPtr), int Function(Pointer<SM2Key>, int)
  133. >("sm2_public_key_info_from_pem");
  134. final sm2PublicKeyInfoToDER = _lib.lookupFunction<
  135. Int Function(Pointer<SM2Key>, Pointer<UintPtr>, Pointer<Size>),
  136. int Function(Pointer<SM2Key>, Pointer<UintPtr>, Pointer<Size>)
  137. >("sm2_public_key_info_to_der");
  138. final sm2PublicKeyInfoFromDER = _lib.lookupFunction<
  139. Int Function(Pointer<SM2Key>, Pointer<Pointer<Uint8>>, Pointer<Size>),
  140. int Function(Pointer<SM2Key>, Pointer<Pointer<Uint8>>, Pointer<Size>)
  141. >("sm2_public_key_info_from_der");
  142. final sm2Encrypt = _lib.lookupFunction<
  143. Int Function(Pointer<SM2Key>, Pointer<Uint8>, Size, Pointer<Uint8>, Pointer<Size>),
  144. int Function(Pointer<SM2Key>, Pointer<Uint8>, int, Pointer<Uint8>, Pointer<Size>)
  145. >("sm2_encrypt");
  146. final sm2Decrypt = _lib.lookupFunction<
  147. Int Function(Pointer<SM2Key>, Pointer<Uint8>, Size, Pointer<Uint8>, Pointer<Size>),
  148. int Function(Pointer<SM2Key>, Pointer<Uint8>, int, Pointer<Uint8>, Pointer<Size>)
  149. >("sm2_decrypt");
  150. final sm4cbcEncryptInit = _lib.lookupFunction<
  151. Int Function(Pointer<SM4cbcCtx>, Pointer<Block16>, Pointer<Block16>),
  152. int Function(Pointer<SM4cbcCtx>, Pointer<Block16>, Pointer<Block16>)
  153. >("sm4_cbc_encrypt_init");
  154. final sm4cbcEncryptUpdate = _lib.lookupFunction<
  155. Int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Size, Pointer<Uint8>, Pointer<Size>),
  156. int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, int, Pointer<Uint8>, Pointer<Size>)
  157. >("sm4_cbc_encrypt_update");
  158. final sm4cbcEncryptFinish = _lib.lookupFunction<
  159. Int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Pointer<Size>),
  160. int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Pointer<Size>)
  161. >("sm4_cbc_encrypt_finish");
  162. final sm4cbcDecryptInit = _lib.lookupFunction<
  163. Int Function(Pointer<SM4cbcCtx>, Pointer<Block16>, Pointer<Block16>),
  164. int Function(Pointer<SM4cbcCtx>, Pointer<Block16>, Pointer<Block16>)
  165. >("sm4_cbc_decrypt_init");
  166. final sm4cbcDecryptUpdate = _lib.lookupFunction<
  167. Int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Size, Pointer<Uint8>, Pointer<Size>),
  168. int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, int, Pointer<Uint8>, Pointer<Size>)
  169. >("sm4_cbc_decrypt_update");
  170. final sm4cbcDecryptFinish = _lib.lookupFunction<
  171. Int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Pointer<Size>),
  172. int Function(Pointer<SM4cbcCtx>, Pointer<Uint8>, Pointer<Size>)
  173. >("sm4_cbc_decrypt_finish");
  174. }
  175. Uint8List sm4cbcEncrypt(Uint8List input, Uint8List sm4key, Uint8List iv) {
  176. assert(sm4key.length == 16, "key length error");
  177. assert(iv.length == 16, "key length error");
  178. // print("sm4cbcEncrypt start...");
  179. // print("malloc...");
  180. final ctx = malloc<SM4cbcCtx>();
  181. final key = malloc<Block16>();
  182. final civ = malloc<Block16>();
  183. final inBuf = malloc<Uint8>(4096);
  184. final outBuf = malloc<Uint8>(4196);
  185. final outLen = malloc<Size>();
  186. final output = <int>[];
  187. // print("copy...");
  188. for (int i=0; i<16; ++i) {
  189. key.p[i] = sm4key[i];
  190. }
  191. for (int i=0; i<16; ++i) {
  192. civ.p[i] = iv[i];
  193. }
  194. // print("init...");
  195. assert(gm.sm4cbcEncryptInit(ctx, key, civ) == 1,
  196. "sm4cbcEncryptInit error");
  197. // print("encrypt...");
  198. for (int i=0; i<input.length; i+=4096) {
  199. final j = min(i+4096, input.length), len = j-i;
  200. for (int k=i; k<j; ++k) {
  201. inBuf[k-i] = input[k];
  202. }
  203. assert(gm.sm4cbcEncryptUpdate(ctx, inBuf, len, outBuf, outLen) == 1,
  204. "sm4cbcEncryptUpdate error");
  205. output.addAll(outBuf.asTypedList(outLen.value));
  206. }
  207. assert(gm.sm4cbcEncryptFinish(ctx, outBuf, outLen) == 1,
  208. "sm4cbcEncryptFinish error");
  209. output.addAll(outBuf.asTypedList(outLen.value));
  210. malloc.free(ctx);
  211. malloc.free(key);
  212. malloc.free(civ);
  213. malloc.free(inBuf);
  214. malloc.free(outBuf);
  215. malloc.free(outLen);
  216. // print("sm4cbcEncrypt return...");
  217. return Uint8List.fromList(output);
  218. }
  219. Uint8List sm4cbcDecrypt(Uint8List input, Uint8List sm4key, Uint8List iv) {
  220. assert(sm4key.length == 16, "key length error");
  221. assert(iv.length == 16, "key length error");
  222. // print("sm4cbcDecrypt start...");
  223. final ctx = malloc<SM4cbcCtx>();
  224. final key = malloc<Block16>();
  225. final civ = malloc<Block16>();
  226. final inBuf = malloc<Uint8>(4096);
  227. final outBuf = malloc<Uint8>(4196);
  228. final outLen = malloc<Size>();
  229. final output = <int>[];
  230. for (int i=0; i<16; ++i) {
  231. key.p[i] = sm4key[i];
  232. }
  233. for (int i=0; i<16; ++i) {
  234. civ.p[i] = iv[i];
  235. }
  236. assert(gm.sm4cbcDecryptInit(ctx, key, civ) == 1,
  237. "sm4cbcDecryptInit error");
  238. for (int i=0; i<input.length; i+=4096) {
  239. final j = min(i+4096, input.length), len = j-i;
  240. for (int k=i; k<j; ++k) {
  241. inBuf[k-i] = input[k];
  242. }
  243. assert(gm.sm4cbcDecryptUpdate(ctx, inBuf, len, outBuf, outLen) == 1,
  244. "sm4cbcEncryptUpdate error");
  245. output.addAll(outBuf.asTypedList(outLen.value));
  246. }
  247. assert(gm.sm4cbcDecryptFinish(ctx, outBuf, outLen) == 1,
  248. "sm4cbcDecryptFinish error");
  249. output.addAll(outBuf.asTypedList(outLen.value));
  250. malloc.free(ctx);
  251. malloc.free(key);
  252. malloc.free(civ);
  253. malloc.free(inBuf);
  254. malloc.free(outBuf);
  255. malloc.free(outLen);
  256. // print("sm4cbcDecrypt return...");
  257. return Uint8List.fromList(output);
  258. }
  259. Uint8List sm2PublicKeyInfoToDER(Pointer<SM2Key> key) {
  260. final buf = malloc<Uint8>(512);
  261. final p = malloc<UintPtr>(1);
  262. p.value = buf.address;
  263. final len = malloc<Size>(1);
  264. len.value = 0;
  265. assert(gm.sm2PublicKeyInfoToDER(key, p, len) == 1);
  266. assert(len.value >= 0 && len.value < 512, "error: len.value == ${len.value}");
  267. final res = buf.asTypedList(len.value);
  268. malloc.free(buf);
  269. malloc.free(len);
  270. malloc.free(p);
  271. return res;
  272. }
  273. int sm2PublicKeyInfoFromDER(Pointer<SM2Key> key, Uint8List der) {
  274. final buf = malloc<Uint8>(512);
  275. final len = malloc<Size>();
  276. len.value = der.length;
  277. final p = malloc<Pointer<Uint8>>();
  278. p.value = buf;
  279. for (int i=0; i<der.length; ++i) {
  280. buf[i] = der[i];
  281. }
  282. final res = gm.sm2PublicKeyInfoFromDER(key, p, len);
  283. malloc.free(buf);
  284. malloc.free(p);
  285. malloc.free(len);
  286. return res;
  287. }
  288. // Future<String> get _tempPemPath async =>
  289. // "${(await getTemporaryDirectory()).path}/temp.pem";
  290. // Future<String> sm2PublicKeyInfoToPEMString(SM2Key key) async {
  291. // final path = await _tempPemPath;
  292. // final res = sm2PublicKeyInfoToPEM(key, path);
  293. // assert(res == 1);
  294. // return File(path).readAsStringSync();
  295. // }
  296. int sm2PublicKeyInfoToPEM(Pointer<SM2Key> key, String path) {
  297. final pf = gm.fopen(path, "w");
  298. final res = gm.sm2PublicKeyInfoToPEM(key, pf);
  299. // TODO: 封装一个file类隐式执行fflush & fclose
  300. gm.fflush(pf);
  301. gm.fclose(pf);
  302. return res;
  303. }
  304. int sm2PublicKeyInfoFromPEM(Pointer<SM2Key> key, String path) {
  305. final pf = gm.fopen(path, "r");
  306. assert(pf != 0, "fopen $path failed");
  307. final res = gm.sm2PublicKeyInfoFromPEM(key, pf);
  308. gm.fflush(pf);
  309. gm.fclose(pf);
  310. return res;
  311. }
  312. // Future<int> sm2PublicKeyInfoFromPEMString(SM2Key key, String pem) async {
  313. // final path = await _tempPemPath;
  314. // File file = File(path);
  315. // file.writeAsStringSync(pem);
  316. // return sm2PublicKeyInfoFromPEM(key, path);
  317. // }
  318. // Future<String> sm2PrivateKeyInfoEncryptToPEMString(
  319. // SM2Key key, Pointer<Utf8> pass) async {
  320. // final path = await _tempPemPath;
  321. // final res = sm2PrivateKeyInfoEncryptToPEM(key, pass, path);
  322. // return File(path).readAsStringSync();
  323. // // pf = gm.fopen(savePath, "r");
  324. // // assert(gm.sm2PrivateKeyInfoDecryptFromPEM(key, pass, pf) == 1);
  325. // }
  326. void sm2PrivateKeyInfoEncryptToPEM(Pointer<SM2Key> key, Pointer<Utf8> pass, String path) {
  327. final pf = gm.fopen(path, "w");
  328. assert(pf != 0, "fopen $path failed");
  329. final res = gm.sm2PrivateKeyInfoEncryptToPEM(key, pass, pf);
  330. gm.fflush(pf);
  331. gm.fclose(pf);
  332. assert(res == 1);
  333. }
  334. int sm2PrivateKeyInfoDecryptFromPEM(Pointer<SM2Key> key, Pointer<Utf8> pass, String path) {
  335. final pf = gm.fopen(path, "r");
  336. assert(pf != 0, "fopen $path failed");
  337. final res = gm.sm2PrivateKeyInfoDecryptFromPEM(key, pass, pf);
  338. gm.fflush(pf);
  339. gm.fclose(pf);
  340. return res;
  341. }
  342. Uint8List sm2Encrypt(Pointer<SM2Key> key, Uint8List plaintext) {
  343. final inLen = plaintext.length;
  344. assert(inLen <= sm2MaxPlainText,
  345. "plaintext length > $sm2MaxPlainText");
  346. Pointer<Uint8> input = malloc(sm2MaxPlainText + 1);
  347. Pointer<Uint8> output = malloc(sm2MaxCipherTextSize);
  348. Pointer<Size> outLen = malloc<Size>();
  349. for (int i=0; i<inLen; ++i) {
  350. input[i] = plaintext[i];
  351. }
  352. final res = gm.sm2Encrypt(key, input, inLen, output, outLen);
  353. assert(res == 1);
  354. malloc.free(input);
  355. malloc.free(output);
  356. malloc.free(outLen);
  357. return output.asTypedList(outLen.value);
  358. }
  359. Uint8List sm2Decrypt(Pointer<SM2Key> key, Uint8List ciphertext) {
  360. final inLen = ciphertext.length;
  361. assert(inLen <= sm2MaxCipherTextSize, "ciphertext length > $sm2MaxCipherTextSize");
  362. Pointer<Uint8> input = malloc(sm2MaxCipherTextSize);
  363. Pointer<Uint8> output = malloc(sm2MaxCipherTextSize);
  364. Pointer<Size> outLen = malloc<Size>();
  365. for (int i=0; i<inLen; ++i) {
  366. input[i] = ciphertext[i];
  367. }
  368. final res = gm.sm2Decrypt(key, input, inLen, output, outLen);
  369. assert(res == 1);
  370. malloc.free(input);
  371. malloc.free(output);
  372. malloc.free(outLen);
  373. return output.asTypedList(outLen.value);
  374. }
  375. Uint8List sm2PrivateKeyInfoEncryptToDER(SM2Key key, Pointer<Utf8> pass) {
  376. // throw UnimplementedError("this method run incorrectly");
  377. // TODO: something wrong...
  378. // TODO: 检查使用完成后是否需要清理&释放内存
  379. Pointer<Uint8> buf = malloc.allocate(1024 * sizeOf<Uint8>());
  380. Pointer<Pointer<Uint8>> p = malloc.allocate(sizeOf<Pointer>());
  381. p.value = buf;
  382. Pointer<Size> len = calloc.allocate(sizeOf<Size>());
  383. final res = gm.sm2PrivateKeyInfoEncryptToDER(key, pass, p, len);
  384. assert(res == 1);
  385. final list = buf.asTypedList(len.value);
  386. // TODO: safety clean
  387. malloc.free(buf);
  388. malloc.free(p);
  389. malloc.free(len);
  390. return list;
  391. }